context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright(c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. using Google.Cloud.Firestore; using System; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; namespace GoogleCloudSamples { public class QueryData { public static string Usage = @"Usage: C:\> dotnet run command YOUR_PROJECT_ID Where command is one of query-create-examples create-query-state create-query-capital simple-queries array-contains-query array-contains-any-query in-query in-query-array collection-group-query chained-query composite-index-chained-query range-query invalid-range-query "; private static async Task QueryCreateExamples(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START fs_query_create_examples] CollectionReference citiesRef = db.Collection("cities"); await citiesRef.Document("SF").SetAsync(new Dictionary<string, object>(){ { "Name", "San Francisco" }, { "State", "CA" }, { "Country", "USA" }, { "Capital", false }, { "Population", 860000 }, { "Regions", new ArrayList{"west_coast", "norcal"} } }); await citiesRef.Document("LA").SetAsync(new Dictionary<string, object>(){ { "Name", "Los Angeles" }, { "State", "CA" }, { "Country", "USA" }, { "Capital", false }, { "Population", 3900000 }, { "Regions", new ArrayList{"west_coast", "socal"} } }); await citiesRef.Document("DC").SetAsync(new Dictionary<string, object>(){ { "Name", "Washington D.C." }, { "State", null }, { "Country", "USA" }, { "Capital", true }, { "Population", 680000 }, { "Regions", new ArrayList{"east_coast"} } }); await citiesRef.Document("TOK").SetAsync(new Dictionary<string, object>(){ { "Name", "Tokyo" }, { "State", null }, { "Country", "Japan" }, { "Capital", true }, { "Population", 9000000 }, { "Regions", new ArrayList{"kanto", "honshu"} } }); await citiesRef.Document("BJ").SetAsync(new Dictionary<string, object>(){ { "Name", "Beijing" }, { "State", null }, { "Country", "China" }, { "Capital", true }, { "Population", 21500000 }, { "Regions", new ArrayList{"jingjinji", "hebei"} } }); Console.WriteLine("Added example cities data to the cities collection."); // [END fs_query_create_examples] } private static async Task CreateQueryState(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START fs_create_query_state] CollectionReference citiesRef = db.Collection("cities"); Query query = citiesRef.WhereEqualTo("State", "CA"); QuerySnapshot querySnapshot = await query.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in querySnapshot.Documents) { Console.WriteLine("Document {0} returned by query State=CA", documentSnapshot.Id); } // [END fs_create_query_state] } private static async Task CreateQueryCapital(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START fs_create_query_capital] CollectionReference citiesRef = db.Collection("cities"); Query query = citiesRef.WhereEqualTo("Capital", true); QuerySnapshot querySnapshot = await query.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in querySnapshot.Documents) { Console.WriteLine("Document {0} returned by query Capital=true", documentSnapshot.Id); } // [END fs_create_query_capital] } private static async Task SimpleQueries(string project) { FirestoreDb db = FirestoreDb.Create(project); CollectionReference citiesRef = db.Collection("cities"); // [START fs_simple_queries] Query stateQuery = citiesRef.WhereEqualTo("State", "CA"); Query populationQuery = citiesRef.WhereGreaterThan("Population", 1000000); Query nameQuery = citiesRef.WhereGreaterThanOrEqualTo("Name", "San Francisco"); // [END fs_simple_queries] QuerySnapshot stateQuerySnapshot = await stateQuery.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in stateQuerySnapshot.Documents) { Console.WriteLine("Document {0} returned by query State=CA", documentSnapshot.Id); } QuerySnapshot populationQuerySnapshot = await populationQuery.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in populationQuerySnapshot.Documents) { Console.WriteLine("Document {0} returned by query Population>1000000", documentSnapshot.Id); } QuerySnapshot nameQuerySnapshot = await nameQuery.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in nameQuerySnapshot.Documents) { Console.WriteLine("Document {0} returned by query Name>=San Francisco", documentSnapshot.Id); } } private static async Task ArrayContainsQuery(string project) { FirestoreDb db = FirestoreDb.Create(project); CollectionReference citiesRef = db.Collection("cities"); // [START fs_array_contains_query] Query query = citiesRef.WhereArrayContains("Regions", "west_coast"); // [END fs_array_contains_query] QuerySnapshot querySnapshot = await query.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in querySnapshot.Documents) { Console.WriteLine("Document {0} returned by query 'Regions array_contains west_coast'", documentSnapshot.Id); } } private static async Task ArrayContainsAnyQuery(string project) { FirestoreDb db = FirestoreDb.Create(project); CollectionReference citiesRef = db.Collection("cities"); // [START fs_query_filter_array_contains_any] Query query = citiesRef.WhereArrayContainsAny("Regions", new[] { "west_coast", "east_coast" }); // [END fs_query_filter_array_contains_any] QuerySnapshot querySnapshot = await query.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in querySnapshot.Documents) { Console.WriteLine("Document {0} returned by query 'Regions array_contains_any {{west_coast, east_coast}}'", documentSnapshot.Id); } } private static async Task InQueryWithoutArray(string project) { FirestoreDb db = FirestoreDb.Create(project); CollectionReference citiesRef = db.Collection("cities"); // [START fs_query_filter_in] Query query = citiesRef.WhereIn("Country", new[] { "USA", "Japan" }); // [END fs_query_filter_in] QuerySnapshot querySnapshot = await query.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in querySnapshot.Documents) { Console.WriteLine("Document {0} returned by query 'Country in {{USA, Japan}}'", documentSnapshot.Id); } } private static async Task InQueryWithArray(string project) { FirestoreDb db = FirestoreDb.Create(project); CollectionReference citiesRef = db.Collection("cities"); // [START fs_query_filter_in_with_array] Query query = citiesRef.WhereIn("Regions", new[] { new[] { "west_coast" }, new[] { "east_coast" } }); // [END fs_query_filter_in_with_array] QuerySnapshot querySnapshot = await query.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in querySnapshot.Documents) { Console.WriteLine("Document {0} returned by query 'Regions in {{west_coast}}, {{east_coast}}'", documentSnapshot.Id); } } private static async Task CollectionGroupQuery(string project) { FirestoreDb db = FirestoreDb.Create(project); CollectionReference citiesRef = db.Collection("cities"); // [START fs_collection_group_query_data_setup] await citiesRef.Document("SF").Collection("landmarks").Document() .CreateAsync(new { Name = "Golden Gate Bridge", Type = "bridge" }); await citiesRef.Document("SF").Collection("landmarks").Document() .CreateAsync(new { Name = "Legion of Honor", Type = "museum" }); await citiesRef.Document("LA").Collection("landmarks").Document() .CreateAsync(new { Name = "Griffith Park", Type = "park" }); await citiesRef.Document("DC").Collection("landmarks").Document() .CreateAsync(new { Name = "Lincoln Memorial", Type = "memorial" }); await citiesRef.Document("DC").Collection("landmarks").Document() .CreateAsync(new { Name = "National Air And Space Museum", Type = "museum" }); await citiesRef.Document("TOK").Collection("landmarks").Document() .CreateAsync(new { Name = "Ueno Park", Type = "park" }); await citiesRef.Document("TOK").Collection("landmarks").Document() .CreateAsync(new { Name = "National Museum of Nature and Science", Type = "museum" }); await citiesRef.Document("BJ").Collection("landmarks").Document() .CreateAsync(new { Name = "Jingshan Park", Type = "park" }); await citiesRef.Document("BJ").Collection("landmarks").Document() .CreateAsync(new { Name = "Beijing Ancient Observatory", Type = "museum" }); // [END fs_collection_group_query_data_setup] // [START fs_collection_group_query] Query museums = db.CollectionGroup("landmarks").WhereEqualTo("Type", "museum"); QuerySnapshot querySnapshot = await museums.GetSnapshotAsync(); foreach (DocumentSnapshot document in querySnapshot.Documents) { Console.WriteLine($"{document.Reference.Path}: {document.GetValue<string>("Name")}"); } // [END fs_collection_group_query] } private static async Task ChainedQuery(string project) { FirestoreDb db = FirestoreDb.Create(project); CollectionReference citiesRef = db.Collection("cities"); // [START fs_chained_query] Query chainedQuery = citiesRef .WhereEqualTo("State", "CA") .WhereEqualTo("Name", "San Francisco"); // [END fs_chained_query] QuerySnapshot querySnapshot = await chainedQuery.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in querySnapshot.Documents) { Console.WriteLine("Document {0} returned by query State=CA and Name=San Francisco", documentSnapshot.Id); } } private static async Task CompositeIndexChainedQuery(string project) { FirestoreDb db = FirestoreDb.Create(project); CollectionReference citiesRef = db.Collection("cities"); // [START fs_composite_index_chained_query] Query chainedQuery = citiesRef .WhereEqualTo("State", "CA") .WhereLessThan("Population", 1000000); // [END fs_composite_index_chained_query] QuerySnapshot querySnapshot = await chainedQuery.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in querySnapshot.Documents) { Console.WriteLine("Document {0} returned by query State=CA and Population<1000000", documentSnapshot.Id); } } private static async Task RangeQuery(string project) { FirestoreDb db = FirestoreDb.Create(project); CollectionReference citiesRef = db.Collection("cities"); // [START fs_range_query] Query rangeQuery = citiesRef .WhereGreaterThanOrEqualTo("State", "CA") .WhereLessThanOrEqualTo("State", "IN"); // [END fs_range_query] QuerySnapshot querySnapshot = await rangeQuery.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in querySnapshot.Documents) { Console.WriteLine("Document {0} returned by query CA<=State<=IN", documentSnapshot.Id); } } private static void InvalidRangeQuery(string project) { FirestoreDb db = FirestoreDb.Create(project); CollectionReference citiesRef = db.Collection("cities"); // [START fs_invalid_range_query] Query invalidRangeQuery = citiesRef .WhereGreaterThanOrEqualTo("State", "CA") .WhereGreaterThan("Population", 1000000); // [END fs_invalid_range_query] } public static void Main(string[] args) { if (args.Length < 2) { Console.Write(Usage); return; } string command = args[0].ToLower(); string project = string.Join(" ", new ArraySegment<string>(args, 1, args.Length - 1)); switch (command) { case "query-create-examples": QueryCreateExamples(project).Wait(); break; case "create-query-state": CreateQueryState(project).Wait(); break; case "create-query-capital": CreateQueryCapital(project).Wait(); break; case "simple-queries": SimpleQueries(project).Wait(); break; case "array-contains-query": ArrayContainsQuery(project).Wait(); break; case "array-contains-any-query": ArrayContainsAnyQuery(project).Wait(); break; case "in-query": InQueryWithoutArray(project).Wait(); break; case "in-query-array": InQueryWithArray(project).Wait(); break; case "collection-group-query": CollectionGroupQuery(project).Wait(); break; case "chained-query": ChainedQuery(project).Wait(); break; case "composite-index-chained-query": CompositeIndexChainedQuery(project).Wait(); break; case "range-query": RangeQuery(project).Wait(); break; case "invalid-range-query": InvalidRangeQuery(project); break; default: Console.Write(Usage); return; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Numerics { /// <summary> /// A complex number z is a number of the form z = x + yi, where x and y /// are real numbers, and i is the imaginary unit, with the property i2= -1. /// </summary> [Serializable] public struct Complex : IEquatable<Complex>, IFormattable { public static readonly Complex Zero = new Complex(0.0, 0.0); public static readonly Complex One = new Complex(1.0, 0.0); public static readonly Complex ImaginaryOne = new Complex(0.0, 1.0); private const double InverseOfLog10 = 0.43429448190325; // 1 / Log(10) // This is the largest x for which (Hypot(x,x) + x) will not overflow. It is used for branching inside Sqrt. private static readonly double s_sqrtRescaleThreshold = double.MaxValue / (Math.Sqrt(2.0) + 1.0); // This is the largest x for which 2 x^2 will not overflow. It is used for branching inside Asin and Acos. private static readonly double s_asinOverflowThreshold = Math.Sqrt(double.MaxValue) / 2.0; // This value is used inside Asin and Acos. private static readonly double s_log2 = Math.Log(2.0); private double _real; private double _imaginary; public Complex(double real, double imaginary) { _real = real; _imaginary = imaginary; } public double Real { get { return _real; } } public double Imaginary { get { return _imaginary; } } public double Magnitude { get { return Abs(this); } } public double Phase { get { return Math.Atan2(_imaginary, _real); } } public static Complex FromPolarCoordinates(double magnitude, double phase) { return new Complex(magnitude * Math.Cos(phase), magnitude * Math.Sin(phase)); } public static Complex Negate(Complex value) { return -value; } public static Complex Add(Complex left, Complex right) { return left + right; } public static Complex Subtract(Complex left, Complex right) { return left - right; } public static Complex Multiply(Complex left, Complex right) { return left * right; } public static Complex Divide(Complex dividend, Complex divisor) { return dividend / divisor; } public static Complex operator -(Complex value) /* Unary negation of a complex number */ { return new Complex(-value._real, -value._imaginary); } public static Complex operator +(Complex left, Complex right) { return new Complex(left._real + right._real, left._imaginary + right._imaginary); } public static Complex operator -(Complex left, Complex right) { return new Complex(left._real - right._real, left._imaginary - right._imaginary); } public static Complex operator *(Complex left, Complex right) { // Multiplication: (a + bi)(c + di) = (ac -bd) + (bc + ad)i double result_Realpart = (left._real * right._real) - (left._imaginary * right._imaginary); double result_Imaginarypart = (left._imaginary * right._real) + (left._real * right._imaginary); return new Complex(result_Realpart, result_Imaginarypart); } public static Complex operator /(Complex left, Complex right) { // Division : Smith's formula. double a = left._real; double b = left._imaginary; double c = right._real; double d = right._imaginary; if (Math.Abs(d) < Math.Abs(c)) { double doc = d / c; return new Complex((a + b * doc) / (c + d * doc), (b - a * doc) / (c + d * doc)); } else { double cod = c / d; return new Complex((b + a * cod) / (d + c * cod), (-a + b * cod) / (d + c * cod)); } } public static double Abs(Complex value) { return Hypot(value._real, value._imaginary); } private static double Hypot(double a, double b) { // Using // sqrt(a^2 + b^2) = |a| * sqrt(1 + (b/a)^2) // we can factor out the larger component to dodge overflow even when a * a would overflow. a = Math.Abs(a); b = Math.Abs(b); double small, large; if (a < b) { small = a; large = b; } else { small = b; large = a; } if (small == 0.0) { return (large); } else if (double.IsPositiveInfinity(large) && !double.IsNaN(small)) { // The NaN test is necessary so we don't return +inf when small=NaN and large=+inf. // NaN in any other place returns NaN without any special handling. return (double.PositiveInfinity); } else { double ratio = small / large; return (large * Math.Sqrt(1.0 + ratio * ratio)); } } private static double Log1P(double x) { // Compute log(1 + x) without loss of accuracy when x is small. // Our only use case so far is for positive values, so this isn't coded to handle negative values. Debug.Assert((x >= 0.0) || double.IsNaN(x)); double xp1 = 1.0 + x; if (xp1 == 1.0) { return x; } else if (x < 0.75) { // This is accurate to within 5 ulp with any floating-point system that uses a guard digit, // as proven in Theorem 4 of "What Every Computer Scientist Should Know About Floating-Point // Arithmetic" (https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) return x * Math.Log(xp1) / (xp1 - 1.0); } else { return Math.Log(xp1); } } public static Complex Conjugate(Complex value) { // Conjugate of a Complex number: the conjugate of x+i*y is x-i*y return new Complex(value._real, -value._imaginary); } public static Complex Reciprocal(Complex value) { // Reciprocal of a Complex number : the reciprocal of x+i*y is 1/(x+i*y) if (value._real == 0 && value._imaginary == 0) { return Zero; } return One / value; } public static bool operator ==(Complex left, Complex right) { return left._real == right._real && left._imaginary == right._imaginary; } public static bool operator !=(Complex left, Complex right) { return left._real != right._real || left._imaginary != right._imaginary; } public override bool Equals(object obj) { if (!(obj is Complex)) return false; return Equals((Complex)obj); } public bool Equals(Complex value) { return _real.Equals(value._real) && _imaginary.Equals(value._imaginary); } public override int GetHashCode() { int n1 = 99999997; int realHash = _real.GetHashCode() % n1; int imaginaryHash = _imaginary.GetHashCode(); int finalHash = realHash ^ imaginaryHash; return finalHash; } public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "({0}, {1})", _real, _imaginary); } public string ToString(string format) { return string.Format(CultureInfo.CurrentCulture, "({0}, {1})", _real.ToString(format, CultureInfo.CurrentCulture), _imaginary.ToString(format, CultureInfo.CurrentCulture)); } public string ToString(IFormatProvider provider) { return string.Format(provider, "({0}, {1})", _real, _imaginary); } public string ToString(string format, IFormatProvider provider) { return string.Format(provider, "({0}, {1})", _real.ToString(format, provider), _imaginary.ToString(format, provider)); } public static Complex Sin(Complex value) { // We need both sinh and cosh of imaginary part. To avoid multiple calls to Math.Exp with the same value, // we compute them both here from a single call to Math.Exp. double p = Math.Exp(value._imaginary); double q = 1.0 / p; double sinh = (p - q) * 0.5; double cosh = (p + q) * 0.5; return new Complex(Math.Sin(value._real) * cosh, Math.Cos(value._real) * sinh); // There is a known limitation with this algorithm: inputs that cause sinh and cosh to overflow, but for // which sin or cos are small enough that sin * cosh or cos * sinh are still representable, nonetheless // produce overflow. For example, Sin((0.01, 711.0)) should produce (~3.0E306, PositiveInfinity), but // instead produces (PositiveInfinity, PositiveInfinity). } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sinh", Justification = "Sinh is the name of a mathematical function.")] public static Complex Sinh(Complex value) { // Use sinh(z) = -i sin(iz) to compute via sin(z). Complex sin = Sin(new Complex(-value._imaginary, value._real)); return new Complex(sin._imaginary, -sin._real); } public static Complex Asin(Complex value) { double b, bPrime, v; Asin_Internal(Math.Abs(value.Real), Math.Abs(value.Imaginary), out b, out bPrime, out v); double u; if (bPrime < 0.0) { u = Math.Asin(b); } else { u = Math.Atan(bPrime); } if (value.Real < 0.0) u = -u; if (value.Imaginary < 0.0) v = -v; return new Complex(u, v); } public static Complex Cos(Complex value) { double p = Math.Exp(value._imaginary); double q = 1.0 / p; double sinh = (p - q) * 0.5; double cosh = (p + q) * 0.5; return new Complex(Math.Cos(value._real) * cosh, -Math.Sin(value._real) * sinh); } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cosh", Justification = "Cosh is the name of a mathematical function.")] public static Complex Cosh(Complex value) { // Use cosh(z) = cos(iz) to compute via cos(z). return Cos(new Complex(-value._imaginary, value._real)); } public static Complex Acos(Complex value) { double b, bPrime, v; Asin_Internal(Math.Abs(value.Real), Math.Abs(value.Imaginary), out b, out bPrime, out v); double u; if (bPrime < 0.0) { u = Math.Acos(b); } else { u = Math.Atan(1.0 / bPrime); } if (value.Real < 0.0) u = Math.PI - u; if (value.Imaginary > 0.0) v = -v; return new Complex(u, v); } public static Complex Tan(Complex value) { // tan z = sin z / cos z, but to avoid unnecessary repeated trig computations, use // tan z = (sin(2x) + i sinh(2y)) / (cos(2x) + cosh(2y)) // (see Abramowitz & Stegun 4.3.57 or derive by hand), and compute trig functions here. // This approach does not work for |y| > ~355, because sinh(2y) and cosh(2y) overflow, // even though their ratio does not. In that case, divide through by cosh to get: // tan z = (sin(2x) / cosh(2y) + i \tanh(2y)) / (1 + cos(2x) / cosh(2y)) // which correctly computes the (tiny) real part and the (normal-sized) imaginary part. double x2 = 2.0 * value._real; double y2 = 2.0 * value._imaginary; double p = Math.Exp(y2); double q = 1.0 / p; double cosh = (p + q) * 0.5; if (Math.Abs(value._imaginary) <= 4.0) { double sinh = (p - q) * 0.5; double D = Math.Cos(x2) + cosh; return new Complex(Math.Sin(x2) / D, sinh / D); } else { double D = 1.0 + Math.Cos(x2) / cosh; return new Complex(Math.Sin(x2) / cosh / D, Math.Tanh(y2) / D); } } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Tanh", Justification = "Tanh is the name of a mathematical function.")] public static Complex Tanh(Complex value) { // Use tanh(z) = -i tan(iz) to compute via tan(z). Complex tan = Tan(new Complex(-value._imaginary, value._real)); return new Complex(tan._imaginary, -tan._real); } public static Complex Atan(Complex value) { Complex two = new Complex(2.0, 0.0); return (ImaginaryOne / two) * (Log(One - ImaginaryOne * value) - Log(One + ImaginaryOne * value)); } private static void Asin_Internal (double x, double y, out double b, out double bPrime, out double v) { // This method for the inverse complex sine (and cosine) is described in Hull, Fairgrieve, // and Tang, "Implementing the Complex Arcsine and Arccosine Functions Using Exception Handling", // ACM Transactions on Mathematical Software (1997) // (https://www.researchgate.net/profile/Ping_Tang3/publication/220493330_Implementing_the_Complex_Arcsine_and_Arccosine_Functions_Using_Exception_Handling/links/55b244b208ae9289a085245d.pdf) // First, the basics: start with sin(w) = (e^{iw} - e^{-iw}) / (2i) = z. Here z is the input // and w is the output. To solve for w, define t = e^{i w} and multiply through by t to // get the quadratic equation t^2 - 2 i z t - 1 = 0. The solution is t = i z + sqrt(1 - z^2), so // w = arcsin(z) = - i log( i z + sqrt(1 - z^2) ) // Decompose z = x + i y, multiply out i z + sqrt(1 - z^2), use log(s) = |s| + i arg(s), and do a // bunch of algebra to get the components of w = arcsin(z) = u + i v // u = arcsin(beta) v = sign(y) log(alpha + sqrt(alpha^2 - 1)) // where // alpha = (rho + sigma) / 2 beta = (rho - sigma) / 2 // rho = sqrt((x + 1)^2 + y^2) sigma = sqrt((x - 1)^2 + y^2) // These formulas appear in DLMF section 4.23. (http://dlmf.nist.gov/4.23), along with the analogous // arccos(w) = arccos(beta) - i sign(y) log(alpha + sqrt(alpha^2 - 1)) // So alpha and beta together give us arcsin(w) and arccos(w). // As written, alpha is not susceptible to cancelation errors, but beta is. To avoid cancelation, note // beta = (rho^2 - sigma^2) / (rho + sigma) / 2 = (2 x) / (rho + sigma) = x / alpha // which is not subject to cancelation. Note alpha >= 1 and |beta| <= 1. // For alpha ~ 1, the argument of the log is near unity, so we compute (alpha - 1) instead, // write the argument as 1 + (alpha - 1) + sqrt((alpha - 1)(alpha + 1)), and use the log1p function // to compute the log without loss of accuracy. // For beta ~ 1, arccos does not accurately resolve small angles, so we compute the tangent of the angle // instead. // Hull, Fairgrieve, and Tang derive formulas for (alpha - 1) and beta' = tan(u) that do not suffer // from cancelation in these cases. // For simplicity, we assume all positive inputs and return all positive outputs. The caller should // assign signs appropriate to the desired cut conventions. We return v directly since its magnitude // is the same for both arcsin and arccos. Instead of u, we usually return beta and sometimes beta'. // If beta' is not computed, it is set to -1; if it is computed, it should be used instead of beta // to determine u. Compute u = arcsin(beta) or u = arctan(beta') for arcsin, u = arccos(beta) // or arctan(1/beta') for arccos. Debug.Assert((x >= 0.0) || double.IsNaN(x)); Debug.Assert((y >= 0.0) || double.IsNaN(y)); // For x or y large enough to overflow alpha^2, we can simplify our formulas and avoid overflow. if ((x > s_asinOverflowThreshold) || (y > s_asinOverflowThreshold)) { b = -1.0; bPrime = x / y; double small, big; if (x < y) { small = x; big = y; } else { small = y; big = x; } double ratio = small / big; v = s_log2 + Math.Log(big) + 0.5 * Log1P(ratio * ratio); } else { double r = Hypot((x + 1.0), y); double s = Hypot((x - 1.0), y); double a = (r + s) * 0.5; b = x / a; if (b > 0.75) { if (x <= 1.0) { double amx = (y * y / (r + (x + 1.0)) + (s + (1.0 - x))) * 0.5; bPrime = x / Math.Sqrt((a + x) * amx); } else { // In this case, amx ~ y^2. Since we take the square root of amx, we should // pull y out from under the square root so we don't lose its contribution // when y^2 underflows. double t = (1.0 / (r + (x + 1.0)) + 1.0 / (s + (x - 1.0))) * 0.5; bPrime = x / y / Math.Sqrt((a + x) * t); } } else { bPrime = -1.0; } if (a < 1.5) { if (x < 1.0) { // This is another case where our expression is proportional to y^2 and // we take its square root, so again we pull out a factor of y from // under the square root. double t = (1.0 / (r + (x + 1.0)) + 1.0 / (s + (1.0 - x))) * 0.5; double am1 = y * y * t; v = Log1P(am1 + y * Math.Sqrt(t * (a + 1.0))); } else { double am1 = (y * y / (r + (x + 1.0)) + (s + (x - 1.0))) * 0.5; v = Log1P(am1 + Math.Sqrt(am1 * (a + 1.0))); } } else { // Because of the test above, we can be sure that a * a will not overflow. v = Math.Log(a + Math.Sqrt((a - 1.0) * (a + 1.0))); } } } public static Complex Log(Complex value) { return new Complex(Math.Log(Abs(value)), Math.Atan2(value._imaginary, value._real)); } public static Complex Log(Complex value, double baseValue) { return Log(value) / Log(baseValue); } public static Complex Log10(Complex value) { Complex tempLog = Log(value); return Scale(tempLog, InverseOfLog10); } public static Complex Exp(Complex value) { double expReal = Math.Exp(value._real); double cosImaginary = expReal * Math.Cos(value._imaginary); double sinImaginary = expReal * Math.Sin(value._imaginary); return new Complex(cosImaginary, sinImaginary); } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sqrt", Justification = "Sqrt is the name of a mathematical function.")] public static Complex Sqrt(Complex value) { if (value._imaginary == 0.0) { // Handle the trivial case quickly. if (value._real < 0.0) { return new Complex(0.0, Math.Sqrt(-value._real)); } else { return new Complex(Math.Sqrt(value._real), 0.0); } } else { // One way to compute Sqrt(z) is just to call Pow(z, 0.5), which coverts to polar coordinates // (sqrt + atan), halves the phase, and reconverts to cartesian coordinates (cos + sin). // Not only is this more expensive than necessary, it also fails to preserve certain expected // symmetries, such as that the square root of a pure negative is a pure imaginary, and that the // square root of a pure imaginary has exactly equal real and imaginary parts. This all goes // back to the fact that Math.PI is not stored with infinite precision, so taking half of Math.PI // does not land us on an argument with cosine exactly equal to zero. // To find a fast and symmetry-respecting formula for complex square root, // note x + i y = \sqrt{a + i b} implies x^2 + 2 i x y - y^2 = a + i b, // so x^2 - y^2 = a and 2 x y = b. Cross-substitute and use the quadratic formula to obtain // x = \sqrt{\frac{\sqrt{a^2 + b^2} + a}{2}} y = \pm \sqrt{\frac{\sqrt{a^2 + b^2} - a}{2}} // There is just one complication: depending on the sign on a, either x or y suffers from // cancelation when |b| << |a|. We can get aroud this by noting that our formulas imply // x^2 y^2 = b^2 / 4, so |x| |y| = |b| / 2. So after computing the one that doesn't suffer // from cancelation, we can compute the other with just a division. This is basically just // the right way to evaluate the quadratic formula without cancelation. // All this reduces our total cost to two sqrts and a few flops, and it respects the desired // symmetries. Much better than atan + cos + sin! // The signs are a matter of choice of branch cut, which is traditionally taken so x > 0 and sign(y) = sign(b). // If the components are too large, Hypot will overflow, even though the subsequent sqrt would // make the result representable. To avoid this, we re-scale (by exact powers of 2 for accuracy) // when we encounter very large components to avoid intermediate infinities. bool rescale = false; if ((Math.Abs(value._real) >= s_sqrtRescaleThreshold) || (Math.Abs(value._imaginary) >= s_sqrtRescaleThreshold)) { if (double.IsInfinity(value._imaginary) && !double.IsNaN(value._real)) { // We need to handle infinite imaginary parts specially because otherwise // our formulas below produce inf/inf = NaN. The NaN test is necessary // so that we return NaN rather than (+inf,inf) for (NaN,inf). return (new Complex(double.PositiveInfinity, value._imaginary)); } else { value._real *= 0.25; value._imaginary *= 0.25; rescale = true; } } // This is the core of the algorithm. Everything else is special case handling. double x, y; if (value._real >= 0.0) { x = Math.Sqrt((Hypot(value._real, value._imaginary) + value._real) * 0.5); y = value._imaginary / (2.0 * x); } else { y = Math.Sqrt((Hypot(value._real, value._imaginary) - value._real) * 0.5); if (value._imaginary < 0.0) y = -y; x = value._imaginary / (2.0 * y); } if (rescale) { x *= 2.0; y *= 2.0; } return new Complex(x, y); } } public static Complex Pow(Complex value, Complex power) { if (power == Zero) { return One; } if (value == Zero) { return Zero; } double valueReal = value._real; double valueImaginary = value._imaginary; double powerReal = power._real; double powerImaginary = power._imaginary; double rho = Abs(value); double theta = Math.Atan2(valueImaginary, valueReal); double newRho = powerReal * theta + powerImaginary * Math.Log(rho); double t = Math.Pow(rho, powerReal) * Math.Pow(Math.E, -powerImaginary * theta); return new Complex(t * Math.Cos(newRho), t * Math.Sin(newRho)); } public static Complex Pow(Complex value, double power) { return Pow(value, new Complex(power, 0)); } private static Complex Scale(Complex value, double factor) { double realResult = factor * value._real; double imaginaryResuilt = factor * value._imaginary; return new Complex(realResult, imaginaryResuilt); } public static implicit operator Complex(short value) { return new Complex(value, 0.0); } public static implicit operator Complex(int value) { return new Complex(value, 0.0); } public static implicit operator Complex(long value) { return new Complex(value, 0.0); } [CLSCompliant(false)] public static implicit operator Complex(ushort value) { return new Complex(value, 0.0); } [CLSCompliant(false)] public static implicit operator Complex(uint value) { return new Complex(value, 0.0); } [CLSCompliant(false)] public static implicit operator Complex(ulong value) { return new Complex(value, 0.0); } [CLSCompliant(false)] public static implicit operator Complex(sbyte value) { return new Complex(value, 0.0); } public static implicit operator Complex(byte value) { return new Complex(value, 0.0); } public static implicit operator Complex(float value) { return new Complex(value, 0.0); } public static implicit operator Complex(double value) { return new Complex(value, 0.0); } public static explicit operator Complex(BigInteger value) { return new Complex((double)value, 0.0); } public static explicit operator Complex(decimal value) { return new Complex((double)value, 0.0); } } }
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using UnityEngine; using System; using System.Collections; using System.Collections.Generic; /* GoogleAnalyticsV4 is an interface for developers to send hits to Google Analytics. The class will delegate the hits to the appropriate helper class depending on the platform being built for - Android, iOS or Measurement Protocol for all others. Each method has a simple form with the hit parameters, or developers can pass a builder to the same method name in order to add custom metrics or custom dimensions to the hit. */ public class GoogleAnalyticsV4 : MonoBehaviour { private string uncaughtExceptionStackTrace = null; private bool initialized = false; public enum DebugMode { ERROR, WARNING, INFO, VERBOSE }; [Tooltip("The tracking code to be used for Android. Example value: UA-XXXX-Y.")] public string androidTrackingCode; [Tooltip("The tracking code to be used for iOS. Example value: UA-XXXX-Y.")] public string IOSTrackingCode; [Tooltip("The tracking code to be used for platforms other than Android and iOS. Example value: UA-XXXX-Y.")] public string otherTrackingCode; [Tooltip("The application name. This value should be modified in the " + "Unity Player Settings.")] public string productName; [Tooltip("The application identifier. Example value: com.company.app.")] public string bundleIdentifier; [Tooltip("The application version. Example value: 1.2")] public string bundleVersion; [RangedTooltip("The dispatch period in seconds. Only required for Android " + "and iOS.", 0, 3600)] public int dispatchPeriod = 5; [RangedTooltip("The sample rate to use. Only required for Android and" + " iOS.", 0, 100)] public int sampleFrequency = 100; [Tooltip("The log level. Default is WARNING.")] public DebugMode logLevel = DebugMode.WARNING; [Tooltip("If checked, the IP address of the sender will be anonymized.")] public bool anonymizeIP = false; [Tooltip("Automatically report uncaught exceptions.")] public bool UncaughtExceptionReporting = false; [Tooltip("Automatically send a launch event when the game starts up.")] public bool sendLaunchEvent = false; [Tooltip("If checked, hits will not be dispatched. Use for testing.")] public bool dryRun = false; // TODO: Create conditional textbox attribute [Tooltip("The amount of time in seconds your application can stay in" + "the background before the session is ended. Default is 30 minutes" + " (1800 seconds). A value of -1 will disable session management.")] public int sessionTimeout = 1800; [AdvertiserOptIn()] public bool enableAdId = false; public static GoogleAnalyticsV4 instance = null; [HideInInspector] public readonly static string currencySymbol = "USD"; public readonly static string EVENT_HIT = "createEvent"; public readonly static string APP_VIEW = "createAppView"; public readonly static string SET = "set"; public readonly static string SET_ALL = "setAll"; public readonly static string SEND = "send"; public readonly static string ITEM_HIT = "createItem"; public readonly static string TRANSACTION_HIT = "createTransaction"; public readonly static string SOCIAL_HIT = "createSocial"; public readonly static string TIMING_HIT = "createTiming"; public readonly static string EXCEPTION_HIT = "createException"; #if UNITY_ANDROID && !UNITY_EDITOR private GoogleAnalyticsAndroidV4 androidTracker = new GoogleAnalyticsAndroidV4(); #elif UNITY_IPHONE && !UNITY_EDITOR private GoogleAnalyticsiOSV3 iosTracker = new GoogleAnalyticsiOSV3(); #else private GoogleAnalyticsMPV3 mpTracker = new GoogleAnalyticsMPV3(); #endif private bool setup = false; public void SetUp() { if (setup) return; setup = true; InitializeTracker (); if (sendLaunchEvent) { LogEvent("Google Analytics", "Auto Instrumentation", "Game Launch", 0); } if (UncaughtExceptionReporting) { #if UNITY_5 Application.logMessageReceived += HandleException; #else Application.RegisterLogCallback (HandleException); #endif if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Enabling uncaught exception reporting."); } } } void Update() { if (!string.IsNullOrEmpty(uncaughtExceptionStackTrace)) { LogException(uncaughtExceptionStackTrace, true); uncaughtExceptionStackTrace = null; } } private void HandleException(string condition, string stackTrace, LogType type) { if (type == LogType.Exception) { uncaughtExceptionStackTrace = condition + "\n" + stackTrace + UnityEngine.StackTraceUtility.ExtractStackTrace(); } } // TODO: Error checking on initialization parameters private void InitializeTracker() { if (!initialized) { instance = this; DontDestroyOnLoad(instance); Debug.Log("Initializing Google Analytics 0.2."); #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.SetTrackingCode(androidTrackingCode); androidTracker.SetAppName(productName); androidTracker.SetBundleIdentifier(bundleIdentifier); androidTracker.SetAppVersion(bundleVersion); androidTracker.SetDispatchPeriod(dispatchPeriod); androidTracker.SetSampleFrequency(sampleFrequency); androidTracker.SetLogLevelValue(logLevel); androidTracker.SetAnonymizeIP(anonymizeIP); androidTracker.SetAdIdCollection(enableAdId); androidTracker.SetDryRun(dryRun); androidTracker.InitializeTracker(); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.SetTrackingCode(IOSTrackingCode); iosTracker.SetAppName(productName); iosTracker.SetBundleIdentifier(bundleIdentifier); iosTracker.SetAppVersion(bundleVersion); iosTracker.SetDispatchPeriod(dispatchPeriod); iosTracker.SetSampleFrequency(sampleFrequency); iosTracker.SetLogLevelValue(logLevel); iosTracker.SetAnonymizeIP(anonymizeIP); iosTracker.SetAdIdCollection(enableAdId); iosTracker.SetDryRun(dryRun); iosTracker.InitializeTracker(); #else mpTracker.SetTrackingCode(otherTrackingCode); mpTracker.SetBundleIdentifier(bundleIdentifier); mpTracker.SetAppName(productName); mpTracker.SetAppVersion(bundleVersion); mpTracker.SetLogLevelValue(logLevel); mpTracker.SetAnonymizeIP(anonymizeIP); mpTracker.SetDryRun(dryRun); mpTracker.InitializeTracker(); #endif initialized = true; SetOnTracker(Fields.DEVELOPER_ID, "GbOCSs"); } } public void SetAppLevelOptOut(bool optOut) { InitializeTracker(); #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.SetOptOut(optOut); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.SetOptOut(optOut); #else mpTracker.SetOptOut(optOut); #endif } public void SetUserIDOverride(string userID) { SetOnTracker(Fields.USER_ID, userID); } public void ClearUserIDOverride() { InitializeTracker(); #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.ClearUserIDOverride(); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.ClearUserIDOverride(); #else mpTracker.ClearUserIDOverride(); #endif } public void DispatchHits() { InitializeTracker(); #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.DispatchHits(); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.DispatchHits(); #else //Do nothing #endif } public void StartSession() { InitializeTracker(); #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.StartSession(); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.StartSession(); #else mpTracker.StartSession(); #endif } public void StopSession() { InitializeTracker(); #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.StopSession(); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.StopSession(); #else mpTracker.StopSession(); #endif } // Use values from Fields for the fieldName parameter ie. Fields.SCREEN_NAME public void SetOnTracker(Field fieldName, object value) { InitializeTracker(); #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.SetTrackerVal(fieldName, value); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.SetTrackerVal(fieldName, value); #else mpTracker.SetTrackerVal(fieldName, value); #endif } public void LogScreen(string title) { AppViewHitBuilder builder = new AppViewHitBuilder().SetScreenName(title); LogScreen(builder); } public void LogScreen(AppViewHitBuilder builder) { InitializeTracker(); if (builder.Validate() == null) { return; } if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Logging screen."); } #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.LogScreen(builder); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.LogScreen(builder); #else mpTracker.LogScreen(builder); #endif } public void LogEvent(string eventCategory, string eventAction, string eventLabel, long value) { EventHitBuilder builder = new EventHitBuilder() .SetEventCategory(eventCategory) .SetEventAction(eventAction) .SetEventLabel(eventLabel) .SetEventValue(value); LogEvent(builder); } public void LogEvent(EventHitBuilder builder) { InitializeTracker(); if (builder.Validate() == null) { return; } if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Logging event."); } #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.LogEvent (builder); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.LogEvent(builder); #else mpTracker.LogEvent(builder); #endif } public void LogTransaction(string transID, string affiliation, double revenue, double tax, double shipping) { LogTransaction (transID, affiliation, revenue, tax, shipping, ""); } public void LogTransaction(string transID, string affiliation, double revenue, double tax, double shipping, string currencyCode) { TransactionHitBuilder builder = new TransactionHitBuilder() .SetTransactionID(transID) .SetAffiliation(affiliation) .SetRevenue(revenue) .SetTax(tax) .SetShipping(shipping) .SetCurrencyCode(currencyCode); LogTransaction(builder); } public void LogTransaction(TransactionHitBuilder builder) { InitializeTracker(); if (builder.Validate() == null) { return; } if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Logging transaction."); } #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.LogTransaction(builder); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.LogTransaction(builder); #else mpTracker.LogTransaction(builder); #endif } public void LogItem(string transID, string name, string sku, string category, double price, long quantity) { LogItem (transID, name, sku, category, price, quantity, null); } public void LogItem(string transID, string name, string sku, string category, double price, long quantity, string currencyCode) { ItemHitBuilder builder = new ItemHitBuilder() .SetTransactionID(transID) .SetName(name) .SetSKU(sku) .SetCategory(category) .SetPrice(price) .SetQuantity(quantity) .SetCurrencyCode(currencyCode); LogItem(builder); } public void LogItem(ItemHitBuilder builder) { InitializeTracker(); if (builder.Validate() == null) { return; } if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Logging item."); } #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.LogItem(builder); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.LogItem(builder); #else mpTracker.LogItem(builder); #endif } public void LogException(string exceptionDescription, bool isFatal) { ExceptionHitBuilder builder = new ExceptionHitBuilder() .SetExceptionDescription(exceptionDescription) .SetFatal(isFatal); LogException(builder); } public void LogException(ExceptionHitBuilder builder) { InitializeTracker(); if (builder.Validate() == null) { return; } if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Logging exception."); } #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.LogException(builder); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.LogException(builder); #else mpTracker.LogException(builder); #endif } public void LogSocial(string socialNetwork, string socialAction, string socialTarget) { SocialHitBuilder builder = new SocialHitBuilder() .SetSocialNetwork(socialNetwork) .SetSocialAction(socialAction) .SetSocialTarget(socialTarget); LogSocial(builder); } public void LogSocial(SocialHitBuilder builder) { InitializeTracker(); if (builder.Validate() == null) { return; } if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Logging social."); } #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.LogSocial(builder); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.LogSocial(builder); #else mpTracker.LogSocial(builder); #endif } public void LogTiming(string timingCategory, long timingInterval, string timingName, string timingLabel) { TimingHitBuilder builder = new TimingHitBuilder() .SetTimingCategory(timingCategory) .SetTimingInterval(timingInterval) .SetTimingName(timingName) .SetTimingLabel(timingLabel); LogTiming(builder); } public void LogTiming(TimingHitBuilder builder) { InitializeTracker(); if (builder.Validate() == null) { return; } if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Logging timing."); } #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.LogTiming(builder); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.LogTiming(builder); #else mpTracker.LogTiming(builder); #endif } public void Dispose() { initialized = false; #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.Dispose(); #elif UNITY_IPHONE && !UNITY_EDITOR #else #endif } public static bool belowThreshold(GoogleAnalyticsV4.DebugMode userLogLevel, GoogleAnalyticsV4.DebugMode comparelogLevel) { if (comparelogLevel == userLogLevel) { return true; } else if (userLogLevel == GoogleAnalyticsV4.DebugMode.ERROR) { return false; } else if (userLogLevel == GoogleAnalyticsV4.DebugMode.VERBOSE) { return true; } else if (userLogLevel == GoogleAnalyticsV4.DebugMode.WARNING && (comparelogLevel == GoogleAnalyticsV4.DebugMode.INFO || comparelogLevel == GoogleAnalyticsV4.DebugMode.VERBOSE)) { return false; } else if (userLogLevel == GoogleAnalyticsV4.DebugMode.INFO && (comparelogLevel == GoogleAnalyticsV4.DebugMode.VERBOSE)) { return false; } return true; } // Instance for running Coroutines from platform specific classes public static GoogleAnalyticsV4 getInstance() { return instance; } }
using System; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Providers.MongoDB.Test.GrainInterfaces; using Orleans.Providers.MongoDB.Test.Grains; namespace Orleans.Providers.MongoDB.Test.Host { public static class Program { public static async Task Main(string[] args) { var connectionString = "mongodb://localhost/OrleansTestApp"; var createShardKey = false; var silo = new SiloHostBuilder() .ConfigureApplicationParts(options => { options.AddApplicationPart(typeof(EmployeeGrain).Assembly).WithReferences(); }) .UseMongoDBClient(connectionString) .UseMongoDBClustering(options => { options.DatabaseName = "OrleansTestApp"; options.CreateShardKeyForCosmos = createShardKey; }) .AddStartupTask(async (s, ct) => { var grainFactory = s.GetRequiredService<IGrainFactory>(); await grainFactory.GetGrain<IHelloWorldGrain>((int)DateTime.UtcNow.TimeOfDay.Ticks).SayHello("HI"); }) .UseMongoDBReminders(options => { options.DatabaseName = "OrleansTestApp"; options.CreateShardKeyForCosmos = createShardKey; }) .AddSimpleMessageStreamProvider("OrleansTestStream", options => { options.FireAndForgetDelivery = true; options.OptimizeForImmutableData = true; options.PubSubType = Orleans.Streams.StreamPubSubType.ExplicitGrainBasedOnly; }) .AddMongoDBGrainStorage("PubSubStore", options => { options.DatabaseName = "OrleansTestAppPubSubStore"; options.CreateShardKeyForCosmos = createShardKey; options.ConfigureJsonSerializerSettings = settings => { settings.NullValueHandling = NullValueHandling.Include; settings.ObjectCreationHandling = ObjectCreationHandling.Replace; settings.DefaultValueHandling = DefaultValueHandling.Populate; }; }) .AddMongoDBGrainStorage("MongoDBStore", options => { options.DatabaseName = "OrleansTestApp"; options.CreateShardKeyForCosmos = createShardKey; options.ConfigureJsonSerializerSettings = settings => { settings.NullValueHandling = NullValueHandling.Include; settings.ObjectCreationHandling = ObjectCreationHandling.Replace; settings.DefaultValueHandling = DefaultValueHandling.Populate; }; }) .Configure<ClusterOptions>(options => { options.ClusterId = "helloworldcluster"; options.ServiceId = "helloworldcluster"; }) .ConfigureEndpoints(IPAddress.Loopback, 11111, 30000) .ConfigureLogging(logging => logging.AddConsole()) .Build(); await silo.StartAsync(); var client = new ClientBuilder() .ConfigureApplicationParts(options => { options.AddApplicationPart(typeof(IHelloWorldGrain).Assembly); }) .UseMongoDBClient(connectionString) .UseMongoDBClustering(options => { options.DatabaseName = "OrleansTestApp"; }) .Configure<ClusterOptions>(options => { options.ClusterId = "helloworldcluster"; options.ServiceId = "helloworldcluster"; }) .ConfigureLogging(logging => logging.AddConsole()) .Build(); await client.Connect(); await TestBasic(client); if (!args.Contains("--skip-reminders")) { await TestReminders(client); } if (!args.Contains("--skip-streams")) { await TestStreams(client); } await TestState(client); await TestStateWithCollections(client); Console.ReadKey(); await silo.StopAsync(); } private static async Task TestStreams(IClusterClient client) { var streamProducer = client.GetGrain<IStreamProducerGrain>(0); var streamConsumer1 = client.GetGrain<IStreamConsumerGrain>(0); var streamConsumer2 = client.GetGrain<IStreamConsumerGrain>(0); _ = streamProducer.ProduceEvents(); await streamConsumer1.Activate(); await streamConsumer2.Activate(); await Task.Delay(1000); var consumed1 = await streamConsumer1.GetConsumedItems(); var consumed2 = await streamConsumer1.GetConsumedItems(); Console.WriteLine("Consumed Events: {0}/{1}", consumed1, consumed2); } private static async Task TestBasic(IClusterClient client) { var helloWorldGrain = client.GetGrain<IHelloWorldGrain>(1); await helloWorldGrain.SayHello("World"); } private static async Task TestReminders(IClusterClient client) { var reminderGrain = client.GetGrain<IReminderGrain>(1); await reminderGrain.StartReminder("TestReminder", TimeSpan.FromMinutes(1)); } private static async Task TestStateWithCollections(IClusterClient client) { var vacationEmployee = client.GetGrain<IEmployeeGrain>(2); var vacationEmployeeId = await vacationEmployee.ReturnLevel(); if (vacationEmployeeId == 0) { for (int i = 0; i < 2; i++) { await vacationEmployee.AddVacationLeave(); } for (int i = 0; i < 2; i++) { await vacationEmployee.AddSickLeave(); } await vacationEmployee.SetLevel(101); } // Use ObjectCreationHandling.Replace in JsonSerializerSettings to replace the result during deserialization. var leaveCount = await vacationEmployee.ReturnLeaveCount(); Console.WriteLine($"Total leave count: {leaveCount}"); } private static async Task TestState(IClusterClient client) { var employee = client.GetGrain<IEmployeeGrain>(1); var employeeId = await employee.ReturnLevel(); if (employeeId == 100) { await employee.SetLevel(50); } else { await employee.SetLevel(100); } employeeId = await employee.ReturnLevel(); Console.WriteLine(employeeId); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, 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 { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Threading; using JetBrains.Annotations; using NLog.Common; using NLog.Internal; using NLog.Layouts; using NLog.MessageTemplates; using NLog.Time; /// <summary> /// Represents the logging event. /// </summary> public class LogEventInfo { /// <summary> /// Gets the date of the first log event created. /// </summary> public static readonly DateTime ZeroDate = DateTime.UtcNow; private static int globalSequenceId; /// <summary> /// The formatted log message. /// </summary> private string _formattedMessage; /// <summary> /// The log message including any parameter placeholders /// </summary> private string _message; private object[] _parameters; private IFormatProvider _formatProvider; private LogMessageFormatter _messageFormatter; private IDictionary<Layout, object> _layoutCache; private PropertiesDictionary _properties; private int _sequenceId; /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> public LogEventInfo() { TimeStamp = TimeSource.Current.Time; } /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="message">Log message including parameter placeholders.</param> public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message) : this(level, loggerName, null, message, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="message">Log message including parameter placeholders.</param> /// <param name="messageTemplateParameters">Already parsed message template parameters.</param> public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message, IList<MessageTemplateParameter> messageTemplateParameters) : this(level, loggerName, null, message, null, null) { if (messageTemplateParameters != null) { var messagePropertyCount = messageTemplateParameters.Count; if (messagePropertyCount > 0) { var messageProperties = new MessageTemplateParameter[messagePropertyCount]; for (int i = 0; i < messagePropertyCount; ++i) messageProperties[i] = messageTemplateParameters[i]; _properties = new PropertiesDictionary(messageProperties); } } } #if !NET35 /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="message">Log message.</param> /// <param name="eventProperties">List of event-properties</param> public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message, IReadOnlyList<KeyValuePair<object, object>> eventProperties) : this(level, loggerName, null, message, null, null) { if (eventProperties?.Count > 0) { _properties = new PropertiesDictionary(eventProperties); } } #endif /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">Log message including parameter placeholders.</param> /// <param name="parameters">Parameter array.</param> public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters) : this(level, loggerName, formatProvider, message, parameters, null) { } /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">Log message including parameter placeholders.</param> /// <param name="parameters">Parameter array.</param> /// <param name="exception">Exception information.</param> public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters, Exception exception) : this() { Level = level; LoggerName = loggerName; _formatProvider = formatProvider; _message = message; Parameters = parameters; Exception = exception; } /// <summary> /// Gets the unique identifier of log event which is automatically generated /// and monotonously increasing. /// </summary> // ReSharper disable once InconsistentNaming public int SequenceID { get { if (_sequenceId == 0) Interlocked.CompareExchange(ref _sequenceId, Interlocked.Increment(ref globalSequenceId), 0); return _sequenceId; } } /// <summary> /// Gets or sets the timestamp of the logging event. /// </summary> public DateTime TimeStamp { get; set; } /// <summary> /// Gets or sets the level of the logging event. /// </summary> public LogLevel Level { get; set; } [CanBeNull] internal CallSiteInformation CallSiteInformation { get; private set; } [NotNull] internal CallSiteInformation GetCallSiteInformationInternal() { return CallSiteInformation ?? (CallSiteInformation = new CallSiteInformation()); } /// <summary> /// Gets a value indicating whether stack trace has been set for this event. /// </summary> public bool HasStackTrace => CallSiteInformation?.StackTrace != null; /// <summary> /// Gets the stack frame of the method that did the logging. /// </summary> public StackFrame UserStackFrame => CallSiteInformation?.UserStackFrame; /// <summary> /// Gets the number index of the stack frame that represents the user /// code (not the NLog code). /// </summary> public int UserStackFrameNumber => CallSiteInformation?.UserStackFrameNumberLegacy ?? CallSiteInformation?.UserStackFrameNumber ?? 0; /// <summary> /// Gets the entire stack trace. /// </summary> public StackTrace StackTrace => CallSiteInformation?.StackTrace; /// <summary> /// Gets the callsite class name /// </summary> public string CallerClassName => CallSiteInformation?.GetCallerClassName(null, true, true, true); /// <summary> /// Gets the callsite member function name /// </summary> public string CallerMemberName => CallSiteInformation?.GetCallerMethodName(null, false, true, true); /// <summary> /// Gets the callsite source file path /// </summary> public string CallerFilePath => CallSiteInformation?.GetCallerFilePath(0); /// <summary> /// Gets the callsite source file line number /// </summary> public int CallerLineNumber => CallSiteInformation?.GetCallerLineNumber(0) ?? 0; /// <summary> /// Gets or sets the exception information. /// </summary> [CanBeNull] public Exception Exception { get; set; } /// <summary> /// Gets or sets the logger name. /// </summary> [CanBeNull] public string LoggerName { get; set; } /// <summary> /// Gets or sets the log message including any parameter placeholders. /// </summary> public string Message { get => _message; set { bool rebuildMessageTemplateParameters = ResetMessageTemplateParameters(); _message = value; ResetFormattedMessage(rebuildMessageTemplateParameters); } } /// <summary> /// Gets or sets the parameter values or null if no parameters have been specified. /// </summary> public object[] Parameters { get => _parameters; set { bool rebuildMessageTemplateParameters = ResetMessageTemplateParameters(); _parameters = value; ResetFormattedMessage(rebuildMessageTemplateParameters); } } /// <summary> /// Gets or sets the format provider that was provided while logging or <see langword="null" /> /// when no formatProvider was specified. /// </summary> public IFormatProvider FormatProvider { get => _formatProvider; set { if (_formatProvider != value) { _formatProvider = value; ResetFormattedMessage(false); } } } /// <summary> /// Gets or sets the message formatter for generating <see cref="LogEventInfo.FormattedMessage"/> /// Uses string.Format(...) when nothing else has been configured. /// </summary> public LogMessageFormatter MessageFormatter { get => _messageFormatter ?? LogManager.LogFactory.ActiveMessageFormatter; set { _messageFormatter = value ?? LogMessageStringFormatter.Default.MessageFormatter; ResetFormattedMessage(false); } } /// <summary> /// Gets the formatted message. /// </summary> public string FormattedMessage { get { if (_formattedMessage is null) { CalcFormattedMessage(); } return _formattedMessage; } } /// <summary> /// Checks if any per-event properties (Without allocation) /// </summary> public bool HasProperties { get { if (_properties != null) { return _properties.Count > 0; } else { return CreateOrUpdatePropertiesInternal(false)?.Count > 0; } } } /// <summary> /// Gets the dictionary of per-event context properties. /// </summary> public IDictionary<object, object> Properties => CreateOrUpdatePropertiesInternal(); /// <summary> /// Gets the dictionary of per-event context properties. /// Internal helper for the PropertiesDictionary type. /// </summary> /// <param name="forceCreate">Create the event-properties dictionary, even if no initial template parameters</param> /// <param name="templateParameters">Provided when having parsed the message template and capture template parameters (else null)</param> /// <returns></returns> internal PropertiesDictionary CreateOrUpdatePropertiesInternal(bool forceCreate = true, IList<MessageTemplateParameter> templateParameters = null) { var properties = _properties; if (properties is null) { if (forceCreate || templateParameters?.Count > 0 || (templateParameters is null && HasMessageTemplateParameters)) { properties = new PropertiesDictionary(templateParameters); Interlocked.CompareExchange(ref _properties, properties, null); if (templateParameters is null && (!forceCreate || HasMessageTemplateParameters)) { // Trigger capture of MessageTemplateParameters from logevent-message CalcFormattedMessage(); } } } else if (templateParameters != null) { properties.MessageProperties = templateParameters; } return _properties; } private bool HasMessageTemplateParameters { get { // Have not yet parsed/rendered the FormattedMessage, so check with ILogMessageFormatter if (_formattedMessage is null && _parameters?.Length > 0) { var logMessageFormatter = MessageFormatter.Target as ILogMessageFormatter; return logMessageFormatter?.HasProperties(this) ?? false; } return false; } } /// <summary> /// Gets the named parameters extracted from parsing <see cref="Message"/> as MessageTemplate /// </summary> public MessageTemplateParameters MessageTemplateParameters { get { if (_properties != null && _properties.MessageProperties.Count > 0) { return new MessageTemplateParameters(_properties.MessageProperties, _message, _parameters); } else if (_parameters?.Length > 0) { return new MessageTemplateParameters(_message, _parameters); } else { return MessageTemplateParameters.Empty; // No parameters, means nothing to parse } } } /// <summary> /// Creates the null event. /// </summary> /// <returns>Null log event.</returns> public static LogEventInfo CreateNullEvent() { return new LogEventInfo(LogLevel.Off, string.Empty, null, string.Empty, null, null); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="message">The message.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message) { return new LogEventInfo(logLevel, loggerName, null, message, null, null); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="formatProvider">The format provider.</param> /// <param name="message">The message.</param> /// <param name="parameters">The parameters.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> [MessageTemplateFormatMethod("message")] public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object[] parameters) { return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters, null); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="formatProvider">The format provider.</param> /// <param name="message">The message.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, object message) { Exception exception = message as Exception; if (exception is null && message is LogEventInfo logEvent) { logEvent.LoggerName = loggerName; logEvent.Level = logLevel; logEvent.FormatProvider = formatProvider ?? logEvent.FormatProvider; return logEvent; } formatProvider = formatProvider ?? (exception != null ? ExceptionMessageFormatProvider.Instance : null); return new LogEventInfo(logLevel, loggerName, formatProvider, "{0}", new[] { message }, exception); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="exception">The exception.</param> /// <param name="formatProvider">The format provider.</param> /// <param name="message">The message.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message) { return new LogEventInfo(logLevel, loggerName, formatProvider, message, null, exception); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="exception">The exception.</param> /// <param name="formatProvider">The format provider.</param> /// <param name="message">The message.</param> /// <param name="parameters">The parameters.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> [MessageTemplateFormatMethod("message")] public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object[] parameters) { return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters, exception); } /// <summary> /// Creates <see cref="AsyncLogEventInfo"/> from this <see cref="LogEventInfo"/> by attaching the specified asynchronous continuation. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <returns>Instance of <see cref="AsyncLogEventInfo"/> with attached continuation.</returns> public AsyncLogEventInfo WithContinuation(AsyncContinuation asyncContinuation) { return new AsyncLogEventInfo(this, asyncContinuation); } /// <summary> /// Returns a string representation of this log event. /// </summary> /// <returns>String representation of the log event.</returns> public override string ToString() { return $"Log Event: Logger='{LoggerName}' Level={Level} Message='{FormattedMessage}'"; } /// <summary> /// Sets the stack trace for the event info. /// </summary> /// <param name="stackTrace">The stack trace.</param> /// <param name="userStackFrame">Index of the first user stack frame within the stack trace (Negative means NLog should skip stackframes from System-assemblies).</param> public void SetStackTrace(StackTrace stackTrace, int userStackFrame) { GetCallSiteInformationInternal().SetStackTrace(stackTrace, userStackFrame >= 0 ? userStackFrame : (int?)null); } /// <summary> /// Sets the details retrieved from the Caller Information Attributes /// </summary> /// <param name="callerClassName"></param> /// <param name="callerMemberName"></param> /// <param name="callerFilePath"></param> /// <param name="callerLineNumber"></param> public void SetCallerInfo(string callerClassName, string callerMemberName, string callerFilePath, int callerLineNumber) { GetCallSiteInformationInternal().SetCallerInfo(callerClassName, callerMemberName, callerFilePath, callerLineNumber); } internal void AddCachedLayoutValue(Layout layout, object value) { if (_layoutCache is null) { var dictionary = new Dictionary<Layout, object>(); dictionary[layout] = value; // Faster than collection initializer if (Interlocked.CompareExchange(ref _layoutCache, dictionary, null) is null) { return; // No need to use lock } } lock (_layoutCache) { _layoutCache[layout] = value; } } internal bool TryGetCachedLayoutValue(Layout layout, out object value) { if (_layoutCache is null) { // We don't need lock to see if dictionary has been created value = null; return false; } lock (_layoutCache) { // dictionary is always non-empty when created return _layoutCache.TryGetValue(layout, out value); } } private static bool NeedToPreformatMessage(object[] parameters) { // we need to preformat message if it contains any parameters which could possibly // do logging in their ToString() if (parameters is null || parameters.Length == 0) { return false; } if (parameters.Length > 5) { // too many parameters, too costly to check return true; } for (int i = 0; i < parameters.Length; ++i) { if (!IsSafeToDeferFormatting(parameters[i])) return true; } return false; } private static bool IsSafeToDeferFormatting(object value) { return Convert.GetTypeCode(value) != TypeCode.Object; } internal bool IsLogEventMutableSafe() { if (Exception != null || _formattedMessage != null) return false; var properties = CreateOrUpdatePropertiesInternal(false); if (properties is null || properties.Count == 0) return true; // No mutable state, no need to precalculate if (properties.Count > 5) return false; // too many properties, too costly to check if (properties.Count == _parameters?.Length && properties.Count == properties.MessageProperties.Count) return true; // Already checked formatted message, no need to do it twice return HasImmutableProperties(properties); } private static bool HasImmutableProperties(PropertiesDictionary properties) { if (properties.Count == properties.MessageProperties.Count) { // Skip enumerator allocation when all properties comes from the message-template for (int i = 0; i < properties.MessageProperties.Count; ++i) { var property = properties.MessageProperties[i]; if (!IsSafeToDeferFormatting(property.Value)) return false; } } else { // Already spent the time on allocating a Dictionary, also have time for an enumerator foreach (var property in properties) { if (!IsSafeToDeferFormatting(property.Value)) return false; } } return true; } internal void SetMessageFormatter([NotNull] LogMessageFormatter messageFormatter, [CanBeNull] LogMessageFormatter singleTargetMessageFormatter) { bool hasCustomMessageFormatter = _messageFormatter != null; if (!hasCustomMessageFormatter) { _messageFormatter = messageFormatter; } if (NeedToPreformatMessage(_parameters)) { CalcFormattedMessage(); } else { if (!hasCustomMessageFormatter && singleTargetMessageFormatter != null && _parameters?.Length > 0 && _message?.Length < 256) { // Change MessageFormatter so it writes directly to StringBuilder without string-allocation _messageFormatter = singleTargetMessageFormatter; } } } private void CalcFormattedMessage() { try { _formattedMessage = MessageFormatter(this); } catch (Exception exception) { _formattedMessage = Message; InternalLogger.Warn(exception, "Error when formatting a message."); if (exception.MustBeRethrown()) { throw; } } } internal void AppendFormattedMessage(ILogMessageFormatter messageFormatter, System.Text.StringBuilder builder) { if (_formattedMessage != null) { builder.Append(_formattedMessage); } else if (_parameters?.Length > 0 && !string.IsNullOrEmpty(_message)) { int originalLength = builder.Length; try { messageFormatter.AppendFormattedMessage(this, builder); } catch (Exception ex) { builder.Length = originalLength; builder.Append(_message ?? string.Empty); InternalLogger.Warn(ex, "Error when formatting a message."); if (ex.MustBeRethrown()) { throw; } } } else { builder.Append(FormattedMessage); } } private void ResetFormattedMessage(bool rebuildMessageTemplateParameters) { _formattedMessage = null; if (rebuildMessageTemplateParameters && HasMessageTemplateParameters) { CalcFormattedMessage(); } } private bool ResetMessageTemplateParameters() { if (_properties != null) { if (HasMessageTemplateParameters) _properties.MessageProperties = null; return _properties.MessageProperties.Count == 0; } return false; } } }
using System.Collections.Generic; namespace Adform.AdServing.AhoCorasickTree.Sandbox.V8 { public class AhoCorasickTree { internal AhoCorasickTreeNode Root { get; set; } public AhoCorasickTree(IEnumerable<string> keywords) { Root = new AhoCorasickTreeNode(); if (keywords != null) { foreach (var p in keywords) { AddPatternToTree(p); } SetFailureNodes(); } } public bool Contains(string text) { var currentNode = Root; var length = text.Length; for (var i = 0; i < length; i = i + 2) { while (true) { var c1 = text[i]; var c2 = text[i+1]; var node = currentNode.GetTransition(c1); if (node == null) { currentNode = currentNode.Failure; if (currentNode == Root && i + 1 >= length) { break; } } else { if (node.IsWord) { return true; } currentNode = node; } node = currentNode.GetTransition(c2); if (node == null) { currentNode = currentNode.Failure; if (currentNode == Root) { break; } } else { if (node.IsWord) { return true; } currentNode = node; break; } } } return false; } public bool ContainsThatStart(string text) { return Contains(text, true); } private bool Contains(string text, bool onlyStarts) { var pointer = Root; for (var i = 0; i < text.Length; i++) { AhoCorasickTreeNode transition = null; while (transition == null) { transition = pointer.GetTransition(text[i]); if (pointer == Root) break; if (transition == null) pointer = pointer.Failure; } if (transition != null) pointer = transition; else if (onlyStarts) return false; if (pointer.Results.Count > 0) return true; } return false; } public IEnumerable<string> FindAll(string text) { var pointer = Root; foreach (var c in text) { var transition = GetTransition(c, ref pointer); if (transition != null) pointer = transition; foreach (var result in pointer.Results) yield return result; } } private AhoCorasickTreeNode GetTransition(char c, ref AhoCorasickTreeNode pointer) { AhoCorasickTreeNode transition = null; while (transition == null) { transition = pointer.GetTransition(c); if (pointer == Root) break; if (transition == null) pointer = pointer.Failure; } return transition; } private void SetFailureNodes() { var nodes = FailToRootNode(); FailUsingBFS(nodes); Root.Failure = Root; } private void AddPatternToTree(string pattern) { var node = Root; foreach (var c in pattern) { node = node.GetTransition(c) ?? node.AddTransition(c); } node.AddResult(pattern); node.IsWord = true; } private List<AhoCorasickTreeNode> FailToRootNode() { var nodes = new List<AhoCorasickTreeNode>(); foreach (var node in Root.Transitions) { node.Failure = Root; nodes.AddRange(node.Transitions); } return nodes; } private void FailUsingBFS(List<AhoCorasickTreeNode> nodes) { while (nodes.Count != 0) { var newNodes = new List<AhoCorasickTreeNode>(); foreach (var node in nodes) { var failure = node.ParentFailure; var value = node.Value; while (failure != null && !failure.ContainsTransition(value)) { failure = failure.Failure; } if (failure == null) { node.Failure = Root; } else { node.Failure = failure.GetTransition(value); node.AddResults(node.Failure.Results); if (!node.IsWord) { node.IsWord = failure.IsWord; } } newNodes.AddRange(node.Transitions); } nodes = newNodes; } } } }
#if !NET45PLUS // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace System.Collections.Immutable { /// <summary> /// An interface that describes the methods that the <see cref="ImmutableList{T}"/> and <see cref="ImmutableList{T}.Builder"/> types have in common. /// </summary> /// <typeparam name="T">The type of element in the collection.</typeparam> internal interface IImmutableListQueries<T> : IReadOnlyList<T> { /// <summary> /// Converts the elements in the current <see cref="ImmutableList{T}"/> to /// another type, and returns a list containing the converted elements. /// </summary> /// <param name="converter"> /// A <see cref="Func{T, TResult}"/> delegate that converts each element from /// one type to another type. /// </param> /// <typeparam name="TOutput"> /// The type of the elements of the target array. /// </typeparam> /// <returns> /// A <see cref="ImmutableList{T}"/> of the target type containing the converted /// elements from the current <see cref="ImmutableList{T}"/>. /// </returns> ImmutableList<TOutput> ConvertAll<TOutput>(Func<T, TOutput> converter); /// <summary> /// Performs the specified action on each element of the list. /// </summary> /// <param name="action">The <see cref="Action{T}"/> delegate to perform on each element of the list.</param> void ForEach(Action<T> action); /// <summary> /// Creates a shallow copy of a range of elements in the source <see cref="ImmutableList{T}"/>. /// </summary> /// <param name="index"> /// The zero-based <see cref="ImmutableList{T}"/> index at which the range /// starts. /// </param> /// <param name="count"> /// The number of elements in the range. /// </param> /// <returns> /// A shallow copy of a range of elements in the source <see cref="ImmutableList{T}"/>. /// </returns> ImmutableList<T> GetRange(int index, int count); /// <summary> /// Copies the entire <see cref="ImmutableList{T}"/> to a compatible one-dimensional /// array, starting at the beginning of the target array. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="Array"/> that is the destination of the elements /// copied from <see cref="ImmutableList{T}"/>. The <see cref="Array"/> must have /// zero-based indexing. /// </param> void CopyTo(T[] array); /// <summary> /// Copies the entire <see cref="ImmutableList{T}"/> to a compatible one-dimensional /// array, starting at the specified index of the target array. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="Array"/> that is the destination of the elements /// copied from <see cref="ImmutableList{T}"/>. The <see cref="Array"/> must have /// zero-based indexing. /// </param> /// <param name="arrayIndex"> /// The zero-based index in <paramref name="array"/> at which copying begins. /// </param> void CopyTo(T[] array, int arrayIndex); /// <summary> /// Copies a range of elements from the <see cref="ImmutableList{T}"/> to /// a compatible one-dimensional array, starting at the specified index of the /// target array. /// </summary> /// <param name="index"> /// The zero-based index in the source <see cref="ImmutableList{T}"/> at /// which copying begins. /// </param> /// <param name="array"> /// The one-dimensional <see cref="Array"/> that is the destination of the elements /// copied from <see cref="ImmutableList{T}"/>. The <see cref="Array"/> must have /// zero-based indexing. /// </param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <param name="count">The number of elements to copy.</param> void CopyTo(int index, T[] array, int arrayIndex, int count); /// <summary> /// Determines whether the <see cref="ImmutableList{T}"/> contains elements /// that match the conditions defined by the specified predicate. /// </summary> /// <param name="match"> /// The <see cref="Predicate{T}"/> delegate that defines the conditions of the elements /// to search for. /// </param> /// <returns> /// true if the <see cref="ImmutableList{T}"/> contains one or more elements /// that match the conditions defined by the specified predicate; otherwise, /// false. /// </returns> bool Exists(Predicate<T> match); /// <summary> /// Searches for an element that matches the conditions defined by the specified /// predicate, and returns the first occurrence within the entire <see cref="ImmutableList{T}"/>. /// </summary> /// <param name="match"> /// The <see cref="Predicate{T}"/> delegate that defines the conditions of the element /// to search for. /// </param> /// <returns> /// The first element that matches the conditions defined by the specified predicate, /// if found; otherwise, the default value for type <typeparamref name="T"/>. /// </returns> T Find(Predicate<T> match); /// <summary> /// Retrieves all the elements that match the conditions defined by the specified /// predicate. /// </summary> /// <param name="match"> /// The <see cref="Predicate{T}"/> delegate that defines the conditions of the elements /// to search for. /// </param> /// <returns> /// A <see cref="ImmutableList{T}"/> containing all the elements that match /// the conditions defined by the specified predicate, if found; otherwise, an /// empty <see cref="ImmutableList{T}"/>. /// </returns> ImmutableList<T> FindAll(Predicate<T> match); /// <summary> /// Searches for an element that matches the conditions defined by the specified /// predicate, and returns the zero-based index of the first occurrence within /// the entire <see cref="ImmutableList{T}"/>. /// </summary> /// <param name="match"> /// The <see cref="Predicate{T}"/> delegate that defines the conditions of the element /// to search for. /// </param> /// <returns> /// The zero-based index of the first occurrence of an element that matches the /// conditions defined by <paramref name="match"/>, if found; otherwise, -1. /// </returns> int FindIndex(Predicate<T> match); /// <summary> /// Searches for an element that matches the conditions defined by the specified /// predicate, and returns the zero-based index of the first occurrence within /// the range of elements in the <see cref="ImmutableList{T}"/> that extends /// from the specified index to the last element. /// </summary> /// <param name="startIndex">The zero-based starting index of the search.</param> /// <param name="match">The <see cref="Predicate{T}"/> delegate that defines the conditions of the element to search for.</param> /// <returns> /// The zero-based index of the first occurrence of an element that matches the /// conditions defined by <paramref name="match"/>, if found; otherwise, -1. /// </returns> int FindIndex(int startIndex, Predicate<T> match); /// <summary> /// Searches for an element that matches the conditions defined by the specified /// predicate, and returns the zero-based index of the first occurrence within /// the range of elements in the <see cref="ImmutableList{T}"/> that starts /// at the specified index and contains the specified number of elements. /// </summary> /// <param name="startIndex">The zero-based starting index of the search.</param> /// <param name="count">The number of elements in the section to search.</param> /// <param name="match">The <see cref="Predicate{T}"/> delegate that defines the conditions of the element to search for.</param> /// <returns> /// The zero-based index of the first occurrence of an element that matches the /// conditions defined by <paramref name="match"/>, if found; otherwise, -1. /// </returns> int FindIndex(int startIndex, int count, Predicate<T> match); /// <summary> /// Searches for an element that matches the conditions defined by the specified /// predicate, and returns the last occurrence within the entire <see cref="ImmutableList{T}"/>. /// </summary> /// <param name="match"> /// The <see cref="Predicate{T}"/> delegate that defines the conditions of the element /// to search for. /// </param> /// <returns> /// The last element that matches the conditions defined by the specified predicate, /// if found; otherwise, the default value for type <typeparamref name="T"/>. /// </returns> T FindLast(Predicate<T> match); /// <summary> /// Searches for an element that matches the conditions defined by the specified /// predicate, and returns the zero-based index of the last occurrence within /// the entire <see cref="ImmutableList{T}"/>. /// </summary> /// <param name="match"> /// The <see cref="Predicate{T}"/> delegate that defines the conditions of the element /// to search for. /// </param> /// <returns> /// The zero-based index of the last occurrence of an element that matches the /// conditions defined by <paramref name="match"/>, if found; otherwise, -1. /// </returns> int FindLastIndex(Predicate<T> match); /// <summary> /// Searches for an element that matches the conditions defined by the specified /// predicate, and returns the zero-based index of the last occurrence within /// the range of elements in the <see cref="ImmutableList{T}"/> that extends /// from the first element to the specified index. /// </summary> /// <param name="startIndex">The zero-based starting index of the backward search.</param> /// <param name="match">The <see cref="Predicate{T}"/> delegate that defines the conditions of the element /// to search for.</param> /// <returns> /// The zero-based index of the last occurrence of an element that matches the /// conditions defined by <paramref name="match"/>, if found; otherwise, -1. /// </returns> int FindLastIndex(int startIndex, Predicate<T> match); /// <summary> /// Searches for an element that matches the conditions defined by the specified /// predicate, and returns the zero-based index of the last occurrence within /// the range of elements in the <see cref="ImmutableList{T}"/> that contains /// the specified number of elements and ends at the specified index. /// </summary> /// <param name="startIndex">The zero-based starting index of the backward search.</param> /// <param name="count">The number of elements in the section to search.</param> /// <param name="match"> /// The <see cref="Predicate{T}"/> delegate that defines the conditions of the element /// to search for. /// </param> /// <returns> /// The zero-based index of the last occurrence of an element that matches the /// conditions defined by <paramref name="match"/>, if found; otherwise, -1. /// </returns> int FindLastIndex(int startIndex, int count, Predicate<T> match); /// <summary> /// Determines whether every element in the <see cref="ImmutableList{T}"/> /// matches the conditions defined by the specified predicate. /// </summary> /// <param name="match"> /// The <see cref="Predicate{T}"/> delegate that defines the conditions to check against /// the elements. /// </param> /// <returns> /// true if every element in the <see cref="ImmutableList{T}"/> matches the /// conditions defined by the specified predicate; otherwise, false. If the list /// has no elements, the return value is true. /// </returns> bool TrueForAll(Predicate<T> match); /// <summary> /// Searches the entire sorted <see cref="IReadOnlyList{T}"/> for an element /// using the default comparer and returns the zero-based index of the element. /// </summary> /// <param name="item">The object to locate. The value can be null for reference types.</param> /// <returns> /// The zero-based index of <paramref name="item"/> in the sorted <see cref="IReadOnlyList{T}"/>, /// if <paramref name="item"/> is found; otherwise, a negative number that is the bitwise complement /// of the index of the next element that is larger than <paramref name="item"/> or, if there is /// no larger element, the bitwise complement of <see cref="IReadOnlyCollection{T}.Count"/>. /// </returns> /// <exception cref="InvalidOperationException"> /// The default comparer <see cref="Comparer{T}.Default"/> cannot /// find an implementation of the <see cref="IComparable{T}"/> generic interface or /// the <see cref="IComparable"/> interface for type <typeparamref name="T"/>. /// </exception> int BinarySearch(T item); /// <summary> /// Searches the entire sorted <see cref="IReadOnlyList{T}"/> for an element /// using the specified comparer and returns the zero-based index of the element. /// </summary> /// <param name="item">The object to locate. The value can be null for reference types.</param> /// <param name="comparer"> /// The <see cref="IComparer{T}"/> implementation to use when comparing /// elements.-or-null to use the default comparer <see cref="Comparer{T}.Default"/>. /// </param> /// <returns> /// The zero-based index of <paramref name="item"/> in the sorted <see cref="IReadOnlyList{T}"/>, /// if <paramref name="item"/> is found; otherwise, a negative number that is the bitwise complement /// of the index of the next element that is larger than <paramref name="item"/> or, if there is /// no larger element, the bitwise complement of <see cref="IReadOnlyCollection{T}.Count"/>. /// </returns> /// <exception cref="InvalidOperationException"> /// <paramref name="comparer"/> is null, and the default comparer <see cref="Comparer{T}.Default"/> /// cannot find an implementation of the <see cref="IComparable{T}"/> generic interface /// or the <see cref="IComparable"/> interface for type <typeparamref name="T"/>. /// </exception> int BinarySearch(T item, IComparer<T> comparer); /// <summary> /// Searches a range of elements in the sorted <see cref="IReadOnlyList{T}"/> /// for an element using the specified comparer and returns the zero-based index /// of the element. /// </summary> /// <param name="index">The zero-based starting index of the range to search.</param> /// <param name="count"> The length of the range to search.</param> /// <param name="item">The object to locate. The value can be null for reference types.</param> /// <param name="comparer"> /// The <see cref="IComparer{T}"/> implementation to use when comparing /// elements, or null to use the default comparer <see cref="Comparer{T}.Default"/>. /// </param> /// <returns> /// The zero-based index of <paramref name="item"/> in the sorted <see cref="IReadOnlyList{T}"/>, /// if <paramref name="item"/> is found; otherwise, a negative number that is the bitwise complement /// of the index of the next element that is larger than <paramref name="item"/> or, if there is /// no larger element, the bitwise complement of <see cref="IReadOnlyCollection{T}.Count"/>. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index"/> is less than 0.-or-<paramref name="count"/> is less than 0. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="index"/> and <paramref name="count"/> do not denote a valid range in the <see cref="IReadOnlyList{T}"/>. /// </exception> /// <exception cref="InvalidOperationException"> /// <paramref name="comparer"/> is null, and the default comparer <see cref="Comparer{T}.Default"/> /// cannot find an implementation of the <see cref="IComparable{T}"/> generic interface /// or the <see cref="IComparable"/> interface for type <typeparamref name="T"/>. /// </exception> int BinarySearch(int index, int count, T item, IComparer<T> comparer); } } #endif
#region License /* * ResponseStream.cs * * This code is derived from System.Net.ResponseStream.cs of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2014 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * Gonzalo Paniagua Javier <[email protected]> */ #endregion using System; using System.IO; using System.Text; namespace WebSocketSharp.Net { // FIXME: Does this buffer the response until Close? // Update: we send a single packet for the first non-chunked Write // What happens when we set content-length to X and write X-1 bytes then close? // what if we don't set content-length at all? internal class ResponseStream : Stream { #region Private Static Fields private static byte [] _crlf = new byte [] { 13, 10 }; #endregion #region Private Fields private bool _disposed; private bool _ignoreErrors; private HttpListenerResponse _response; private Stream _stream; private bool _trailerSent; #endregion #region Internal Constructors internal ResponseStream ( Stream stream, HttpListenerResponse response, bool ignoreErrors) { _stream = stream; _response = response; _ignoreErrors = ignoreErrors; } #endregion #region Public Properties public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { throw new NotSupportedException (); } } public override long Position { get { throw new NotSupportedException (); } set { throw new NotSupportedException (); } } #endregion #region Private Methods private static byte [] getChunkSizeBytes (int size, bool final) { return Encoding.ASCII.GetBytes ( String.Format ("{0:x}\r\n{1}", size, final ? "\r\n" : "")); } private MemoryStream getHeaders (bool closing) { if (_response.HeadersSent) return null; var stream = new MemoryStream (); _response.SendHeaders (closing, stream); return stream; } #endregion #region Internal Methods internal void InternalWrite (byte [] buffer, int offset, int count) { if (_ignoreErrors) { try { _stream.Write (buffer, offset, count); } catch { } } else { _stream.Write (buffer, offset, count); } } #endregion #region Public Methods public override IAsyncResult BeginRead ( byte [] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException (); } public override IAsyncResult BeginWrite ( byte [] buffer, int offset, int count, AsyncCallback callback, object state) { if (_disposed) throw new ObjectDisposedException (GetType ().ToString ()); var stream = getHeaders (false); var chunked = _response.SendChunked; byte [] bytes = null; if (stream != null) { var start = stream.Position; stream.Position = stream.Length; if (chunked) { bytes = getChunkSizeBytes (count, false); stream.Write (bytes, 0, bytes.Length); } stream.Write (buffer, offset, count); buffer = stream.GetBuffer (); offset = (int) start; count = (int) (stream.Position - start); } else if (chunked) { bytes = getChunkSizeBytes (count, false); InternalWrite (bytes, 0, bytes.Length); } return _stream.BeginWrite (buffer, offset, count, callback, state); } public override void Close () { if (_disposed) return; _disposed = true; var stream = getHeaders (true); var chunked = _response.SendChunked; byte [] bytes = null; if (stream != null) { var start = stream.Position; if (chunked && !_trailerSent) { bytes = getChunkSizeBytes (0, true); stream.Position = stream.Length; stream.Write (bytes, 0, bytes.Length); } InternalWrite ( stream.GetBuffer (), (int) start, (int) (stream.Length - start)); _trailerSent = true; } else if (chunked && !_trailerSent) { bytes = getChunkSizeBytes (0, true); InternalWrite (bytes, 0, bytes.Length); _trailerSent = true; } _response.Close (); } public override int EndRead (IAsyncResult asyncResult) { throw new NotSupportedException (); } public override void EndWrite (IAsyncResult asyncResult) { if (_disposed) throw new ObjectDisposedException (GetType ().ToString ()); Action<IAsyncResult> endWrite = ares => { _stream.EndWrite (ares); if (_response.SendChunked) _stream.Write (_crlf, 0, 2); }; if (_ignoreErrors) { try { endWrite (asyncResult); } catch { } } else { endWrite (asyncResult); } } public override void Flush () { } public override int Read (byte [] buffer, int offset, int count) { throw new NotSupportedException (); } public override long Seek (long offset, SeekOrigin origin) { throw new NotSupportedException (); } public override void SetLength (long value) { throw new NotSupportedException (); } public override void Write (byte [] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException (GetType ().ToString ()); var stream = getHeaders (false); var chunked = _response.SendChunked; byte [] bytes = null; if (stream != null) { // After the possible preamble for the encoding. var start = stream.Position; stream.Position = stream.Length; if (chunked) { bytes = getChunkSizeBytes (count, false); stream.Write (bytes, 0, bytes.Length); } var newCount = Math.Min ( count, 16384 - (int) stream.Position + (int) start); stream.Write (buffer, offset, newCount); count -= newCount; offset += newCount; InternalWrite ( stream.GetBuffer (), (int) start, (int) (stream.Length - start)); stream.SetLength (0); stream.Capacity = 0; // 'dispose' the buffer in stream. } else if (chunked) { bytes = getChunkSizeBytes (count, false); InternalWrite (bytes, 0, bytes.Length); } if (count > 0) InternalWrite (buffer, offset, count); if (chunked) InternalWrite (_crlf, 0, 2); } #endregion } }
using System; using System.Diagnostics; using System.Threading; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2007 August 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes for win32 ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-03-09 19:31:43 4ae453ea7be69018d8c16eb8dabe05617397dc4d ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** The code in this file is only used if we are compiling multithreaded ** on a win32 system. */ #if SQLITE_MUTEX_W32 /* ** Each recursive mutex is an instance of the following structure. */ struct sqlite3_mutex { CRITICAL_SECTION mutex; /* Mutex controlling the lock */ int id; /* Mutex type */ int nRef; /* Number of enterances */ DWORD owner; /* Thread holding this mutex */ #if SQLITE_DEBUG int trace; /* True to trace changes */ #endif }; //#define SQLITE_W32_MUTEX_INITIALIZER { 0 } #if SQLITE_DEBUG //#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 } #else //#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0 } #endif /* ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP, ** or WinCE. Return false (zero) for Win95, Win98, or WinME. ** ** Here is an interesting observation: Win95, Win98, and WinME lack ** the LockFileEx() API. But we can still statically link against that ** API as long as we don't call it win running Win95/98/ME. A call to ** this routine is used to determine if the host is Win95/98/ME or ** WinNT/2K/XP so that we will know whether or not we can safely call ** the LockFileEx() API. ** ** mutexIsNT() is only used for the TryEnterCriticalSection() API call, ** which is only available if your application was compiled with ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only ** call to TryEnterCriticalSection() is #ifdef'ed out, so #if ** this out as well. */ #if FALSE #if SQLITE_OS_WINCE //# define mutexIsNT() (1) #else static int mutexIsNT(void){ static int osType = 0; if( osType==0 ){ OSVERSIONINFO sInfo; sInfo.dwOSVersionInfoSize = sizeof(sInfo); GetVersionEx(&sInfo); osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1; } return osType==2; } #endif //* SQLITE_OS_WINCE */ #endif #if SQLITE_DEBUG /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use only inside Debug.Assert() statements. */ static int winMutexHeld(sqlite3_mutex p){ return p.nRef!=0 && p.owner==GetCurrentThreadId(); } static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){ return p->nRef==0 || p->owner!=tid; } static int winMutexNotheld(sqlite3_mutex *p){ DWORD tid = GetCurrentThreadId(); return winMutexNotheld2(p, tid); } #endif /* ** Initialize and deinitialize the mutex subsystem. */ static sqlite3_mutex winMutex_staticMutexes[6] = { SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER }; static int winMutex_isInit = 0; /* As winMutexInit() and winMutexEnd() are called as part ** of the sqlite3_initialize and sqlite3_shutdown() ** processing, the "interlocked" magic is probably not ** strictly necessary. */ static long winMutex_lock = 0; static int winMutexInit(void){ /* The first to increment to 1 does actual initialization */ if( InterlockedCompareExchange(winMutex_lock, 1, 0)==0 ){ int i; for(i=0; i<ArraySize(winMutex_staticMutexes); i++){ InitializeCriticalSection(&winMutex_staticMutexes[i].mutex); } winMutex_isInit = 1; }else{ /* Someone else is in the process of initing the static mutexes */ while( !winMutex_isInit ){ Sleep(1); } } return SQLITE_OK; } static int winMutexEnd(void){ /* The first to decrement to 0 does actual shutdown ** (which should be the last to shutdown.) */ if( InterlockedCompareExchange(winMutex_lock, 0, 1)==1 ){ if( winMutex_isInit==1 ){ int i; for(i=0; i<ArraySize(winMutex_staticMutexes); i++){ DeleteCriticalSection(&winMutex_staticMutexes[i].mutex); } winMutex_isInit = 0; } } return SQLITE_OK; } /* ** The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. If it returns NULL ** that means that a mutex could not be allocated. SQLite ** will unwind its stack and return an error. The argument ** to sqlite3_mutex_alloc() is one of these integer constants: ** ** <ul> ** <li> SQLITE_MUTEX_FAST ** <li> SQLITE_MUTEX_RECURSIVE ** <li> SQLITE_MUTEX_STATIC_MASTER ** <li> SQLITE_MUTEX_STATIC_MEM ** <li> SQLITE_MUTEX_STATIC_MEM2 ** <li> SQLITE_MUTEX_STATIC_PRNG ** <li> SQLITE_MUTEX_STATIC_LRU ** <li> SQLITE_MUTEX_STATIC_LRU2 ** </ul> ** ** The first two constants cause sqlite3_mutex_alloc() to create ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does ** not want to. But SQLite will only request a recursive mutex in ** cases where it really needs one. If a faster non-recursive mutex ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** ** The other allowed parameters to sqlite3_mutex_alloc() each return ** a pointer to a static preexisting mutex. Six static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal ** use by SQLite only. Applications that use SQLite mutexes should ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or ** SQLITE_MUTEX_RECURSIVE. ** ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() ** returns a different mutex on every call. But for the static ** mutex types, the same mutex is returned on every call that has ** the same type number. */ static sqlite3_mutex *winMutexAlloc(int iType){ sqlite3_mutex p; switch( iType ){ case SQLITE_MUTEX_FAST: case SQLITE_MUTEX_RECURSIVE: { p = sqlite3MallocZero( sizeof(*p) ); if( p ){ p.id = iType; InitializeCriticalSection(p.mutex); } break; } default: { Debug.Assert( winMutex_isInit==1 ); Debug.Assert(iType-2 >= 0 ); assert( iType-2 < ArraySize(winMutex_staticMutexes) ); p = &winMutex_staticMutexes[iType-2]; p.id = iType; break; } } return p; } /* ** This routine deallocates a previously ** allocated mutex. SQLite is careful to deallocate every ** mutex that it allocates. */ static void winMutexFree(sqlite3_mutex p){ Debug.Assert(p ); Debug.Assert(p.nRef==0 ); Debug.Assert(p.id==SQLITE_MUTEX_FAST || p.id==SQLITE_MUTEX_RECURSIVE ); DeleteCriticalSection(p.mutex); sqlite3DbFree(db,p); } /* ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can ** be entered multiple times by the same thread. In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. If the same thread tries to enter any other kind of mutex ** more than once, the behavior is undefined. */ static void winMutexEnter(sqlite3_mutex p){ DWORD tid = GetCurrentThreadId(); assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); EnterCriticalSection(&p->mutex); p->owner = tid; p->nRef++; #if SQLITE_DEBUG if( p->trace ){ printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); } #endif } static int winMutexTry(sqlite3_mutex *p){ #if !NDEBUG DWORD tid = GetCurrentThreadId(); #endif int rc = SQLITE_BUSY; assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); /* ** The sqlite3_mutex_try() routine is very rarely used, and when it ** is used it is merely an optimization. So it is OK for it to always ** fail. ** ** The TryEnterCriticalSection() interface is only available on WinNT. ** And some windows compilers complain if you try to use it without ** first doing some #defines that prevent SQLite from building on Win98. ** For that reason, we will omit this optimization for now. See ** ticket #2685. */ #if FALSE if( mutexIsNT() && TryEnterCriticalSection(p.mutex) ){ p.owner = tid; p.nRef++; rc = SQLITE_OK; } #else UNUSED_PARAMETER(p); #endif #if SQLITE_DEBUG if( rc==SQLITE_OK && p->trace ){ printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); } #endif return rc; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered or ** is not currently allocated. SQLite will never do either. */ static void winMutexLeave(sqlite3_mutex p){ #if !NDEBUG DWORD tid = GetCurrentThreadId(); #endif Debug.Assert(p.nRef>0 ); Debug.Assert(p.owner==tid ); p.nRef--; Debug.Assert(p.nRef==0 || p.id==SQLITE_MUTEX_RECURSIVE ); LeaveCriticalSection(p.mutex); #if SQLITE_DEBUG if( p->trace ){ printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); } #endif } sqlite3_mutex_methods *sqlite3DefaultMutex(void){ static sqlite3_mutex_methods sMutex = { winMutexInit, winMutexEnd, winMutexAlloc, winMutexFree, winMutexEnter, winMutexTry, winMutexLeave, #if SQLITE_DEBUG winMutexHeld, winMutexNotheld #else null, null #endif }; return &sMutex; } #endif // * SQLITE_MUTEX_W32 */ } }
namespace BrowseDotNet.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class initdatabase : DbMigration { public override void Up() { CreateTable( "dbo.IdentityRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.IdentityUserRoles", c => new { RoleId = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), IdentityRole_Id = c.String(maxLength: 128), }) .PrimaryKey(t => new { t.RoleId, t.UserId }) .ForeignKey("dbo.IdentityRoles", t => t.IdentityRole_Id) .ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId) .Index(t => t.IdentityRole_Id); CreateTable( "dbo.SearchKeys", c => new { ID = c.Int(nullable: false, identity: true), Term = c.String(nullable: false, maxLength: 20), DateCreated = c.DateTime(nullable: false), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.Snippets", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 50), Description = c.String(nullable: false, maxLength: 300), DateCreated = c.DateTime(nullable: false), Website = c.String(maxLength: 200), ProgrammingLanguageID = c.Int(nullable: false), }) .PrimaryKey(t => t.ID) .ForeignKey("dbo.ProgrammingLanguages", t => t.ProgrammingLanguageID, cascadeDelete: true) .Index(t => t.ProgrammingLanguageID); CreateTable( "dbo.ProgrammingLanguages", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 20), DateCreated = c.DateTime(nullable: false), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.Solutions", c => new { ID = c.Int(nullable: false, identity: true), Author = c.String(maxLength: 50), Name = c.String(nullable: false, maxLength: 100), Description = c.String(nullable: false, maxLength: 300), Website = c.String(maxLength: 200), DateRegistered = c.DateTime(nullable: false), SolutionTypeID = c.Int(nullable: false), ProgrammingLanguage_ID = c.Int(), }) .PrimaryKey(t => t.ID) .ForeignKey("dbo.SolutionTypes", t => t.SolutionTypeID, cascadeDelete: true) .ForeignKey("dbo.ProgrammingLanguages", t => t.ProgrammingLanguage_ID) .Index(t => t.SolutionTypeID) .Index(t => t.ProgrammingLanguage_ID); CreateTable( "dbo.SolutionTypes", c => new { ID = c.Int(nullable: false, identity: true), Type = c.String(nullable: false, maxLength: 50), DateCreated = c.DateTime(nullable: false), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.Users", c => new { Id = c.String(nullable: false, maxLength: 128), Email = c.String(), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.IdentityUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(maxLength: 128), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.UserId) .Index(t => t.UserId); CreateTable( "dbo.IdentityUserLogins", c => new { UserId = c.String(nullable: false, maxLength: 128), LoginProvider = c.String(), ProviderKey = c.String(), User_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.UserId) .ForeignKey("dbo.Users", t => t.User_Id) .Index(t => t.User_Id); CreateTable( "dbo.SnippetSearchKeys", c => new { Snippet_ID = c.Int(nullable: false), SearchKey_ID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.Snippet_ID, t.SearchKey_ID }) .ForeignKey("dbo.Snippets", t => t.Snippet_ID, cascadeDelete: true) .ForeignKey("dbo.SearchKeys", t => t.SearchKey_ID, cascadeDelete: true) .Index(t => t.Snippet_ID) .Index(t => t.SearchKey_ID); CreateTable( "dbo.SolutionSearchKeys", c => new { Solution_ID = c.Int(nullable: false), SearchKey_ID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.Solution_ID, t.SearchKey_ID }) .ForeignKey("dbo.Solutions", t => t.Solution_ID, cascadeDelete: true) .ForeignKey("dbo.SearchKeys", t => t.SearchKey_ID, cascadeDelete: true) .Index(t => t.Solution_ID) .Index(t => t.SearchKey_ID); } public override void Down() { DropForeignKey("dbo.IdentityUserRoles", "UserId", "dbo.Users"); DropForeignKey("dbo.IdentityUserLogins", "User_Id", "dbo.Users"); DropForeignKey("dbo.IdentityUserClaims", "UserId", "dbo.Users"); DropForeignKey("dbo.Solutions", "ProgrammingLanguage_ID", "dbo.ProgrammingLanguages"); DropForeignKey("dbo.Solutions", "SolutionTypeID", "dbo.SolutionTypes"); DropForeignKey("dbo.SolutionSearchKeys", "SearchKey_ID", "dbo.SearchKeys"); DropForeignKey("dbo.SolutionSearchKeys", "Solution_ID", "dbo.Solutions"); DropForeignKey("dbo.Snippets", "ProgrammingLanguageID", "dbo.ProgrammingLanguages"); DropForeignKey("dbo.SnippetSearchKeys", "SearchKey_ID", "dbo.SearchKeys"); DropForeignKey("dbo.SnippetSearchKeys", "Snippet_ID", "dbo.Snippets"); DropForeignKey("dbo.IdentityUserRoles", "IdentityRole_Id", "dbo.IdentityRoles"); DropIndex("dbo.SolutionSearchKeys", new[] { "SearchKey_ID" }); DropIndex("dbo.SolutionSearchKeys", new[] { "Solution_ID" }); DropIndex("dbo.SnippetSearchKeys", new[] { "SearchKey_ID" }); DropIndex("dbo.SnippetSearchKeys", new[] { "Snippet_ID" }); DropIndex("dbo.IdentityUserLogins", new[] { "User_Id" }); DropIndex("dbo.IdentityUserClaims", new[] { "UserId" }); DropIndex("dbo.Solutions", new[] { "ProgrammingLanguage_ID" }); DropIndex("dbo.Solutions", new[] { "SolutionTypeID" }); DropIndex("dbo.Snippets", new[] { "ProgrammingLanguageID" }); DropIndex("dbo.IdentityUserRoles", new[] { "IdentityRole_Id" }); DropIndex("dbo.IdentityUserRoles", new[] { "UserId" }); DropTable("dbo.SolutionSearchKeys"); DropTable("dbo.SnippetSearchKeys"); DropTable("dbo.IdentityUserLogins"); DropTable("dbo.IdentityUserClaims"); DropTable("dbo.Users"); DropTable("dbo.SolutionTypes"); DropTable("dbo.Solutions"); DropTable("dbo.ProgrammingLanguages"); DropTable("dbo.Snippets"); DropTable("dbo.SearchKeys"); DropTable("dbo.IdentityUserRoles"); DropTable("dbo.IdentityRoles"); } } }
//! \file ArcDAT.cs //! \date 2018 Sep 20 //! \brief Lazycrew resource archive. // // Copyright (C) 2018 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Text.RegularExpressions; using GameRes.Utility; // [031024][Lazycrew] Sister Mermaid // [020927][Ga-Bang] Sorairo Memories namespace GameRes.Formats.Lazycrew { internal class DirEntry { public string Name; public int Offset; public int Count; } [Export(typeof(ArchiveFormat))] public class DatOpener : ArchiveFormat { public override string Tag { get { return "DAT/LAZYCREW"; } } public override string Description { get { return "Lazycrew resource archive"; } } public override uint Signature { get { return 0; } } public override bool IsHierarchic { get { return true; } } public override bool CanWrite { get { return false; } } public DatOpener () { Extensions = new string[] { "dat", "" }; Signatures = new uint[] { 2, 0 }; } static readonly Regex NamePattern = new Regex (@"^(?:(?<num>0\d\d\d)\.dat|data(?<num>\d+)?)$", RegexOptions.IgnoreCase); const uint DefaultPcmKey = 0x4B5AB4A5; public override ArcFile TryOpen (ArcView file) { var name = Path.GetFileName (file.Name); if (!NamePattern.IsMatch (name)) return null; var match = NamePattern.Match (name); int name_id = 1; var num_str = match.Groups["num"].Value; if (!string.IsNullOrEmpty (num_str)) name_id = Int32.Parse (num_str); if (name_id < 1) return null; ArcView index = file; try { if (name_id != 1) { string index_name; if (file.Name.HasExtension (".dat")) index_name = VFS.ChangeFileName (file.Name, "0001.dat"); else index_name = VFS.ChangeFileName (file.Name, "data"); if (!VFS.FileExists (index_name)) return null; index = VFS.OpenView (index_name); } var dir = ReadIndex (index, name_id, file.MaxOffset); if (null == dir || 0 == dir.Count) return null; return new ArcFile (file, this, dir); } finally { if (index != file) index.Dispose(); } } List<Entry> ReadIndex (ArcView index, int arc_id, long arc_length) { int dir_count = index.View.ReadInt32 (0); if (dir_count <= 0 || dir_count > 20) return null; var dir_list = new List<DirEntry> (dir_count); int dir_offset = 4; int first_offset = dir_count * 0x10 + 4; for (int i = 0; i < dir_count; ++i) { var dir_entry = new DirEntry { Name = index.View.ReadString (dir_offset, 8), Offset = index.View.ReadInt32 (dir_offset+8), Count = index.View.ReadInt32 (dir_offset+12), }; if (dir_entry.Offset < first_offset || dir_entry.Offset >= index.MaxOffset || !IsSaneCount (dir_entry.Count)) return null; dir_list.Add (dir_entry); dir_offset += 16; } var file_list = new List<Entry>(); foreach (var dir in dir_list) { dir_offset = dir.Offset; string type = ""; if (dir.Name.Equals ("image", StringComparison.OrdinalIgnoreCase)) type = "image"; else if (dir.Name.Equals ("sound", StringComparison.OrdinalIgnoreCase)) type = "audio"; for (int i = 0; i < dir.Count; ++i) { int id = index.View.ReadUInt16 (dir_offset); if (id == arc_id) { var entry = new Entry { Name = Path.Combine (dir.Name, i.ToString ("D5")), Type = type, Offset = index.View.ReadUInt32 (dir_offset+2), Size = index.View.ReadUInt32 (dir_offset+6), }; if (!entry.CheckPlacement (arc_length)) return null; file_list.Add (entry); } dir_offset += 10; } } return file_list; } public override Stream OpenEntry (ArcFile arc, Entry entry) { if (entry.Type == "audio") { uint signature = arc.File.View.ReadUInt32 (entry.Offset); if (signature == 0x10000 || signature == 0) return OpenAudio (arc, entry); else if (signature == 1 || signature == 0x10001) return arc.File.CreateStream (entry.Offset+4, entry.Size-4); } return base.OpenEntry (arc, entry); } Stream OpenAudio (ArcFile arc, Entry entry) { var riff_header = new byte[0x2C]; LittleEndian.Pack (AudioFormat.Wav.Signature, riff_header, 0); LittleEndian.Pack (0x45564157, riff_header, 8); // 'WAVE' LittleEndian.Pack (0x20746d66, riff_header, 12); // 'fmt ' LittleEndian.Pack (0x10, riff_header, 16); arc.File.View.Read (entry.Offset+4, riff_header, 20, 0x10); LittleEndian.Pack (0x61746164, riff_header, 0x24); // 'data' uint data_size = arc.File.View.ReadUInt32 (entry.Offset+0x16); LittleEndian.Pack (data_size + 0x24u, riff_header, 4); LittleEndian.Pack (data_size, riff_header, 0x28); var pcm = arc.File.View.ReadBytes (entry.Offset+0x1A, data_size); DecryptData (pcm, DefaultPcmKey); var riff_data = new MemoryStream (pcm); return new PrefixStream (riff_header, riff_data); } public override IImageDecoder OpenImage (ArcFile arc, Entry entry) { var input = arc.OpenBinaryEntry (entry); int fmt = (int)input.Signature & 0xFFFF; if (fmt > 4) return ImageFormatDecoder.Create (input); var header = input.ReadHeader (14); input.Position = 0; int hpos = 2; if (1 == fmt || 3 == fmt) hpos = 8; int cmp = header.ToUInt16 (hpos); int bpp = 0; switch (cmp & 0xFF) { case 2: bpp = 4; break; case 3: bpp = 8; break; case 5: bpp = 24; break; default: return ImageFormatDecoder.Create (input); } var info = new LcImageMetaData { Width = header.ToUInt16 (hpos+2), Height = header.ToUInt16 (hpos+4), BPP = bpp, Format = fmt, Compression = cmp, DataOffset = hpos + 6, }; return new LcImageDecoder (input, info); } void DecryptData (byte[] data, uint key) { for (int i = 0; i < data.Length; ++i) { data[i] ^= (byte)key; key = data[i] ^ ((key << 9) | (key >> 23) & 0x1F0); } } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Ntfs { using System; using System.Collections.Generic; using System.IO; internal class ClusterBitmap : IDisposable { private File _file; private Bitmap _bitmap; private long _nextDataCluster; private bool _fragmentedDiskMode; public ClusterBitmap(File file) { _file = file; _bitmap = new Bitmap( _file.OpenStream(AttributeType.Data, null, FileAccess.ReadWrite), Utilities.Ceil(file.Context.BiosParameterBlock.TotalSectors64, file.Context.BiosParameterBlock.SectorsPerCluster)); } internal Bitmap Bitmap { get { return _bitmap; } } public void Dispose() { if (_bitmap != null) { _bitmap.Dispose(); _bitmap = null; } } /// <summary> /// Allocates clusters from the disk. /// </summary> /// <param name="count">The number of clusters to allocate.</param> /// <param name="proposedStart">The proposed start cluster (or -1).</param> /// <param name="isMft"><c>true</c> if this attribute is the $MFT\$DATA attribute.</param> /// <param name="total">The total number of clusters in the file, including this allocation.</param> /// <returns>The list of cluster allocations.</returns> public Tuple<long, long>[] AllocateClusters(long count, long proposedStart, bool isMft, long total) { List<Tuple<long, long>> result = new List<Tuple<long, long>>(); long numFound = 0; long totalClusters = _file.Context.RawStream.Length / _file.Context.BiosParameterBlock.BytesPerCluster; if (isMft) { // First, try to extend the existing cluster run (if available) if (proposedStart >= 0) { numFound += ExtendRun(count - numFound, result, proposedStart, totalClusters); } // The MFT grows sequentially across the disk if (numFound < count && !_fragmentedDiskMode) { numFound += FindClusters(count - numFound, result, 0, totalClusters, isMft, true, 0); } if (numFound < count) { numFound += FindClusters(count - numFound, result, 0, totalClusters, isMft, false, 0); } } else { // First, try to extend the existing cluster run (if available) if (proposedStart >= 0) { numFound += ExtendRun(count - numFound, result, proposedStart, totalClusters); } // Try to find a contiguous range if (numFound < count && !_fragmentedDiskMode) { numFound += FindClusters(count - numFound, result, totalClusters / 8, totalClusters, isMft, true, total / 4); } if (numFound < count) { numFound += FindClusters(count - numFound, result, totalClusters / 8, totalClusters, isMft, false, 0); } if (numFound < count) { numFound = FindClusters(count - numFound, result, totalClusters / 16, totalClusters / 8, isMft, false, 0); } if (numFound < count) { numFound = FindClusters(count - numFound, result, totalClusters / 32, totalClusters / 16, isMft, false, 0); } if (numFound < count) { numFound = FindClusters(count - numFound, result, 0, totalClusters / 32, isMft, false, 0); } } if (numFound < count) { FreeClusters(result.ToArray()); throw new IOException("Out of disk space"); } // If we found more than two clusters, or we have a fragmented result, // then switch out of trying to allocate contiguous ranges. Similarly, // switch back if we found a resonable quantity in a single span. if ((numFound > 4 && result.Count == 1) || result.Count > 1) { _fragmentedDiskMode = (numFound / result.Count) < 4; } return result.ToArray(); } internal void MarkAllocated(long first, long count) { _bitmap.MarkPresentRange(first, count); } internal void FreeClusters(params Tuple<long, long>[] runs) { foreach (var run in runs) { #if NET20 _bitmap.MarkAbsentRange(run.First, run.Second); #else _bitmap.MarkAbsentRange(run.Item1, run.Item2); #endif } } internal void FreeClusters(params Range<long, long>[] runs) { foreach (var run in runs) { _bitmap.MarkAbsentRange(run.Offset, run.Count); } } /// <summary> /// Sets the total number of clusters managed in the volume. /// </summary> /// <param name="numClusters">Total number of clusters in the volume.</param> /// <remarks> /// Any clusters represented in the bitmap beyond the total number in the volume are marked as in-use. /// </remarks> internal void SetTotalClusters(long numClusters) { long actualClusters = _bitmap.SetTotalEntries(numClusters); if (actualClusters != numClusters) { MarkAllocated(numClusters, actualClusters - numClusters); } } private long ExtendRun(long count, List<Tuple<long, long>> result, long start, long end) { long focusCluster = start; while (!_bitmap.IsPresent(focusCluster) && focusCluster < end && focusCluster - start < count) { ++focusCluster; } long numFound = focusCluster - start; if (numFound > 0) { _bitmap.MarkPresentRange(start, numFound); result.Add(new Tuple<long, long>(start, numFound)); } return numFound; } /// <summary> /// Finds one or more free clusters in a range. /// </summary> /// <param name="count">The number of clusters required.</param> /// <param name="result">The list of clusters found (i.e. out param).</param> /// <param name="start">The first cluster in the range to look at.</param> /// <param name="end">The last cluster in the range to look at (exclusive).</param> /// <param name="isMft">Indicates if the clusters are for the MFT.</param> /// <param name="contiguous">Indicates if contiguous clusters are required.</param> /// <param name="headroom">Indicates how many clusters to skip before next allocation, to prevent fragmentation.</param> /// <returns>The number of clusters found in the range.</returns> private long FindClusters(long count, List<Tuple<long, long>> result, long start, long end, bool isMft, bool contiguous, long headroom) { long numFound = 0; long focusCluster; if (isMft) { focusCluster = start; } else { if (_nextDataCluster < start || _nextDataCluster >= end) { _nextDataCluster = start; } focusCluster = _nextDataCluster; } long numInspected = 0; while (numFound < count && focusCluster >= start && numInspected < end - start) { if (!_bitmap.IsPresent(focusCluster)) { // Start of a run... long runStart = focusCluster; ++focusCluster; while (!_bitmap.IsPresent(focusCluster) && focusCluster - runStart < (count - numFound)) { ++focusCluster; ++numInspected; } if (!contiguous || (focusCluster - runStart) == (count - numFound)) { _bitmap.MarkPresentRange(runStart, focusCluster - runStart); result.Add(new Tuple<long, long>(runStart, focusCluster - runStart)); numFound += focusCluster - runStart; } } else { ++focusCluster; } ++numInspected; if (focusCluster >= end) { focusCluster = start; } } if (!isMft) { _nextDataCluster = focusCluster + headroom; } return numFound; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; // ERROR: Not supported in C#: OptionDeclaration using Microsoft.VisualBasic.PowerPacks; namespace _4PosBackOffice.NET { internal partial class frmStockChildMessage : System.Windows.Forms.Form { int gStockItemID; int gPromotionID; int gQuantity; bool fDone; private void loadLanguage() { //frmStockChildMessage = No Code [New Child Message] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmStockChildMessage.Caption = rsLang("LanguageLayoutLnk_Description"): frmStockChildMessage.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074; //Undo|Checked if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004; //Exit|Checked if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} //lblPComp = No Code [Please specify if you wish this stock item to be cherge on sale] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then lblPComp.Caption = rsLang("LanguageLayoutLnk_Description"): lblPComp.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1935; //Stock Item Name|Checked if (modRecordSet.rsLang.RecordCount){_LBL_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_LBL_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} //chkCharge = No Code [Charge on Sale] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then chkCharge.Caption = rsLang("LanguageLayoutLnk_Description"): chkCharge.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1151; //Price|Checked if (modRecordSet.rsLang.RecordCount){_LBL_3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_LBL_3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} //_lbl_2 = No Code [Chargable Item?] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then _lbl_2.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmStockChildMessage.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } public bool makeItem(ref int childID) { int lID = 0; ADODB.Recordset rs = default(ADODB.Recordset); fDone = false; lID = My.MyProject.Forms.frmStockList2.getItem(); if (lID != 0) { // ERROR: Not supported in C#: OnErrorStatement loadItem(ref lID, ref childID); //adoPrimaryRS("PromotionID"), lID } return fDone; } private void loadData() { ADODB.Recordset rs = default(ADODB.Recordset); rs = modRecordSet.getRS(ref "SELECT StockItem.StockItem_Name, CatalogueChannelLnk.CatalogueChannelLnk_Quantity, CatalogueChannelLnk.CatalogueChannelLnk_Price FROM (Catalogue INNER JOIN StockItem ON (StockItem.StockItem_Quantity = Catalogue.Catalogue_Quantity) AND (Catalogue.Catalogue_StockItemID = StockItem.StockItemID)) INNER JOIN CatalogueChannelLnk ON (Catalogue.Catalogue_StockItemID = CatalogueChannelLnk.CatalogueChannelLnk_StockItemID) AND (Catalogue.Catalogue_Quantity = CatalogueChannelLnk.CatalogueChannelLnk_Quantity) WHERE (((StockItem.StockItemID)=" + gStockItemID + ") AND ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID)=1));"); if (rs.RecordCount) { lblStockItem.Text = rs.Fields("StockItem_Name").Value; //lblPromotion.Caption = rs("Promotion_Name") txtPrice.Text = Convert.ToString(rs.Fields("CatalogueChannelLnk_Price").Value * 100); txtPrice_Leave(txtPrice, new System.EventArgs()); //cmbQuantity.Tag = rs("CatalogueChannelLnk_Quantity") loadLanguage(); ShowDialog(); } else { this.Close(); return; } } //Public Sub loadItem(promotionID As Long, stockitemID As Long, Optional quantity As Long) public void loadItem(ref int stockitemID, ref int promotionID = 0) { gStockItemID = stockitemID; gPromotionID = promotionID; //gQuantity = quantity //lblPComp.Caption = frmStockTransfer.lblPComp.Caption loadData(); //show 1 } private void frmStockChildMessage_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); bool mbAddNewFlag = false; bool mbEditFlag = false; if (mbEditFlag | mbAddNewFlag) goto EventExitSub; switch (KeyAscii) { case System.Windows.Forms.Keys.Escape: KeyAscii = 0; cmdClose.Focus(); System.Windows.Forms.Application.DoEvents(); cmdClose_Click(cmdClose, new System.EventArgs()); break; } EventExitSub: eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs) { // ERROR: Not supported in C#: OnErrorStatement fDone = false; this.Close(); } //UPGRADE_NOTE: update was upgraded to update_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"' private bool update_Renamed() { bool functionReturnValue = false; // ERROR: Not supported in C#: OnErrorStatement ADODB.Recordset rs = default(ADODB.Recordset); ADODB.Recordset rj = default(ADODB.Recordset); ADODB.Recordset adoPrimaryRS = default(ADODB.Recordset); string sql = null; decimal lQuantity = default(decimal); // Long rs = modRecordSet.getRS(ref "SELECT MessageItem.MessageItem_MessageID From MessageItem WHERE (((MessageItem.MessageItem_MessageID)=" + gPromotionID + "));"); modRecordSet.cnnDB.Execute("INSERT INTO MessageItem ( MessageItem_MessageID, MessageItem_Name, MessageItem_Order, MessageItem_StockitemID, MessageItem_Charge ) SELECT " + gPromotionID + ", '" + Strings.Replace(lblStockItem.Text, "'", "''") + "', " + rs.RecordCount + 1 + ", " + gStockItemID + ", " + chkCharge.CheckState + ";"); Interaction.MsgBox("New Child Message from Stock process has been completed.", MsgBoxStyle.ApplicationModal + MsgBoxStyle.Information + MsgBoxStyle.OkOnly, _4PosBackOffice.NET.My.MyProject.Application.Info.Title); functionReturnValue = true; return functionReturnValue; UpdateErr: Interaction.MsgBox(Err().Description); functionReturnValue = true; return functionReturnValue; } private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs) { cmdClose.Focus(); System.Windows.Forms.Application.DoEvents(); //If CCur(txtQty.Text) > 0 Then //Else // txtQty.SetFocus // Exit Sub //End If if (update_Renamed()) { fDone = true; this.Close(); } } private void txtPrice_Enter(System.Object eventSender, System.EventArgs eventArgs) { modUtilities.MyGotFocusNumeric(ref txtPrice); } private void txtPrice_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); //MyKeyPressNegative(txtPrice, KeyAscii) eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void txtPrice_Leave(System.Object eventSender, System.EventArgs eventArgs) { modUtilities.MyLostFocus(ref txtPrice, ref 2); } private void txtPriceS_MyGotFocus() { TextBox txtPriceS = new TextBox(); modUtilities.MyGotFocusNumeric(ref txtPriceS); } private void txtPriceS_MyLostFocus() { TextBox txtPriceS = new TextBox(); modUtilities.MyLostFocus(ref txtPriceS, ref 2); } private void txtQty_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); switch (KeyAscii) { case Strings.Asc(Constants.vbCr): KeyAscii = 0; break; case 8: break; case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: break; } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void txtQty_Enter(System.Object eventSender, System.EventArgs eventArgs) { //MyGotFocusNumeric txtQty txtQty.SelectionStart = 0; txtQty.SelectionLength = Strings.Len(txtQty.Text); } private void txtQty_Leave(System.Object eventSender, System.EventArgs eventArgs) { // LostFocus txtQty, 2 } } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using System.Collections.Generic; using Quartz.Impl.Matchers; using Quartz.Spi; namespace Quartz { /// <summary> /// This is the main interface of a Quartz Scheduler. /// </summary> /// <remarks> /// <para> /// A <see cref="IScheduler"/> maintains a registry of /// <see cref="IJobDetail"/>s and <see cref="ITrigger"/>s. Once /// registered, the <see cref="IScheduler"/> is responsible for executing /// <see cref="IJob"/> s when their associated <see cref="ITrigger"/> s /// fire (when their scheduled time arrives). /// </para> /// <para> /// <see cref="IScheduler"/> instances are produced by a /// <see cref="ISchedulerFactory"/>. A scheduler that has already been /// created/initialized can be found and used through the same factory that /// produced it. After a <see cref="IScheduler"/> has been created, it is in /// "stand-by" mode, and must have its <see cref="IScheduler.Start"/> method /// called before it will fire any <see cref="IJob"/>s. /// </para> /// <para> /// <see cref="IJob"/> s are to be created by the 'client program', by /// defining a class that implements the <see cref="IJob"/> interface. /// <see cref="IJobDetail"/> objects are then created (also by the client) to /// define a individual instances of the <see cref="IJob"/>. /// <see cref="IJobDetail"/> instances can then be registered with the /// <see cref="IScheduler"/> via the %IScheduler.ScheduleJob(JobDetail, /// Trigger)% or %IScheduler.AddJob(JobDetail, bool)% method. /// </para> /// <para> /// <see cref="ITrigger"/> s can then be defined to fire individual /// <see cref="IJob"/> instances based on given schedules. /// <see cref="ISimpleTrigger"/> s are most useful for one-time firings, or /// firing at an exact moment in time, with N repeats with a given delay between /// them. <see cref="ICronTrigger"/> s allow scheduling based on time of day, /// day of week, day of month, and month of year. /// </para> /// <para> /// <see cref="IJob"/> s and <see cref="ITrigger"/> s have a name and /// group associated with them, which should uniquely identify them within a single /// <see cref="IScheduler"/>. The 'group' feature may be useful for creating /// logical groupings or categorizations of <see cref="IJob"/>s and /// <see cref="ITrigger"/>s. If you don't have need for assigning a group to a /// given <see cref="IJob"/>s of <see cref="ITrigger"/>s, then you can use /// the <see cref="SchedulerConstants.DefaultGroup"/> constant defined on /// this interface. /// </para> /// <para> /// Stored <see cref="IJob"/> s can also be 'manually' triggered through the /// use of the %IScheduler.TriggerJob(string, string)% function. /// </para> /// <para> /// Client programs may also be interested in the 'listener' interfaces that are /// available from Quartz. The <see cref="IJobListener"/> interface provides /// notifications of <see cref="IJob"/> executions. The /// <see cref="ITriggerListener"/> interface provides notifications of /// <see cref="ITrigger"/> firings. The <see cref="ISchedulerListener"/> /// interface provides notifications of <see cref="IScheduler"/> events and /// errors. Listeners can be associated with local schedulers through the /// <see cref="IListenerManager" /> interface. /// </para> /// <para> /// The setup/configuration of a <see cref="IScheduler"/> instance is very /// customizable. Please consult the documentation distributed with Quartz. /// </para> /// </remarks> /// <seealso cref="IJob"/> /// <seealso cref="IJobDetail"/> /// <seealso cref="ITrigger"/> /// <seealso cref="IJobListener"/> /// <seealso cref="ITriggerListener"/> /// <seealso cref="ISchedulerListener"/> /// <author>Marko Lahma (.NET)</author> public interface IScheduler { /// <summary> /// returns true if the given JobGroup /// is paused /// </summary> /// <param name="groupName"></param> /// <returns></returns> bool IsJobGroupPaused(string groupName); /// <summary> /// returns true if the given TriggerGroup /// is paused /// </summary> /// <param name="groupName"></param> /// <returns></returns> bool IsTriggerGroupPaused(string groupName); /// <summary> /// Returns the name of the <see cref="IScheduler" />. /// </summary> string SchedulerName { get; } /// <summary> /// Returns the instance Id of the <see cref="IScheduler" />. /// </summary> string SchedulerInstanceId { get; } /// <summary> /// Returns the <see cref="SchedulerContext" /> of the <see cref="IScheduler" />. /// </summary> SchedulerContext Context { get; } /// <summary> /// Reports whether the <see cref="IScheduler" /> is in stand-by mode. /// </summary> /// <seealso cref="Standby()" /> /// <seealso cref="Start()" /> bool InStandbyMode { get; } /// <summary> /// Reports whether the <see cref="IScheduler" /> has been Shutdown. /// </summary> bool IsShutdown { get; } /// <summary> /// Get a <see cref="SchedulerMetaData" /> object describing the settings /// and capabilities of the scheduler instance. /// </summary> /// <remarks> /// Note that the data returned is an 'instantaneous' snap-shot, and that as /// soon as it's returned, the meta data values may be different. /// </remarks> SchedulerMetaData GetMetaData(); /// <summary> /// Return a list of <see cref="IJobExecutionContext" /> objects that /// represent all currently executing Jobs in this Scheduler instance. /// </summary> /// <remarks> /// <para> /// This method is not cluster aware. That is, it will only return Jobs /// currently executing in this Scheduler instance, not across the entire /// cluster. /// </para> /// <para> /// Note that the list returned is an 'instantaneous' snap-shot, and that as /// soon as it's returned, the true list of executing jobs may be different. /// Also please read the doc associated with <see cref="IJobExecutionContext" />- /// especially if you're using remoting. /// </para> /// </remarks> /// <seealso cref="IJobExecutionContext" /> IList<IJobExecutionContext> GetCurrentlyExecutingJobs(); /// <summary> /// Set the <see cref="JobFactory" /> that will be responsible for producing /// instances of <see cref="IJob" /> classes. /// </summary> /// <remarks> /// JobFactories may be of use to those wishing to have their application /// produce <see cref="IJob" /> instances via some special mechanism, such as to /// give the opportunity for dependency injection. /// </remarks> /// <seealso cref="IJobFactory" /> IJobFactory JobFactory { set; } /// <summary> /// Get a reference to the scheduler's <see cref="IListenerManager" />, /// through which listeners may be registered. /// </summary> /// <returns>the scheduler's <see cref="IListenerManager" /></returns> /// <seealso cref="ListenerManager" /> /// <seealso cref="IJobListener" /> /// <seealso cref="ITriggerListener" /> /// <seealso cref="ISchedulerListener" /> IListenerManager ListenerManager { get; } /// <summary> /// Get the names of all known <see cref="IJobDetail" /> groups. /// </summary> IList<string> GetJobGroupNames(); /// <summary> /// Get the names of all known <see cref="ITrigger" /> groups. /// </summary> IList<string> GetTriggerGroupNames(); /// <summary> /// Get the names of all <see cref="ITrigger" /> groups that are paused. /// </summary> Collection.ISet<string> GetPausedTriggerGroups(); /// <summary> /// Starts the <see cref="IScheduler" />'s threads that fire <see cref="ITrigger" />s. /// When a scheduler is first created it is in "stand-by" mode, and will not /// fire triggers. The scheduler can also be put into stand-by mode by /// calling the <see cref="Standby" /> method. /// </summary> /// <remarks> /// The misfire/recovery process will be started, if it is the initial call /// to this method on this scheduler instance. /// </remarks> /// <seealso cref="StartDelayed(TimeSpan)"/> /// <seealso cref="Standby"/> /// <seealso cref="Shutdown(bool)"/> void Start(); /// <summary> /// Calls <see cref="Start" /> after the indicated delay. /// (This call does not block). This can be useful within applications that /// have initializers that create the scheduler immediately, before the /// resources needed by the executing jobs have been fully initialized. /// </summary> /// <seealso cref="Start"/> /// <seealso cref="Standby"/> /// <seealso cref="Shutdown(bool)"/> void StartDelayed(TimeSpan delay); /// <summary> /// Whether the scheduler has been started. /// </summary> /// <remarks> /// Note: This only reflects whether <see cref="Start" /> has ever /// been called on this Scheduler, so it will return <see langword="true" /> even /// if the <see cref="IScheduler" /> is currently in standby mode or has been /// since shutdown. /// </remarks> /// <seealso cref="Start" /> /// <seealso cref="IsShutdown" /> /// <seealso cref="InStandbyMode" /> bool IsStarted { get; } /// <summary> /// Temporarily halts the <see cref="IScheduler" />'s firing of <see cref="ITrigger" />s. /// </summary> /// <remarks> /// <para> /// When <see cref="Start" /> is called (to bring the scheduler out of /// stand-by mode), trigger misfire instructions will NOT be applied /// during the execution of the <see cref="Start" /> method - any misfires /// will be detected immediately afterward (by the <see cref="IJobStore" />'s /// normal process). /// </para> /// <para> /// The scheduler is not destroyed, and can be re-started at any time. /// </para> /// </remarks> /// <seealso cref="Start()"/> /// <seealso cref="PauseAll()"/> void Standby(); /// <summary> /// Halts the <see cref="IScheduler" />'s firing of <see cref="ITrigger" />s, /// and cleans up all resources associated with the Scheduler. Equivalent to Shutdown(false). /// </summary> /// <remarks> /// The scheduler cannot be re-started. /// </remarks> /// <seealso cref="Shutdown(bool)" /> void Shutdown(); /// <summary> /// Halts the <see cref="IScheduler" />'s firing of <see cref="ITrigger" />s, /// and cleans up all resources associated with the Scheduler. /// </summary> /// <remarks> /// The scheduler cannot be re-started. /// </remarks> /// <param name="waitForJobsToComplete"> /// if <see langword="true" /> the scheduler will not allow this method /// to return until all currently executing jobs have completed. /// </param> /// <seealso cref="Shutdown()" /> void Shutdown(bool waitForJobsToComplete); /// <summary> /// Add the given <see cref="IJobDetail" /> to the /// Scheduler, and associate the given <see cref="ITrigger" /> with /// it. /// </summary> /// <remarks> /// If the given Trigger does not reference any <see cref="IJob" />, then it /// will be set to reference the Job passed with it into this method. /// </remarks> DateTimeOffset ScheduleJob(IJobDetail jobDetail, ITrigger trigger); /// <summary> /// Schedule the given <see cref="ITrigger" /> with the /// <see cref="IJob" /> identified by the <see cref="ITrigger" />'s settings. /// </summary> DateTimeOffset ScheduleJob(ITrigger trigger); /// <summary> /// Schedule all of the given jobs with the related set of triggers. /// </summary> /// <remarks> /// <para>If any of the given jobs or triggers already exist (or more /// specifically, if the keys are not unique) and the replace /// parameter is not set to true then an exception will be thrown.</para> /// </remarks> void ScheduleJobs(IDictionary<IJobDetail, Collection.ISet<ITrigger>> triggersAndJobs, bool replace); /// <summary> /// Schedule the given job with the related set of triggers. /// </summary> /// <remarks> /// If any of the given job or triggers already exist (or more /// specifically, if the keys are not unique) and the replace /// parameter is not set to true then an exception will be thrown. /// </remarks> /// <param name="jobDetail"></param> /// <param name="triggersForJob"></param> /// <param name="replace"></param> void ScheduleJob(IJobDetail jobDetail, Collection.ISet<ITrigger> triggersForJob, bool replace); /// <summary> /// Remove the indicated <see cref="ITrigger" /> from the scheduler. /// <para>If the related job does not have any other triggers, and the job is /// not durable, then the job will also be deleted.</para> /// </summary> bool UnscheduleJob(TriggerKey triggerKey); /// <summary> /// Remove all of the indicated <see cref="ITrigger" />s from the scheduler. /// </summary> /// <remarks> /// <para>If the related job does not have any other triggers, and the job is /// not durable, then the job will also be deleted.</para> /// Note that while this bulk operation is likely more efficient than /// invoking <see cref="UnscheduleJob(TriggerKey)" /> several /// times, it may have the adverse affect of holding data locks for a /// single long duration of time (rather than lots of small durations /// of time). /// </remarks> bool UnscheduleJobs(IList<TriggerKey> triggerKeys); /// <summary> /// Remove (delete) the <see cref="ITrigger" /> with the /// given key, and store the new given one - which must be associated /// with the same job (the new trigger must have the job name &amp; group specified) /// - however, the new trigger need not have the same name as the old trigger. /// </summary> /// <param name="triggerKey">The <see cref="ITrigger" /> to be replaced.</param> /// <param name="newTrigger"> /// The new <see cref="ITrigger" /> to be stored. /// </param> /// <returns> /// <see langword="null" /> if a <see cref="ITrigger" /> with the given /// name and group was not found and removed from the store (and the /// new trigger is therefore not stored), otherwise /// the first fire time of the newly scheduled trigger. /// </returns> DateTimeOffset? RescheduleJob(TriggerKey triggerKey, ITrigger newTrigger); /// <summary> /// Add the given <see cref="IJob" /> to the Scheduler - with no associated /// <see cref="ITrigger" />. The <see cref="IJob" /> will be 'dormant' until /// it is scheduled with a <see cref="ITrigger" />, or <see cref="TriggerJob(Quartz.JobKey)" /> /// is called for it. /// </summary> /// <remarks> /// The <see cref="IJob" /> must by definition be 'durable', if it is not, /// SchedulerException will be thrown. /// </remarks> void AddJob(IJobDetail jobDetail, bool replace); /// <summary> /// Add the given <see cref="IJob" /> to the Scheduler - with no associated /// <see cref="ITrigger" />. The <see cref="IJob" /> will be 'dormant' until /// it is scheduled with a <see cref="ITrigger" />, or <see cref="TriggerJob(Quartz.JobKey)" /> /// is called for it. /// </summary> /// <remarks> /// With the <paramref name="storeNonDurableWhileAwaitingScheduling"/> parameter /// set to <code>true</code>, a non-durable job can be stored. Once it is /// scheduled, it will resume normal non-durable behavior (i.e. be deleted /// once there are no remaining associated triggers). /// </remarks> void AddJob(IJobDetail jobDetail, bool replace, bool storeNonDurableWhileAwaitingScheduling); /// <summary> /// Delete the identified <see cref="IJob" /> from the Scheduler - and any /// associated <see cref="ITrigger" />s. /// </summary> /// <returns> true if the Job was found and deleted.</returns> bool DeleteJob(JobKey jobKey); /// <summary> /// Delete the identified jobs from the Scheduler - and any /// associated <see cref="ITrigger" />s. /// </summary> /// <remarks> /// <para>Note that while this bulk operation is likely more efficient than /// invoking <see cref="DeleteJob(JobKey)" /> several /// times, it may have the adverse affect of holding data locks for a /// single long duration of time (rather than lots of small durations /// of time).</para> /// </remarks> /// <returns> /// true if all of the Jobs were found and deleted, false if /// one or more were not deleted. /// </returns> bool DeleteJobs(IList<JobKey> jobKeys); /// <summary> /// Trigger the identified <see cref="IJobDetail" /> /// (Execute it now). /// </summary> void TriggerJob(JobKey jobKey); /// <summary> /// Trigger the identified <see cref="IJobDetail" /> (Execute it now). /// </summary> /// <param name="data"> /// the (possibly <see langword="null" />) JobDataMap to be /// associated with the trigger that fires the job immediately. /// </param> /// <param name="jobKey"> /// The <see cref="JobKey"/> of the <see cref="IJob" /> to be executed. /// </param> void TriggerJob(JobKey jobKey, JobDataMap data); /// <summary> /// Pause the <see cref="IJobDetail" /> with the given /// key - by pausing all of its current <see cref="ITrigger" />s. /// </summary> void PauseJob(JobKey jobKey); /// <summary> /// Pause all of the <see cref="IJobDetail" />s in the /// matching groups - by pausing all of their <see cref="ITrigger" />s. /// </summary> /// <remarks> /// <para> /// The Scheduler will "remember" that the groups are paused, and impose the /// pause on any new jobs that are added to any of those groups until it is resumed. /// </para> /// <para>NOTE: There is a limitation that only exactly matched groups /// can be remembered as paused. For example, if there are pre-existing /// job in groups "aaa" and "bbb" and a matcher is given to pause /// groups that start with "a" then the group "aaa" will be remembered /// as paused and any subsequently added jobs in group "aaa" will be paused, /// however if a job is added to group "axx" it will not be paused, /// as "axx" wasn't known at the time the "group starts with a" matcher /// was applied. HOWEVER, if there are pre-existing groups "aaa" and /// "bbb" and a matcher is given to pause the group "axx" (with a /// group equals matcher) then no jobs will be paused, but it will be /// remembered that group "axx" is paused and later when a job is added /// in that group, it will become paused.</para> /// </remarks> /// <seealso cref="ResumeJobs" /> void PauseJobs(GroupMatcher<JobKey> matcher); /// <summary> /// Pause the <see cref="ITrigger" /> with the given key. /// </summary> void PauseTrigger(TriggerKey triggerKey); /// <summary> /// Pause all of the <see cref="ITrigger" />s in the groups matching. /// </summary> /// <remarks> /// <para> /// The Scheduler will "remember" all the groups paused, and impose the /// pause on any new triggers that are added to any of those groups until it is resumed. /// </para> /// <para>NOTE: There is a limitation that only exactly matched groups /// can be remembered as paused. For example, if there are pre-existing /// triggers in groups "aaa" and "bbb" and a matcher is given to pause /// groups that start with "a" then the group "aaa" will be remembered as /// paused and any subsequently added triggers in that group be paused, /// however if a trigger is added to group "axx" it will not be paused, /// as "axx" wasn't known at the time the "group starts with a" matcher /// was applied. HOWEVER, if there are pre-existing groups "aaa" and /// "bbb" and a matcher is given to pause the group "axx" (with a /// group equals matcher) then no triggers will be paused, but it will be /// remembered that group "axx" is paused and later when a trigger is added /// in that group, it will become paused.</para> /// </remarks> /// <seealso cref="ResumeTriggers" /> void PauseTriggers(GroupMatcher<TriggerKey> matcher); /// <summary> /// Resume (un-pause) the <see cref="IJobDetail" /> with /// the given key. /// </summary> /// <remarks> /// If any of the <see cref="IJob" />'s<see cref="ITrigger" /> s missed one /// or more fire-times, then the <see cref="ITrigger" />'s misfire /// instruction will be applied. /// </remarks> void ResumeJob(JobKey jobKey); /// <summary> /// Resume (un-pause) all of the <see cref="IJobDetail" />s /// in matching groups. /// </summary> /// <remarks> /// If any of the <see cref="IJob" /> s had <see cref="ITrigger" /> s that /// missed one or more fire-times, then the <see cref="ITrigger" />'s /// misfire instruction will be applied. /// </remarks> /// <seealso cref="PauseJobs" /> void ResumeJobs(GroupMatcher<JobKey> matcher); /// <summary> /// Resume (un-pause) the <see cref="ITrigger" /> with the given /// key. /// </summary> /// <remarks> /// If the <see cref="ITrigger" /> missed one or more fire-times, then the /// <see cref="ITrigger" />'s misfire instruction will be applied. /// </remarks> void ResumeTrigger(TriggerKey triggerKey); /// <summary> /// Resume (un-pause) all of the <see cref="ITrigger" />s in matching groups. /// </summary> /// <remarks> /// If any <see cref="ITrigger" /> missed one or more fire-times, then the /// <see cref="ITrigger" />'s misfire instruction will be applied. /// </remarks> /// <seealso cref="PauseTriggers" /> void ResumeTriggers(GroupMatcher<TriggerKey> matcher); /// <summary> /// Pause all triggers - similar to calling <see cref="PauseTriggers" /> /// on every group, however, after using this method <see cref="ResumeAll()" /> /// must be called to clear the scheduler's state of 'remembering' that all /// new triggers will be paused as they are added. /// </summary> /// <remarks> /// When <see cref="ResumeAll()" /> is called (to un-pause), trigger misfire /// instructions WILL be applied. /// </remarks> /// <seealso cref="ResumeAll()" /> /// <seealso cref="PauseTriggers" /> /// <seealso cref="Standby()" /> void PauseAll(); /// <summary> /// Resume (un-pause) all triggers - similar to calling /// <see cref="ResumeTriggers" /> on every group. /// </summary> /// <remarks> /// If any <see cref="ITrigger" /> missed one or more fire-times, then the /// <see cref="ITrigger" />'s misfire instruction will be applied. /// </remarks> /// <seealso cref="PauseAll()" /> void ResumeAll(); /// <summary> /// Get the keys of all the <see cref="IJobDetail" />s in the matching groups. /// </summary> Collection.ISet<JobKey> GetJobKeys(GroupMatcher<JobKey> matcher); /// <summary> /// Get all <see cref="ITrigger" /> s that are associated with the /// identified <see cref="IJobDetail" />. /// </summary> /// <remarks> /// The returned Trigger objects will be snap-shots of the actual stored /// triggers. If you wish to modify a trigger, you must re-store the /// trigger afterward (e.g. see <see cref="RescheduleJob(TriggerKey, ITrigger)" />). /// </remarks> IList<ITrigger> GetTriggersOfJob(JobKey jobKey); /// <summary> /// Get the names of all the <see cref="ITrigger" />s in the given /// groups. /// </summary> Collection.ISet<TriggerKey> GetTriggerKeys(GroupMatcher<TriggerKey> matcher); /// <summary> /// Get the <see cref="IJobDetail" /> for the <see cref="IJob" /> /// instance with the given key . /// </summary> /// <remarks> /// The returned JobDetail object will be a snap-shot of the actual stored /// JobDetail. If you wish to modify the JobDetail, you must re-store the /// JobDetail afterward (e.g. see <see cref="AddJob(IJobDetail, bool)" />). /// </remarks> IJobDetail GetJobDetail(JobKey jobKey); /// <summary> /// Get the <see cref="ITrigger" /> instance with the given key. /// </summary> /// <remarks> /// The returned Trigger object will be a snap-shot of the actual stored /// trigger. If you wish to modify the trigger, you must re-store the /// trigger afterward (e.g. see <see cref="RescheduleJob(TriggerKey, ITrigger)" />). /// </remarks> ITrigger GetTrigger(TriggerKey triggerKey); /// <summary> /// Get the current state of the identified <see cref="ITrigger" />. /// </summary> /// <seealso cref="TriggerState.Normal" /> /// <seealso cref="TriggerState.Paused" /> /// <seealso cref="TriggerState.Complete" /> /// <seealso cref="TriggerState.Blocked" /> /// <seealso cref="TriggerState.Error" /> /// <seealso cref="TriggerState.None" /> TriggerState GetTriggerState(TriggerKey triggerKey); /// <summary> /// Add (register) the given <see cref="ICalendar" /> to the Scheduler. /// </summary> /// <param name="calName">Name of the calendar.</param> /// <param name="calendar">The calendar.</param> /// <param name="replace">if set to <c>true</c> [replace].</param> /// <param name="updateTriggers">whether or not to update existing triggers that /// referenced the already existing calendar so that they are 'correct' /// based on the new trigger.</param> void AddCalendar(string calName, ICalendar calendar, bool replace, bool updateTriggers); /// <summary> /// Delete the identified <see cref="ICalendar" /> from the Scheduler. /// </summary> /// <remarks> /// If removal of the <code>Calendar</code> would result in /// <see cref="ITrigger" />s pointing to non-existent calendars, then a /// <see cref="SchedulerException" /> will be thrown. /// </remarks> /// <param name="calName">Name of the calendar.</param> /// <returns>true if the Calendar was found and deleted.</returns> bool DeleteCalendar(string calName); /// <summary> /// Get the <see cref="ICalendar" /> instance with the given name. /// </summary> ICalendar GetCalendar(string calName); /// <summary> /// Get the names of all registered <see cref="ICalendar" />. /// </summary> IList<string> GetCalendarNames(); /// <summary> /// Request the interruption, within this Scheduler instance, of all /// currently executing instances of the identified <see cref="IJob" />, which /// must be an implementor of the <see cref="IInterruptableJob" /> interface. /// </summary> /// <remarks> /// <para> /// If more than one instance of the identified job is currently executing, /// the <see cref="IInterruptableJob.Interrupt" /> method will be called on /// each instance. However, there is a limitation that in the case that /// <see cref="Interrupt(JobKey)" /> on one instances throws an exception, all /// remaining instances (that have not yet been interrupted) will not have /// their <see cref="Interrupt(JobKey)" /> method called. /// </para> /// /// <para> /// If you wish to interrupt a specific instance of a job (when more than /// one is executing) you can do so by calling /// <see cref="GetCurrentlyExecutingJobs" /> to obtain a handle /// to the job instance, and then invoke <see cref="Interrupt(JobKey)" /> on it /// yourself. /// </para> /// <para> /// This method is not cluster aware. That is, it will only interrupt /// instances of the identified InterruptableJob currently executing in this /// Scheduler instance, not across the entire cluster. /// </para> /// </remarks> /// <returns> /// true is at least one instance of the identified job was found and interrupted. /// </returns> /// <seealso cref="IInterruptableJob" /> /// <seealso cref="GetCurrentlyExecutingJobs" /> bool Interrupt(JobKey jobKey); /// <summary> /// Request the interruption, within this Scheduler instance, of the /// identified executing job instance, which /// must be an implementor of the <see cref="IInterruptableJob" /> interface. /// </summary> /// <remarks> /// This method is not cluster aware. That is, it will only interrupt /// instances of the identified InterruptableJob currently executing in this /// Scheduler instance, not across the entire cluster. /// </remarks> /// <seealso cref="IInterruptableJob.Interrupt()" /> /// <seealso cref="GetCurrentlyExecutingJobs()" /> /// <seealso cref="IJobExecutionContext.FireInstanceId" /> /// <seealso cref="Interrupt(JobKey)" /> /// <param nane="fireInstanceId"> /// the unique identifier of the job instance to be interrupted (see <see cref="IJobExecutionContext.FireInstanceId" /> /// </param> /// <param name="fireInstanceId"> </param> /// <returns>true if the identified job instance was found and interrupted.</returns> bool Interrupt(string fireInstanceId); /// <summary> /// Determine whether a <see cref="IJob" /> with the given identifier already /// exists within the scheduler. /// </summary> /// <param name="jobKey">the identifier to check for</param> /// <returns>true if a Job exists with the given identifier</returns> bool CheckExists(JobKey jobKey); /// <summary> /// Determine whether a <see cref="ITrigger" /> with the given identifier already /// exists within the scheduler. /// </summary> /// <param name="triggerKey">the identifier to check for</param> /// <returns>true if a Trigger exists with the given identifier</returns> bool CheckExists(TriggerKey triggerKey); /// <summary> /// Clears (deletes!) all scheduling data - all <see cref="IJob"/>s, <see cref="ITrigger" />s /// <see cref="ICalendar"/>s. /// </summary> void Clear(); } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Epos.Utilities { /// <summary>Encapsulates a unary operation like negating on type /// <typeparamref name="T" />.</summary> /// <typeparam name="T">Type</typeparam> /// <param name="arg">Operand</param> /// <returns>Return value</returns> public delegate T UnaryOperation<T>(T arg); /// <summary>Encapsulates a binary operation like adding on the types /// <typeparamref name="T1" />, <typeparamref name="T2" /> and /// <typeparamref name="TResult" />.</summary> /// <typeparam name="T1">Type of left operand</typeparam> /// <typeparam name="T2">Type of right operand</typeparam> /// <typeparam name="TResult">Result type</typeparam> /// <param name="arg1">Left operand</param> /// <param name="arg2">Right operand</param> /// <returns>Return value</returns> public delegate TResult BinaryOperation<in T1, in T2, out TResult>(T1 arg1, T2 arg2); /// <summary>Encapsulates a rounding operation for the type <typeparamref name="T" />. /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="value">Value to round</param> /// <param name="roundingPrecision">Rounding precision</param> /// <param name="mode">Rounding mode</param> /// <returns>Rounded value</returns> public delegate T RoundOperation<T>(T value, int roundingPrecision, MidpointRounding mode); /// <summary>Provides an abstract factory for arithmetic operations like add, subtract, /// multiply, divide and negate.</summary> public static class Arithmetics { private static readonly ConcurrentDictionary<Type, object> Ones = new ConcurrentDictionary<Type, object>(); private static readonly ConcurrentDictionary<Type, object> MinValues = new ConcurrentDictionary<Type, object>(); private static readonly ConcurrentDictionary<Type, object> MaxValues = new ConcurrentDictionary<Type, object>(); private static readonly ConcurrentDictionary<Type, Delegate> RoundOperations = new ConcurrentDictionary<Type, Delegate>(); private static readonly ConcurrentDictionary<(Type T1, Type T2, Type TResult), Delegate> AddOperations = new ConcurrentDictionary<(Type T1, Type T2, Type TResult), Delegate>(); private static readonly ConcurrentDictionary<(Type T1, Type T2, Type TResult), Delegate> SubtractOperations = new ConcurrentDictionary<(Type T1, Type T2, Type TResult), Delegate>(); private static readonly ConcurrentDictionary<(Type T1, Type T2, Type TResult), Delegate> MultiplyOperations = new ConcurrentDictionary<(Type T1, Type T2, Type TResult), Delegate>(); private static readonly ConcurrentDictionary<(Type T1, Type T2, Type TResult), Delegate> DivideOperations = new ConcurrentDictionary<(Type T1, Type T2, Type TResult), Delegate>(); private static readonly ConcurrentDictionary<Type, Delegate> NegateOperations = new ConcurrentDictionary<Type, Delegate>(); /// <summary>Gets the zero value for the type <typeparamref name="T" />.</summary> /// <typeparam name="T">Type</typeparam> /// <returns>Zero value</returns> public static T GetZeroValue<T>() => default!; /// <summary>Gets the one value for the type <typeparamref name="T" />.</summary> /// <typeparam name="T">Type</typeparam> /// <returns>One value</returns> public static T GetOneValue<T>() { Type theKey = typeof(T); if (!Ones.TryGetValue(theKey, out object theOne)) { try { Func<T> theGetOneFunc = Expression.Lambda<Func<T>>( Expression.MakeUnary(ExpressionType.Convert, Expression.Constant(1), theKey) ).Compile(); theOne = theGetOneFunc()!; } catch (InvalidOperationException) { throw new InvalidOperationException($"Cannot create 1-value for the type '{theKey.Dump()}'."); } Ones[theKey] = theOne; } return (T) theOne; } /// <summary>Gets the minimum value for the type <typeparamref name="T" />.</summary> /// <typeparam name="T">Type</typeparam> /// <returns>Minimum value</returns> /// <remarks>This method returns the value of the static <b>MinValue</b> property of /// the type <typeparamref name="T" />.</remarks> public static T GetMinValue<T>() { Type theKey = typeof(T); if (!MinValues.TryGetValue(theKey, out object theMinValue)) { FieldInfo theFieldInfo = theKey.GetField("MinValue", BindingFlags.Static | BindingFlags.Public); if (theFieldInfo != null) { theMinValue = theFieldInfo.GetValue(null); MinValues[theKey] = theMinValue; } else { throw new InvalidOperationException($"Cannot create MinValue for the type '{theKey.Dump()}'."); } } return (T) theMinValue; } /// <summary>Gets the maximum value for the type <typeparamref name="T" />.</summary> /// <typeparam name="T">Type</typeparam> /// <returns>Maximum value</returns> /// <remarks>This method returns the value of the static <b>MaxValue</b> property of /// the type <typeparamref name="T" />.</remarks> public static T GetMaxValue<T>() { Type theKey = typeof(T); if (!MaxValues.TryGetValue(theKey, out object theMaxValue)) { FieldInfo theFieldInfo = theKey.GetField("MaxValue", BindingFlags.Static | BindingFlags.Public); if (theFieldInfo != null) { theMaxValue = theFieldInfo.GetValue(null); MaxValues[theKey] = theMaxValue; } else { throw new InvalidOperationException($"Cannot create MaxValue for the type '{theKey.Dump()}'."); } } return (T) theMaxValue; } /// <summary>Creates the <see cref="RoundOperation{T}" /> for for the type /// <typeparamref name="T" />.</summary> /// <typeparam name="T">Type</typeparam> /// <returns><see cref="RoundOperation{T}" /></returns> /// <remarks>Works only with the following types: <see cref="double" />, <see cref="decimal" /></remarks> public static RoundOperation<T> CreateRoundOperation<T>() { Type theType = typeof(T); if (!RoundOperations.TryGetValue(theType, out Delegate theDelegate)) { bool isNullableType = theType.IsGenericType && theType.GetGenericTypeDefinition() == typeof(Nullable<>); Type theTypeToRound = isNullableType ? theType.GetGenericArguments().Single() : theType; ParameterExpression theTypeToRoundArgument = Expression.Parameter(theTypeToRound); ParameterExpression theInt32Argument = Expression.Parameter(typeof(int)); ParameterExpression theMidpointRoundingArgument = Expression.Parameter(typeof(MidpointRounding)); MethodInfo theRoundMethodInfo = typeof(Math).GetMethod( "Round", new[] { theTypeToRound, typeof(int), typeof(MidpointRounding) } ); MethodCallExpression theCallRoundExpression = Expression.Call( theRoundMethodInfo, theTypeToRoundArgument, theInt32Argument, theMidpointRoundingArgument ); if (!isNullableType) { theDelegate = Expression.Lambda<RoundOperation<T>>( theCallRoundExpression, theTypeToRoundArgument, theInt32Argument, theMidpointRoundingArgument ).Compile(); } else { ParameterExpression theTypeArgument = Expression.Parameter(typeof(T)); MethodInfo theGetHasValueMethodInfo = theType.GetMethod("get_HasValue"); MethodCallExpression theCallGetHasValueExpression = Expression.Call(theTypeArgument, theGetHasValueMethodInfo); MethodInfo theGetValueMethodInfo = theType.GetMethod("get_Value"); MethodCallExpression theCallGetValueExpression = Expression.Call(theTypeArgument, theGetValueMethodInfo); theCallRoundExpression = Expression.Call( theRoundMethodInfo, theCallGetValueExpression, theInt32Argument, theMidpointRoundingArgument ); ConstructorInfo theConstructorInfo = theType.GetConstructor(new[] { theTypeToRound }); NewExpression theNewNullableExpression = Expression.New(theConstructorInfo, theCallRoundExpression); theDelegate = Expression.Lambda<RoundOperation<T>>( Expression.Condition(theCallGetHasValueExpression, theNewNullableExpression, theTypeArgument), theTypeArgument, theInt32Argument, theMidpointRoundingArgument ).Compile(); } RoundOperations[theType] = theDelegate; } return (RoundOperation<T>) theDelegate; } /// <summary>Creates the negate operation for for the type /// <typeparamref name="T" />.</summary> /// <typeparam name="T">Type</typeparam> /// <returns>Negate operation</returns> public static UnaryOperation<T> CreateNegateOperation<T>() { Type theKey = typeof(T); if (!NegateOperations.TryGetValue(theKey, out Delegate theDelegate)) { ParameterExpression theArg = Expression.Parameter(typeof(T)); theDelegate = Expression.Lambda<UnaryOperation<T>>( Expression.MakeUnary(ExpressionType.Negate, theArg, null), theArg ).Compile(); NegateOperations[theKey] = theDelegate; } return (UnaryOperation<T>) theDelegate; } /// <summary>Creates the add operation for for the type /// <typeparamref name="T" />.</summary> /// <typeparam name="T">Type</typeparam> /// <returns>Add operation</returns> public static BinaryOperation<T, T, T> CreateAddOperation<T>() => CreateAddOperation<T, T, T>(); /// <summary>Creates the add operation for the types /// <typeparamref name="T1" /> and <typeparamref name="T2" />.</summary> /// <typeparam name="T1">Type for left operand</typeparam> /// <typeparam name="T2">Type for right operand</typeparam> /// <typeparam name="TResult">Return type</typeparam> /// <returns>Add operation that returns a <typeparamref name="TResult" /> instance</returns> public static BinaryOperation<T1, T2, TResult> CreateAddOperation<T1, T2, TResult>() => GetBinaryOperation<T1, T2, TResult>(ExpressionType.Add, AddOperations); /// <summary>Creates the subtract operation for for the type /// <typeparamref name="T" />.</summary> /// <typeparam name="T">Type</typeparam> /// <returns>Subtract operation</returns> public static BinaryOperation<T, T, T> CreateSubtractOperation<T>() => CreateSubtractOperation<T, T, T>(); /// <summary>Creates the subtract operation for the types /// <typeparamref name="T1" /> and <typeparamref name="T2" />.</summary> /// <typeparam name="T1">Type for left operand</typeparam> /// <typeparam name="T2">Type for right operand</typeparam> /// <typeparam name="TResult">Return type</typeparam> /// <returns>Subtract operation that returns a <typeparamref name="TResult" /> instance</returns> public static BinaryOperation<T1, T2, TResult> CreateSubtractOperation<T1, T2, TResult>() => GetBinaryOperation<T1, T2, TResult>(ExpressionType.Subtract, SubtractOperations); /// <summary>Creates the multiply operation for for the type /// <typeparamref name="T" />.</summary> /// <typeparam name="T">Type</typeparam> /// <returns>Multiply operation</returns> public static BinaryOperation<T, T, T> CreateMultiplyOperation<T>() => GetBinaryOperation<T, T, T>(ExpressionType.Multiply, MultiplyOperations); /// <summary>Creates the divide operation for for the type /// <typeparamref name="T" />.</summary> /// <typeparam name="T">Type</typeparam> /// <returns>Divide operation</returns> public static BinaryOperation<T, T, T> CreateDivideOperation<T>() => GetBinaryOperation<T, T, T>(ExpressionType.Divide, DivideOperations); #region Helper methods private static BinaryOperation<T1, T2, TResult> GetBinaryOperation<T1, T2, TResult>( ExpressionType expressionType, IDictionary<(Type T1, Type T2, Type TResult), Delegate> dictionary ) { (Type T1, Type T2, Type TResult) theKey = (T1: typeof(T1), T2: typeof(T2), TResult: typeof(TResult)); if (!dictionary.TryGetValue(theKey, out Delegate theDelegate)) { ParameterExpression theArg1 = Expression.Parameter(typeof(T1)); ParameterExpression theArg2 = Expression.Parameter(typeof(T2)); theDelegate = Expression.Lambda<BinaryOperation<T1, T2, TResult>>( Expression.MakeBinary(expressionType, theArg1, theArg2), theArg1, theArg2 ).Compile(); dictionary[theKey] = theDelegate; } return (BinaryOperation<T1, T2, TResult>) theDelegate; } #endregion } }
// UrlRewriter - A .NET URL Rewriter module // Version 2.0 // // Copyright 2007 Intelligencia // Copyright 2007 Seth Yates // using System; using System.Net; using System.Web; using System.Xml; using System.Text; using System.Configuration; using System.Reflection; using System.Collections; using System.Collections.Specialized; using System.Text.RegularExpressions; using Intelligencia.UrlRewriter.Conditions; using Intelligencia.UrlRewriter.Actions; using Intelligencia.UrlRewriter.Utilities; using Intelligencia.UrlRewriter.Parsers; using Intelligencia.UrlRewriter.Errors; using Intelligencia.UrlRewriter.Transforms; using Intelligencia.UrlRewriter.Logging; namespace Intelligencia.UrlRewriter.Configuration { /// <summary> /// Reads configuration from an XML Node. /// </summary> public sealed class RewriterConfigurationReader { /// <summary> /// Default constructor. /// </summary> private RewriterConfigurationReader() { } /// <summary> /// Reads configuration information from the given XML Node. /// </summary> /// <param name="section">The XML node to read configuration from.</param> /// <returns>The configuration information.</returns> public static object Read(XmlNode section) { if (section == null) { throw new ArgumentNullException("section"); } RewriterConfiguration config = RewriterConfiguration.Create(); foreach (XmlNode node in section.ChildNodes) { if (node.NodeType == XmlNodeType.Element) { if (node.LocalName == Constants.ElementErrorHandler) { ReadErrorHandler(node, config); } else if (node.LocalName == Constants.ElementDefaultDocuments) { ReadDefaultDocuments(node, config); } else if (node.LocalName == Constants.ElementRegister) { if (node.Attributes[Constants.AttrParser] != null) { ReadRegisterParser(node, config); } else if (node.Attributes[Constants.AttrTransform] != null) { ReadRegisterTransform(node, config); } else if (node.Attributes[Constants.AttrLogger] != null) { ReadRegisterLogger(node, config); } } else if (node.LocalName == Constants.ElementMapping) { ReadMapping(node, config); } else { ReadRule(node, config); } } } return config; } private static void ReadRegisterTransform(XmlNode node, RewriterConfiguration config) { // Type attribute. XmlNode typeNode = node.Attributes[Constants.AttrTransform]; if (typeNode == null) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrTransform), node); } if (node.ChildNodes.Count > 0) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.ElementNoElements, Constants.ElementRegister), node); } // Transform type specified. Create an instance and add it // as the mapper handler for this map. IRewriteTransform handler = TypeHelper.Activate(typeNode.Value, null) as IRewriteTransform; if (handler != null) { config.TransformFactory.AddTransform(handler); } else { // TODO: Error due to type. } } private static void ReadRegisterLogger(XmlNode node, RewriterConfiguration config) { // Type attribute. XmlNode typeNode = node.Attributes[Constants.AttrLogger]; if (typeNode == null) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrLogger), node); } if (node.ChildNodes.Count > 0) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.ElementNoElements, Constants.ElementRegister), node); } // Logger type specified. Create an instance and add it // as the mapper handler for this map. IRewriteLogger logger = TypeHelper.Activate(typeNode.Value, null) as IRewriteLogger; if (logger != null) { config.Logger = logger; } } private static void ReadRegisterParser(XmlNode node, RewriterConfiguration config) { XmlNode typeNode = node.Attributes[Constants.AttrParser]; if (typeNode == null) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrParser), node); } if (node.ChildNodes.Count > 0) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.ElementNoElements, Constants.ElementRegister), node); } object parser = TypeHelper.Activate(typeNode.Value, null); IRewriteActionParser actionParser = parser as IRewriteActionParser; if (actionParser != null) { config.ActionParserFactory.AddParser(actionParser); } IRewriteConditionParser conditionParser = parser as IRewriteConditionParser; if (conditionParser != null) { config.ConditionParserPipeline.AddParser(conditionParser); } } private static void ReadDefaultDocuments(XmlNode node, RewriterConfiguration config) { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.NodeType == XmlNodeType.Element && childNode.LocalName == Constants.ElementDocument) { config.DefaultDocuments.Add(childNode.InnerText); } } } private static void ReadErrorHandler(XmlNode node, RewriterConfiguration config) { XmlNode codeNode = node.Attributes[Constants.AttrCode]; if (codeNode == null) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrCode), node); } XmlNode typeNode = node.Attributes[Constants.AttrType]; XmlNode urlNode = node.Attributes[Constants.AttrUrl]; if (typeNode == null && urlNode == null) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrUrl), node); } IRewriteErrorHandler handler = null; if (typeNode != null) { // <error-handler code="500" url="/oops.aspx" /> handler = TypeHelper.Activate(typeNode.Value, null) as IRewriteErrorHandler; if (handler == null) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.InvalidTypeSpecified)); } } else { handler = new DefaultErrorHandler(urlNode.Value); } config.ErrorHandlers.Add(Convert.ToInt32(codeNode.Value), handler); } private static void ReadMapping(XmlNode node, RewriterConfiguration config) { // Name attribute. XmlNode nameNode = node.Attributes[Constants.AttrName]; // Mapper type not specified. Load in the hash map. StringDictionary map = new StringDictionary(); foreach (XmlNode mapNode in node.ChildNodes) { if (mapNode.NodeType == XmlNodeType.Element) { if (mapNode.LocalName == Constants.ElementMap) { XmlNode fromValueNode = mapNode.Attributes[Constants.AttrFrom]; if (fromValueNode == null) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrFrom), node); } XmlNode toValueNode = mapNode.Attributes[Constants.AttrTo]; if (toValueNode == null) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrTo), node); } map.Add(fromValueNode.Value, toValueNode.Value); } else { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.ElementNotAllowed, mapNode.LocalName), node); } } } config.TransformFactory.AddTransform(new StaticMappingTransform(nameNode.Value, map)); } private static void ReadRule(XmlNode node, RewriterConfiguration config) { bool parsed = false; IList parsers = config.ActionParserFactory.GetParsers(node.LocalName); if (parsers != null) { foreach (IRewriteActionParser parser in parsers) { if (!parser.AllowsNestedActions && node.ChildNodes.Count > 0) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.ElementNoElements, parser.Name), node); } if (!parser.AllowsAttributes && node.Attributes.Count > 0) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.ElementNoAttributes, parser.Name), node); } IRewriteAction rule = parser.Parse(node, config); if (rule != null) { config.Rules.Add(rule); parsed = true; break; } } } if (!parsed) { // No parsers recognised to handle this node. throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.ElementNotAllowed, node.LocalName), node); } } } }
#region license // Copyright (c) 2005 - 2007 Ayende Rahien ([email protected]) // 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 Ayende Rahien nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.IO; using Castle.ActiveRecord; using MbUnit.Framework; using NHibernate; using NHibernate.Criterion; using Rhino.Commons.ForTesting; namespace Rhino.Commons.Test.Repository { public abstract class RepositoryProjectionTests : RepositoryTestsBase { [SetUp] public void TestInitialize() { CurrentContext.CreateUnitOfWork(); CreateExampleObjectsInDb(); } [TearDown] public void TestCleanup() { CurrentContext.DisposeUnitOfWork(); } protected void CreateExampleObjectsInDb() { parentsInDb = new List<Parent>(); parentsInDb.Add(CreateExampleParentObject("Parent1", 100, new Child(), new Child())); parentsInDb.Add(CreateExampleParentObject("Parent2", 200, new Child(), new Child())); parentsInDb.Add(CreateExampleParentObject("Parent3", 300, new Child(), new Child())); SaveAndFlushToDatabase(parentsInDb); } [Test] public void CanReportOneMatchingCriteria() { DetachedCriteria where = DetachedCriteria.For<Parent>() .Add(Expression.Eq("Name", "Parent1")); ParentDto dto = Repository<Parent>.ReportOne<ParentDto>(where, ProjectByNameAndAge); AssertDtoCreatedFrom(parentsInDb[0], dto); } [Test] public void CanReportOneMatchingCriterion() { SimpleExpression whereName = Expression.Eq("Name", "Parent1"); SimpleExpression whereAge = Expression.Eq("Age", 100); ParentDto dto = Repository<Parent>.ReportOne<ParentDto>(ProjectByNameAndAge, whereName, whereAge); AssertDtoCreatedFrom(parentsInDb[0], dto); } [Test, ExpectedException(typeof (NonUniqueResultException))] public void ReportOneWillThrowIfMoreThanOneMatch() { SimpleExpression whereName = Expression.Like("Name", "Parent%"); Repository<Parent>.ReportOne<ParentDto>(ProjectByNameAndAge, whereName); } [Test] public void CanReportAll() { ICollection<ParentDto> dtos = Repository<Parent>.ReportAll<ParentDto>(ProjectByNameAndAge); Assert.AreEqual(parentsInDb.Count, dtos.Count); AssertDtosCreatedFrom(parentsInDb, dtos); } [Test] public void CanReportAllDistinct() { IList<Parent> parents = LoadAll<Parent>(); parents[0].Age = parents[1].Age; parents[0].Name = parents[1].Name; UnitOfWork.Current.Flush(); ICollection<ParentDto> dtos = Repository<Parent>.ReportAll<ParentDto>(ProjectByNameAndAge, true); Assert.AreEqual(parents.Count - 1, dtos.Count); } [Test] public void CanReportAllWithSorting() { ICollection<ParentDto> dtos = Repository<Parent>.ReportAll<ParentDto>(ProjectByNameAndAge, Order.Desc("Name")); AssertDtosCreatedFrom(parentsInDb, dtos); AssertDtosSortedByName(dtos, "Desc"); } [Test] public void CanReportAllMatchingCriteria() { DetachedCriteria where = DetachedCriteria.For<Parent>() .Add(Expression.Eq("Name", "Parent2")); ICollection<ParentDto> dtos = Repository<Parent>.ReportAll<ParentDto>(where, ProjectByNameAndAge); Assert.AreEqual(1, dtos.Count); AssertDtoCreatedFrom(parentsInDb[1], Collection.First(dtos)); } [Test] public void CanReportAllMatchingCriteriaWithSorting() { DetachedCriteria where = DetachedCriteria.For<Parent>() .Add(Expression.Like("Name", "Parent%")); ICollection<ParentDto> dtos = Repository<Parent>.ReportAll<ParentDto>(where, ProjectByNameAndAge, Order.Desc("Name")); Assert.AreEqual(parentsInDb.Count, dtos.Count); AssertDtosSortedByName(dtos, "Desc"); } [Test] public void CanReportAllMatchingCriterion() { SimpleExpression whereName = Expression.Eq("Name", "Parent1"); SimpleExpression whereAge = Expression.Eq("Age", 100); ICollection<ParentDto> dtos = Repository<Parent>.ReportAll<ParentDto>(ProjectByNameAndAge, whereName, whereAge); Assert.AreEqual(1, dtos.Count); AssertDtoCreatedFrom(parentsInDb[0], Collection.First(dtos)); } [Test] public void CanReportAllMatchingCriterionWithSorting() { SimpleExpression whereName = Expression.Like("Name", "Parent%"); Order[] orderBy = {Order.Desc("Name")}; ICollection<ParentDto> dtos = Repository<Parent>.ReportAll<ParentDto>(ProjectByNameAndAge, orderBy, whereName); Assert.AreEqual(parentsInDb.Count, dtos.Count); AssertDtosSortedByName(dtos, "Desc"); } private static void AssertDtoCreatedFrom(Parent parent, ParentDto dto) { Assert.AreEqual(parent.Age, dto.Age); Assert.AreEqual(parent.Name, dto.Name); } private void AssertDtosCreatedFrom(IList<Parent> parents, ICollection<ParentDto> dtos) { foreach (Parent parent in parents) { Predicate<ParentDto> matchByNameAndAge = delegate(ParentDto dto) { return dto.Age == parent.Age && dto.Name == parent.Name; }; if (Collection.Find(dtos, matchByNameAndAge) == null) Assert.Fail("Expected Dto not found"); } } private void AssertDtosSortedByName(ICollection<ParentDto> dtos, string sortOrder) { Comparison<ParentDto> sortedByName = delegate(ParentDto x, ParentDto y) { return x.Name.CompareTo(y.Name); }; AssertSorted(dtos, sortOrder, sortedByName); } private static ProjectionList ProjectByNameAndAge { get { return Projections.ProjectionList() .Add(Projections.Property("Name")) .Add(Projections.Property("Age")); } } } [TestFixture] public class ActiveRecordRepositoryProjectionTests : RepositoryProjectionTests { [TestFixtureSetUp] public override void OneTimeTestInitialize() { base.OneTimeTestInitialize(); string path = Path.GetFullPath(@"Repository\Windsor-AR.config"); IntializeNHibernateAndIoC(PersistenceFramework.ActiveRecord, path, MappingInfoForRepositoryTests); } } public class ParentSummaryDto { private string name; private int age; private int _numberOfChildren; public ParentSummaryDto(string name, int age, int numberOfChildren) { this.name = name; this.age = age; _numberOfChildren = numberOfChildren; } public int NumberOfChildren { get { return _numberOfChildren; } set { _numberOfChildren = value; } } public int Age { get { return age; } set { age = value; } } public string Name { get { return name; } set { name = value; } } } public class ParentDto { private string name; private int age; public ParentDto(string name, int age) { this.name = name; this.age = age; } public int Age { get { return age; } set { age = value; } } public string Name { get { return name; } set { name = value; } } } }
/* Copyright (c) 2004-2005 Jan Benda. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.IO; using System.Net; using System.Text; using System.Collections; using System.Diagnostics; using PHP.Core; using System.Security.Principal; using System.Security.AccessControl; namespace PHP.Core { #region Abstract Stream Wrapper /// <summary> /// Abstract base class for PHP stream wrappers. Descendants define /// methods implementing fopen, stat, unlink, rename, opendir, mkdir and rmdir /// for different stream types. /// </summary> public abstract partial class StreamWrapper { #region Optional Wrapper Operations (Warning) /// <include file='Doc/Wrappers.xml' path='docs/method[@name="Stat"]/*'/> /// <remarks> /// <seealso cref="StreamStatOptions"/> for the list of additional options. /// </remarks> public virtual StatStruct Stat(string path, StreamStatOptions options, StreamContext context, bool streamStat) { // int (*url_stat)(php_stream_wrapper *wrapper, char *url, int flags, php_stream_statbuf *ssb, php_stream_context *context TSRMLS_DC); PhpException.Throw(PhpError.Warning, CoreResources.GetString("wrapper_op_unsupported", "Stat")); return new StatStruct(); } #endregion } #endregion #region Local Filesystem Wrapper /// <summary> /// Derived from <see cref="StreamWrapper"/>, this class provides access to /// the local filesystem files. /// </summary> public partial class FileStreamWrapper : StreamWrapper { #region Opening a file /// <include file='Doc/Wrappers.xml' path='docs/method[@name="Open"]/*'/> public override PhpStream Open(ref string path, string mode, StreamOpenOptions options, StreamContext context) { Debug.Assert(path != null); //Debug.Assert(PhpPath.IsLocalFile(path)); // Get the File.Open modes from the mode string FileMode fileMode; FileAccess fileAccess; StreamAccessOptions ao; if (!ParseMode(mode, options, out fileMode, out fileAccess, out ao)) return null; // Open the native stream FileStream stream = null; try { // stream = File.Open(path, fileMode, fileAccess, FileShare.ReadWrite); stream = new FileStream(path, fileMode, fileAccess, FileShare.ReadWrite | FileShare.Delete); } catch (FileNotFoundException) { // Note: There may still be an URL in the path here. PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_not_exists", FileSystemUtils.StripPassword(path))); return null; } catch (IOException e) { if ((ao & StreamAccessOptions.Exclusive) > 0) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_exists", FileSystemUtils.StripPassword(path))); } else { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_io_error", FileSystemUtils.StripPassword(path), PhpException.ToErrorMessage(e.Message))); } return null; } catch (UnauthorizedAccessException) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_access_denied", FileSystemUtils.StripPassword(path))); return null; } catch (Exception) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_invalid", FileSystemUtils.StripPassword(path))); return null; } if ((ao & StreamAccessOptions.SeekEnd) > 0) { // Read/Write Append is not supported. Seek to the end of file manually. stream.Seek(0, SeekOrigin.End); } if ((ao & StreamAccessOptions.Temporary) > 0) { // Set the file attributes to Temporary too. File.SetAttributes(path, FileAttributes.Temporary); } return new NativeStream(stream, this, ao, path, context); } #endregion #region Optional Wrapper Operations Implementations #region Stat related methods and Stat caching /// <summary> /// Creates a <see cref="StatStruct"/> from the <see cref="StatStruct"/> filling the common /// members (for files and directories) from the given <see cref="FileSystemInfo"/> class. /// The <c>size</c> member (numeric index <c>7</c>) may be filled by the caller /// for when <paramref name="info"/> is a <see cref="FileInfo"/>. /// </summary> /// <remarks> /// According to these outputs (PHP Win32): /// <code> /// fstat(somefile.txt): /// [dev] => 0 /// [ino] => 0 /// [mode] => 33206 /// [nlink] => 1 /// [uid] => 0 /// [gid] => 0 /// [rdev] => 0 /// [size] => 24 /// [atime] => 1091131360 /// [mtime] => 1091051699 /// [ctime] => 1091051677 /// [blksize] => -1 /// [blocks] => -1 /// /// stat(somefile.txt): /// [dev] => 2 /// [ino] => 0 /// [mode] => 33206 // 0100666 /// [nlink] => 1 /// [uid] => 0 /// [gid] => 0 /// [rdev] => 2 /// [size] => 24 /// [atime] => 1091129621 /// [mtime] => 1091051699 /// [ctime] => 1091051677 /// [blksize] => -1 /// [blocks] => -1 /// /// stat(somedir): /// [st_dev] => 2 /// [st_ino] => 0 /// [st_mode] => 16895 // 040777 /// [st_nlink] => 1 /// [st_uid] => 0 /// [st_gid] => 0 /// [st_rdev] => 2 /// [st_size] => 0 /// [st_atime] => 1091109319 /// [st_mtime] => 1091044521 /// [st_ctime] => 1091044521 /// [st_blksize] => -1 /// [st_blocks] => -1 /// </code> /// </remarks> /// <param name="info">A <see cref="FileInfo"/> or <see cref="DirectoryInfo"/> /// of the <c>stat()</c>ed filesystem entry.</param> /// <param name="attributes">The file or directory attributes.</param> /// <param name="path">The path to the file / directory.</param> /// <returns>A <see cref="StatStruct"/> for use in the <c>stat()</c> related functions.</returns> internal static StatStruct BuildStatStruct(FileSystemInfo info, FileAttributes attributes, string path) { StatStruct result;// = new StatStruct(); uint device = unchecked((uint)(char.ToLower(info.FullName[0]) - 'a')); // index of the disk ushort mode = (ushort)BuildMode(info, attributes, path); long atime,mtime,ctime; atime = ToStatUnixTimeStamp(info, (_info) => _info.LastAccessTimeUtc); mtime = ToStatUnixTimeStamp(info, (_info) => _info.LastWriteTimeUtc); ctime = ToStatUnixTimeStamp(info, (_info) => _info.CreationTimeUtc); result.st_dev = device; // device number result.st_ino = 0; // inode number result.st_mode = mode; // inode protection mode result.st_nlink = 1; // number of links result.st_uid = 0; // userid of owner result.st_gid = 0; // groupid of owner result.st_rdev = device; // device type, if inode device -1 result.st_size = 0; // size in bytes FileInfo file_info = info as FileInfo; if (file_info != null) result.st_size = FileSystemUtils.FileSize(file_info); result.st_atime = atime; // time of last access (unix timestamp) result.st_mtime = mtime; // time of last modification (unix timestamp) result.st_ctime = ctime; // time of last change (unix timestamp) //result.st_blksize = -1; // blocksize of filesystem IO (-1) //result.st_blocks = -1; // number of blocks allocated (-1) return result; } /// <summary> /// Adjusts UTC time of a file by adding Daylight Saving Time difference. /// Makes file times working in the same way as in PHP and Windows Explorer. /// </summary> /// <param name="info"><see cref="FileSystemInfo"/> object reference. Used to avoid creating of closure when passing <paramref name="utcTimeFunc"/>.</param> /// <param name="utcTimeFunc">Function obtaining specific <see cref="DateTime"/> from given <paramref name="info"/>.</param> private static long ToStatUnixTimeStamp(FileSystemInfo info, Func<FileSystemInfo, DateTime> utcTimeFunc) { DateTime utcTime; try { utcTime = utcTimeFunc(info); } catch (ArgumentOutOfRangeException) { //On Linux this exception might be thrown if a file metadata are corrupted //just catch it and return 0; return 0; } return DateTimeUtils.UtcToUnixTimeStamp(utcTime + DateTimeUtils.GetDaylightTimeDifference(utcTime, DateTime.UtcNow)); } /// <summary> /// Gets the ACL of a file and converts it into UNIX-like file mode /// </summary> public static FileModeFlags GetFileMode(FileInfo info) { System.Security.AccessControl.AuthorizationRuleCollection acl; try { // Get the collection of authorization rules that apply to the given directory acl = info.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); } catch (UnauthorizedAccessException) { //we don't want to throw this exception from getting access list return 0; } return GetFileMode(acl); } /// <summary> /// Gets the ACL of a directory and converts it ACL into UNIX-like file mode /// </summary> public static FileModeFlags GetFileMode(DirectoryInfo info) { System.Security.AccessControl.AuthorizationRuleCollection acl; try { // Get the collection of authorization rules that apply to the given directory acl = info.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); } catch(UnauthorizedAccessException) { //we don't want to throw this exception from getting access list return 0; } return GetFileMode(acl); } /// <summary> /// Converts ACL into UNIX-like file mode /// </summary> private static FileModeFlags GetFileMode(System.Security.AccessControl.AuthorizationRuleCollection rules) { WindowsIdentity user = System.Security.Principal.WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(user); FileModeFlags result; // These are set to true if either the allow read or deny read access rights are set bool allowRead = false; bool denyRead = false; bool allowWrite = false; bool denyWrite = false; bool allowExecute = false; bool denyExecute = false; foreach (FileSystemAccessRule currentRule in rules) { // If the current rule applies to the current user if (user.User.Equals(currentRule.IdentityReference) || principal.IsInRole((SecurityIdentifier)currentRule.IdentityReference)) { switch (currentRule.AccessControlType) { case AccessControlType.Deny: denyRead |= (currentRule.FileSystemRights & FileSystemRights.ListDirectory | FileSystemRights.Read) != 0; denyWrite |= (currentRule.FileSystemRights & FileSystemRights.Write) != 0; denyExecute |= (currentRule.FileSystemRights & FileSystemRights.ExecuteFile) != 0; break; case AccessControlType.Allow: allowRead |= (currentRule.FileSystemRights & FileSystemRights.ListDirectory | FileSystemRights.Read) != 0; allowWrite |= (currentRule.FileSystemRights & FileSystemRights.Write) != 0; allowExecute |= (currentRule.FileSystemRights & FileSystemRights.ExecuteFile) != 0; break; } } } result = (allowRead & !denyRead) ? FileModeFlags.Read : 0; result |= (allowWrite & !denyWrite) ? FileModeFlags.Write : 0; result |= (allowExecute & !denyExecute) ? FileModeFlags.Execute : 0; return result; } /// <summary> /// Creates the UNIX-like file mode depending on the file or directory attributes. /// </summary> /// <param name="info">Information about file system object.</param> /// <param name="attributes">Attributes of the file.</param> /// <param name="path">Paths to the file.</param> /// <returns>UNIX-like file mode.</returns> private static FileModeFlags BuildMode(FileSystemInfo/*!*/info, FileAttributes attributes, string path) { // TODO: remove !EnvironmentUtils.IsDotNetFramework branches; // use mono.unix.native.stat on Mono instead of BuildStatStruct(), http://docs.go-mono.com/?link=M%3aMono.Unix.Native.Syscall.stat // TODO: use Win32 stat on Windows // Simulates the UNIX file mode. FileModeFlags rv; if ((attributes & FileAttributes.Directory) != 0) { // a directory: rv = FileModeFlags.Directory; if (EnvironmentUtils.IsDotNetFramework) { rv |= GetFileMode((DirectoryInfo)info); // PHP on Windows always shows that directory isn't executable rv &= ~FileModeFlags.Execute; } else { rv |= FileModeFlags.Read | FileModeFlags.Execute | FileModeFlags.Write; } } else { // a file: rv = FileModeFlags.File; if (EnvironmentUtils.IsDotNetFramework) { rv |= GetFileMode((FileInfo)info); if ((attributes & FileAttributes.ReadOnly) != 0 && (rv & FileModeFlags.Write) != 0) rv &= ~FileModeFlags.Write; if ((rv & FileModeFlags.Execute) == 0) { // PHP on Windows checks the file internaly wheather it is executable // we just look on the extension string ext = Path.GetExtension(path); if ((ext.EqualsOrdinalIgnoreCase(".exe")) || (ext.EqualsOrdinalIgnoreCase(".com")) || (ext.EqualsOrdinalIgnoreCase(".bat"))) rv |= FileModeFlags.Execute; } } else { rv |= FileModeFlags.Read; // | FileModeFlags.Execute; if ((attributes & FileAttributes.ReadOnly) == 0) rv |= FileModeFlags.Write; } } // return rv; } /// <include file='Doc/Wrappers.xml' path='docs/method[@name="Stat"]/*'/> public override StatStruct Stat(string path, StreamStatOptions options, StreamContext context, bool streamStat) { StatStruct invalid = new StatStruct(); invalid.st_size = -1; Debug.Assert(path != null); // Note: path is already absolute w/o the scheme, the permissions have already been checked. return HandleNewFileSystemInfo(invalid, path, (p) => { FileSystemInfo info = null; info = new DirectoryInfo(p); if (!info.Exists) { info = new FileInfo(p); if (!info.Exists) { return invalid; } } return BuildStatStruct(info, info.Attributes, p); }); } /// <summary> /// Try the new FileSystemInfo based operation and hamdle exceptions properly. /// </summary> /// <typeparam name="T">The return value type.</typeparam> /// <param name="invalid">Invalid value.</param> /// <param name="path">Path to the resource passed to the <paramref name="action"/>. Also used for error control.</param> /// <param name="action">Action to try. The first argument is the path.</param> /// <returns>The value of <paramref name="action"/>() or <paramref name="invalid"/>.</returns> public static T HandleNewFileSystemInfo<T>(T invalid, string path, Func<string,T>/*!*/action) { try { return action(path); } catch (ArgumentException) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_stat_invalid_path", FileSystemUtils.StripPassword(path))); } catch (PathTooLongException) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_stat_invalid_path", FileSystemUtils.StripPassword(path))); } catch (Exception e) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_error", FileSystemUtils.StripPassword(path), e.Message)); } return invalid; } #endregion /// <include file='Doc/Wrappers.xml' path='docs/method[@name="Unlink"]/*'/> public override bool Unlink(string path, StreamUnlinkOptions options, StreamContext context) { Debug.Assert(path != null); Debug.Assert(Path.IsPathRooted(path)); try { File.Delete(path); return true; } catch (DirectoryNotFoundException) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_unlink_file_not_found", FileSystemUtils.StripPassword(path))); } catch (UnauthorizedAccessException) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_access_denied", FileSystemUtils.StripPassword(path))); } catch (IOException e) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_unlink_io_error", FileSystemUtils.StripPassword(path), PhpException.ToErrorMessage(e.Message))); } catch (Exception) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_unlink_error", FileSystemUtils.StripPassword(path))); } return false; } /// <include file='Doc/Wrappers.xml' path='docs/method[@name="Listing"]/*'/> public override string[] Listing(string path, StreamListingOptions options, StreamContext context) { Debug.Assert(path != null); Debug.Assert(Path.IsPathRooted(path)); try { string[] listing = Directory.GetFileSystemEntries(path); bool root = Path.GetPathRoot(path) == path; int index = root ? 0 : 2; string[] rv = new string[listing.Length + index]; // Remove the absolute path information (PHP returns only filenames) int pathLength = path.Length; if (path[pathLength - 1] != Path.DirectorySeparatorChar) pathLength++; // Check for the '.' and '..'; they should be present if (!root) { rv[0] = "."; rv[1] = ".."; } for (int i = 0; i < listing.Length; i++) { rv[index++] = listing[i].Substring(pathLength); } return rv; } catch (DirectoryNotFoundException) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_bad_directory", FileSystemUtils.StripPassword(path))); } catch (UnauthorizedAccessException) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_access_denied", FileSystemUtils.StripPassword(path))); } catch (Exception e) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_error", FileSystemUtils.StripPassword(path), e.Message)); } return null; } /// <include file='Doc/Wrappers.xml' path='docs/method[@name="Rename"]/*'/> public override bool Rename(string fromPath, string toPath, StreamRenameOptions options, StreamContext context) { try { File.Move(fromPath, toPath); return true; } catch (UnauthorizedAccessException) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_access_denied", FileSystemUtils.StripPassword(fromPath))); } catch (IOException) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_rename_file_exists", FileSystemUtils.StripPassword(fromPath), FileSystemUtils.StripPassword(toPath))); } catch (Exception e) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_error", FileSystemUtils.StripPassword(fromPath), e.Message)); } return false; } /// <include file='Doc/Wrappers.xml' path='docs/method[@name="MakeDirectory"]/*'/> public override bool MakeDirectory(string path, int accessMode, StreamMakeDirectoryOptions options, StreamContext context) { if ((path == null) || (path == string.Empty)) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("path_argument_empty")); return false; } try { // Default Framework MakeDirectory is RECURSIVE, check for other intention. if ((options & StreamMakeDirectoryOptions.Recursive) == 0) { int pos = path.Length - 1; if (path[pos] == Path.DirectorySeparatorChar) pos--; pos = path.LastIndexOf(Path.DirectorySeparatorChar, pos); if (pos <= 0) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_directory_make_root", FileSystemUtils.StripPassword(path))); return false; } // Parent must exist if not recursive. string parent = path.Substring(0, pos); if (!Directory.Exists(parent)) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_directory_make_parent", FileSystemUtils.StripPassword(path))); return false; } } // Creates the whole path Directory.CreateDirectory(path); return true; } catch (UnauthorizedAccessException) { // The caller does not have the required permission. PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_directory_access_denied", FileSystemUtils.StripPassword(path))); } catch (IOException) { // The directory specified by path is read-only or is not empty. PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_directory_error", FileSystemUtils.StripPassword(path))); } catch (Exception e) { // The specified path is invalid, such as being on an unmapped drive ... PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_error", FileSystemUtils.StripPassword(path), e.Message)); } return false; } /// <include file='Doc/Wrappers.xml' path='docs/method[@name="RemoveDirectory"]/*'/> public override bool RemoveDirectory(string path, StreamRemoveDirectoryOptions options, StreamContext context) { try { // Deletes the directory (but not the contents - must be empty) Directory.Delete(path, false); return true; } catch (UnauthorizedAccessException) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_access_denied", FileSystemUtils.StripPassword(path))); } catch (IOException) { // Directory not empty. PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_rmdir_io_error", FileSystemUtils.StripPassword(path))); } return false; } #endregion } #endregion #region Input/Output Stream Wrapper /// <summary> /// Derived from <see cref="StreamWrapper"/>, this class provides access to the PHP input/output streams. /// </summary> public partial class InputOutputStreamWrapper : StreamWrapper { /// <summary> /// Represents the console input stream (alias php://stdin). /// </summary> /// <remarks> /// It is a persistent text stream. This means that it is never closed /// by <c>fclose()</c> and <c>\r\n</c> is converted to <c>\n</c>. /// </remarks> public static PhpStream In { get { if (stdin == null) { stdin = new NativeStream(Console.OpenStandardInput(), null, StreamAccessOptions.Read | StreamAccessOptions.UseText | StreamAccessOptions.Persistent, "php://stdin", StreamContext.Default); stdin.IsReadBuffered = false; // EX: cache this as a persistent stream (incl. path and options) } return stdin; } } private static PhpStream stdin = null; /// <summary> /// Represents the console output stream (alias php://stdout). /// </summary> /// <remarks> /// It is a persistent text stream. This means that it is never closed /// by <c>fclose()</c> and <c>\n</c> is converted to <c>\r\n</c>. /// </remarks> public static PhpStream Out { get { if (stdout == null) { stdout = new NativeStream(Console.OpenStandardOutput(), null, StreamAccessOptions.Write | StreamAccessOptions.UseText | StreamAccessOptions.Persistent, "php://stdout", StreamContext.Default); stdout.IsWriteBuffered = false; // EX: cache this as a persistent stream } return stdout; } } private static PhpStream stdout = null; /// <summary> /// Represents the console error stream (alias php://error). /// </summary> /// <remarks> /// It is a persistent text stream. This means that it is never closed /// by <c>fclose()</c> and <c>\n</c> is converted to <c>\r\n</c>. /// </remarks> public static PhpStream Error { get { if (stderr == null) { stderr = new NativeStream(Console.OpenStandardInput(), null, StreamAccessOptions.Write | StreamAccessOptions.UseText | StreamAccessOptions.Persistent, "php://stderr", StreamContext.Default); stderr.IsWriteBuffered = false; // EX: cache this as a persistent stream } return stderr; } } private static PhpStream stderr = null; } #endregion }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace CTPPV5.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { public sealed partial class FileCodeModel { private const int ElementAddedDispId = 1; private const int ElementChangedDispId = 2; private const int ElementDeletedDispId = 3; private const int ElementDeletedDispId2 = 4; public bool FireEvents() { var needMoreTime = false; _codeElementTable.CleanUpDeadObjects(); needMoreTime = _codeElementTable.NeedsCleanUp; if (this.IsZombied) { // file is removed from the solution. this can happen if a fireevent is enqueued to foreground notification service // but the file itself is removed from the solution before it has a chance to run return needMoreTime; } Document document; if (!TryGetDocument(out document)) { // file is removed from the solution. this can happen if a fireevent is enqueued to foreground notification service // but the file itself is removed from the solution before it has a chance to run return needMoreTime; } // TODO(DustinCa): Enqueue unknown change event if a file is closed without being saved. var oldTree = _lastSyntaxTree; var newTree = document .GetSyntaxTreeAsync(CancellationToken.None) .WaitAndGetResult(CancellationToken.None); _lastSyntaxTree = newTree; if (oldTree == newTree || oldTree.IsEquivalentTo(newTree, topLevel: true)) { return needMoreTime; } var eventQueue = this.CodeModelService.CollectCodeModelEvents(oldTree, newTree); if (eventQueue.Count == 0) { return needMoreTime; } var provider = GetAbstractProject() as IProjectCodeModelProvider; if (provider == null) { return needMoreTime; } ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> fileCodeModelHandle; if (!provider.ProjectCodeModel.TryGetCachedFileCodeModel(this.Workspace.GetFilePath(GetDocumentId()), out fileCodeModelHandle)) { return needMoreTime; } var extensibility = (EnvDTE80.IVsExtensibility2)this.State.ServiceProvider.GetService(typeof(EnvDTE.IVsExtensibility)); foreach (var codeModelEvent in eventQueue) { EnvDTE.CodeElement element; object parentElement; GetElementsForCodeModelEvent(codeModelEvent, out element, out parentElement); if (codeModelEvent.Type == CodeModelEventType.Add) { extensibility.FireCodeModelEvent(ElementAddedDispId, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown); } else if (codeModelEvent.Type == CodeModelEventType.Remove) { extensibility.FireCodeModelEvent3(ElementDeletedDispId2, parentElement, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown); extensibility.FireCodeModelEvent(ElementDeletedDispId, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown); } else if (codeModelEvent.Type.IsChange()) { extensibility.FireCodeModelEvent(ElementChangedDispId, element, ConvertToChangeKind(codeModelEvent.Type)); } else { Debug.Fail("Invalid event type: " + codeModelEvent.Type); } } return needMoreTime; } private EnvDTE80.vsCMChangeKind ConvertToChangeKind(CodeModelEventType eventType) { EnvDTE80.vsCMChangeKind result = 0; if ((eventType & CodeModelEventType.Rename) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindRename; } if ((eventType & CodeModelEventType.Unknown) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown; } if ((eventType & CodeModelEventType.BaseChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindBaseChange; } if ((eventType & CodeModelEventType.TypeRefChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindTypeRefChange; } if ((eventType & CodeModelEventType.SigChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindSignatureChange; } if ((eventType & CodeModelEventType.ArgChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindArgumentChange; } return result; } // internal for testing internal void GetElementsForCodeModelEvent(CodeModelEvent codeModelEvent, out EnvDTE.CodeElement element, out object parentElement) { parentElement = GetParentElementForCodeModelEvent(codeModelEvent); if (codeModelEvent.Node == null) { element = this.CodeModelService.CreateUnknownRootNamespaceCodeElement(this.State, this); } else if (this.CodeModelService.IsParameterNode(codeModelEvent.Node)) { element = GetParameterElementForCodeModelEvent(codeModelEvent, parentElement); } else if (this.CodeModelService.IsAttributeNode(codeModelEvent.Node)) { element = GetAttributeElementForCodeModelEvent(codeModelEvent, parentElement); } else if (this.CodeModelService.IsAttributeArgumentNode(codeModelEvent.Node)) { element = GetAttributeArgumentElementForCodeModelEvent(codeModelEvent, parentElement); } else { if (codeModelEvent.Type == CodeModelEventType.Remove) { element = this.CodeModelService.CreateUnknownCodeElement(this.State, this, codeModelEvent.Node); } else { element = this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.Node); } } if (element == null) { Debug.Fail("We should have created an element for this event!"); } Debug.Assert(codeModelEvent.Type != CodeModelEventType.Remove || parentElement != null); } private object GetParentElementForCodeModelEvent(CodeModelEvent codeModelEvent) { if (this.CodeModelService.IsParameterNode(codeModelEvent.Node) || this.CodeModelService.IsAttributeArgumentNode(codeModelEvent.Node)) { if (codeModelEvent.ParentNode != null) { return this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode); } } else if (this.CodeModelService.IsAttributeNode(codeModelEvent.Node)) { if (codeModelEvent.ParentNode != null) { return this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode); } else { return this; } } else if (codeModelEvent.Type == CodeModelEventType.Remove) { if (codeModelEvent.ParentNode != null && codeModelEvent.ParentNode.Parent != null) { return this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode); } else { return this; } } return null; } private EnvDTE.CodeElement GetParameterElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement) { var parentDelegate = parentElement as EnvDTE.CodeDelegate; if (parentDelegate != null) { return GetParameterElementForCodeModelEvent(codeModelEvent, parentDelegate.Parameters, parentElement); } var parentFunction = parentElement as EnvDTE.CodeFunction; if (parentFunction != null) { return GetParameterElementForCodeModelEvent(codeModelEvent, parentFunction.Parameters, parentElement); } var parentProperty = parentElement as EnvDTE80.CodeProperty2; if (parentProperty != null) { return GetParameterElementForCodeModelEvent(codeModelEvent, parentProperty.Parameters, parentElement); } return null; } private EnvDTE.CodeElement GetParameterElementForCodeModelEvent(CodeModelEvent codeModelEvent, EnvDTE.CodeElements parentParameters, object parentElement) { if (parentParameters == null) { return null; } var parameterName = this.CodeModelService.GetName(codeModelEvent.Node); if (codeModelEvent.Type == CodeModelEventType.Remove) { var parentCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeMember>(parentElement); if (parentCodeElement != null) { return (EnvDTE.CodeElement)CodeParameter.Create(this.State, parentCodeElement, parameterName); } } else { return parentParameters.Item(parameterName); } return null; } private EnvDTE.CodeElement GetAttributeElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement) { var node = codeModelEvent.Node; var parentNode = codeModelEvent.ParentNode; var eventType = codeModelEvent.Type; var parentType = parentElement as EnvDTE.CodeType; if (parentType != null) { return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentType.Attributes, parentElement); } var parentFunction = parentElement as EnvDTE.CodeFunction; if (parentFunction != null) { return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentFunction.Attributes, parentElement); } var parentProperty = parentElement as EnvDTE.CodeProperty; if (parentProperty != null) { return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentProperty.Attributes, parentElement); } var parentEvent = parentElement as EnvDTE80.CodeEvent; if (parentEvent != null) { return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentEvent.Attributes, parentElement); } var parentVariable = parentElement as EnvDTE.CodeVariable; if (parentVariable != null) { return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentVariable.Attributes, parentElement); } // In the following case, parentNode is null and the root should be used instead. var parentFileCodeModel = parentElement as EnvDTE.FileCodeModel; if (parentFileCodeModel != null) { var fileCodeModel = ComAggregate.TryGetManagedObject<FileCodeModel>(parentElement); parentNode = fileCodeModel.GetSyntaxRoot(); return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentFileCodeModel.CodeElements, parentElement); } return null; } private EnvDTE.CodeElement GetAttributeElementForCodeModelEvent(SyntaxNode node, SyntaxNode parentNode, CodeModelEventType eventType, EnvDTE.CodeElements elementsToSearch, object parentObject) { if (elementsToSearch == null) { return null; } string name; int ordinal; CodeModelService.GetAttributeNameAndOrdinal(parentNode, node, out name, out ordinal); if (eventType == CodeModelEventType.Remove) { if (parentObject is EnvDTE.CodeElement) { var parentCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(parentObject); if (parentCodeElement != null) { return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this, parentCodeElement, name, ordinal); } } else if (parentObject is EnvDTE.FileCodeModel) { var parentFileCodeModel = ComAggregate.TryGetManagedObject<FileCodeModel>(parentObject); if (parentFileCodeModel != null && parentFileCodeModel == this) { return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this, null, name, ordinal); } } } else { int testOrdinal = 0; foreach (EnvDTE.CodeElement element in elementsToSearch) { if (element.Kind != EnvDTE.vsCMElement.vsCMElementAttribute) { continue; } if (element.Name == name) { if (ordinal == testOrdinal) { return element; } testOrdinal++; } } } return null; } private EnvDTE.CodeElement GetAttributeArgumentElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement) { var parentAttribute = parentElement as EnvDTE80.CodeAttribute2; if (parentAttribute != null) { return GetAttributeArgumentForCodeModelEvent(codeModelEvent, parentAttribute.Arguments, parentElement); } return null; } private EnvDTE.CodeElement GetAttributeArgumentForCodeModelEvent(CodeModelEvent codeModelEvent, EnvDTE.CodeElements parentAttributeArguments, object parentElement) { if (parentAttributeArguments == null) { return null; } SyntaxNode attributeNode; int ordinal; CodeModelService.GetAttributeArgumentParentAndIndex(codeModelEvent.Node, out attributeNode, out ordinal); if (codeModelEvent.Type == CodeModelEventType.Remove) { var parentCodeElement = ComAggregate.TryGetManagedObject<CodeAttribute>(parentElement); if (parentCodeElement != null) { return (EnvDTE.CodeElement)CodeAttributeArgument.Create(this.State, parentCodeElement, ordinal); } } else { return parentAttributeArguments.Item(ordinal + 1); // Needs to be 1-based to call back into code model } return null; } } }
// ZipOutputStream.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // HISTORY // 22-12-2009 Z-1649 Added AES support // 22-02-2010 Z-1648 Zero byte entries would create invalid zip files // 27-07-2012 Z-1724 Compressed size was incorrect in local header when CRC and Size are known #if ZIPLIB using System; using System.IO; using System.Collections; using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; namespace ICSharpCode.SharpZipLib.Zip { /// <summary> /// This is a DeflaterOutputStream that writes the files into a zip /// archive one after another. It has a special method to start a new /// zip entry. The zip entries contains information about the file name /// size, compressed size, CRC, etc. /// /// It includes support for Stored and Deflated entries. /// This class is not thread safe. /// <br/> /// <br/>Author of the original java version : Jochen Hoenicke /// </summary> /// <example> This sample shows how to create a zip file /// <code> /// using System; /// using System.IO; /// /// using ICSharpCode.SharpZipLib.Core; /// using ICSharpCode.SharpZipLib.Zip; /// /// class MainClass /// { /// public static void Main(string[] args) /// { /// string[] filenames = Directory.GetFiles(args[0]); /// byte[] buffer = new byte[4096]; /// /// using ( ZipOutputStream s = new ZipOutputStream(File.Create(args[1])) ) { /// /// s.SetLevel(9); // 0 - store only to 9 - means best compression /// /// foreach (string file in filenames) { /// ZipEntry entry = new ZipEntry(file); /// s.PutNextEntry(entry); /// /// using (FileStream fs = File.OpenRead(file)) { /// StreamUtils.Copy(fs, s, buffer); /// } /// } /// } /// } /// } /// </code> /// </example> internal class ZipOutputStream : DeflaterOutputStream { #region Constructors /// <summary> /// Creates a new Zip output stream, writing a zip archive. /// </summary> /// <param name="baseOutputStream"> /// The output stream to which the archive contents are written. /// </param> public ZipOutputStream(Stream baseOutputStream) : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true)) { } /// <summary> /// Creates a new Zip output stream, writing a zip archive. /// </summary> /// <param name="baseOutputStream">The output stream to which the archive contents are written.</param> /// <param name="bufferSize">Size of the buffer to use.</param> public ZipOutputStream( Stream baseOutputStream, int bufferSize ) : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true), bufferSize) { } #endregion /// <summary> /// Gets a flag value of true if the central header has been added for this archive; false if it has not been added. /// </summary> /// <remarks>No further entries can be added once this has been done.</remarks> public bool IsFinished { get { return entries == null; } } /// <summary> /// Set the zip file comment. /// </summary> /// <param name="comment"> /// The comment text for the entire archive. /// </param> /// <exception name ="ArgumentOutOfRangeException"> /// The converted comment is longer than 0xffff bytes. /// </exception> public void SetComment(string comment) { // TODO: Its not yet clear how to handle unicode comments here. byte[] commentBytes = ZipConstants.ConvertToArray(comment); if (commentBytes.Length > 0xffff) { throw new ArgumentOutOfRangeException("comment"); } zipComment = commentBytes; } /// <summary> /// Sets the compression level. The new level will be activated /// immediately. /// </summary> /// <param name="level">The new compression level (1 to 9).</param> /// <exception cref="ArgumentOutOfRangeException"> /// Level specified is not supported. /// </exception> /// <see cref="ICSharpCode.SharpZipLib.Zip.Compression.Deflater"/> public void SetLevel(int level) { deflater_.SetLevel(level); defaultCompressionLevel = level; } /// <summary> /// Get the current deflater compression level /// </summary> /// <returns>The current compression level</returns> public int GetLevel() { return deflater_.GetLevel(); } /// <summary> /// Get / set a value indicating how Zip64 Extension usage is determined when adding entries. /// </summary> /// <remarks>Older archivers may not understand Zip64 extensions. /// If backwards compatability is an issue be careful when adding <see cref="ZipEntry.Size">entries</see> to an archive. /// Setting this property to off is workable but less desirable as in those circumstances adding a file /// larger then 4GB will fail.</remarks> public UseZip64 UseZip64 { get { return useZip64_; } set { useZip64_ = value; } } /// <summary> /// Write an unsigned short in little endian byte order. /// </summary> private void WriteLeShort(int value) { unchecked { baseOutputStream_.WriteByte((byte)(value & 0xff)); baseOutputStream_.WriteByte((byte)((value >> 8) & 0xff)); } } /// <summary> /// Write an int in little endian byte order. /// </summary> private void WriteLeInt(int value) { unchecked { WriteLeShort(value); WriteLeShort(value >> 16); } } /// <summary> /// Write an int in little endian byte order. /// </summary> private void WriteLeLong(long value) { unchecked { WriteLeInt((int)value); WriteLeInt((int)(value >> 32)); } } /// <summary> /// Starts a new Zip entry. It automatically closes the previous /// entry if present. /// All entry elements bar name are optional, but must be correct if present. /// If the compression method is stored and the output is not patchable /// the compression for that entry is automatically changed to deflate level 0 /// </summary> /// <param name="entry"> /// the entry. /// </param> /// <exception cref="System.ArgumentNullException"> /// if entry passed is null. /// </exception> /// <exception cref="System.IO.IOException"> /// if an I/O error occured. /// </exception> /// <exception cref="System.InvalidOperationException"> /// if stream was finished /// </exception> /// <exception cref="ZipException"> /// Too many entries in the Zip file<br/> /// Entry name is too long<br/> /// Finish has already been called<br/> /// </exception> public void PutNextEntry(ZipEntry entry) { if ( entry == null ) { throw new ArgumentNullException("entry"); } if (entries == null) { throw new InvalidOperationException("ZipOutputStream was finished"); } if (curEntry != null) { CloseEntry(); } if (entries.Count == int.MaxValue) { throw new ZipException("Too many entries for Zip file"); } CompressionMethod method = entry.CompressionMethod; int compressionLevel = defaultCompressionLevel; // Clear flags that the library manages internally entry.Flags &= (int)GeneralBitFlags.UnicodeText; patchEntryHeader = false; bool headerInfoAvailable; // No need to compress - definitely no data. if (entry.Size == 0) { entry.CompressedSize = entry.Size; entry.Crc = 0; method = CompressionMethod.Stored; headerInfoAvailable = true; } else { headerInfoAvailable = (entry.Size >= 0) && entry.HasCrc && entry.CompressedSize >= 0; // Switch to deflation if storing isnt possible. if (method == CompressionMethod.Stored) { if (!headerInfoAvailable) { if (!CanPatchEntries) { // Can't patch entries so storing is not possible. method = CompressionMethod.Deflated; compressionLevel = 0; } } else // entry.size must be > 0 { entry.CompressedSize = entry.Size; headerInfoAvailable = entry.HasCrc; } } } if (headerInfoAvailable == false) { if (CanPatchEntries == false) { // Only way to record size and compressed size is to append a data descriptor // after compressed data. // Stored entries of this form have already been converted to deflating. entry.Flags |= 8; } else { patchEntryHeader = true; } } if (Password != null) { entry.IsCrypted = true; if (entry.Crc < 0) { // Need to append a data descriptor as the crc isnt available for use // with encryption, the date is used instead. Setting the flag // indicates this to the decompressor. entry.Flags |= 8; } } entry.Offset = offset; entry.CompressionMethod = (CompressionMethod)method; curMethod = method; sizePatchPos = -1; if ( (useZip64_ == UseZip64.On) || ((entry.Size < 0) && (useZip64_ == UseZip64.Dynamic)) ) { entry.ForceZip64(); } // Write the local file header WriteLeInt(ZipConstants.LocalHeaderSignature); WriteLeShort(entry.Version); WriteLeShort(entry.Flags); WriteLeShort((byte)entry.CompressionMethodForHeader); WriteLeInt((int)entry.DosTime); // TODO: Refactor header writing. Its done in several places. if (headerInfoAvailable) { WriteLeInt((int)entry.Crc); if ( entry.LocalHeaderRequiresZip64 ) { WriteLeInt(-1); WriteLeInt(-1); } else { WriteLeInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize); WriteLeInt((int)entry.Size); } } else { if (patchEntryHeader) { crcPatchPos = baseOutputStream_.Position; } WriteLeInt(0); // Crc if ( patchEntryHeader ) { sizePatchPos = baseOutputStream_.Position; } // For local header both sizes appear in Zip64 Extended Information if ( entry.LocalHeaderRequiresZip64 || patchEntryHeader ) { WriteLeInt(-1); WriteLeInt(-1); } else { WriteLeInt(0); // Compressed size WriteLeInt(0); // Uncompressed size } } byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name); if (name.Length > 0xFFFF) { throw new ZipException("Entry name too long."); } ZipExtraData ed = new ZipExtraData(entry.ExtraData); if (entry.LocalHeaderRequiresZip64) { ed.StartNewEntry(); if (headerInfoAvailable) { ed.AddLeLong(entry.Size); ed.AddLeLong(entry.CompressedSize); } else { ed.AddLeLong(-1); ed.AddLeLong(-1); } ed.AddNewEntry(1); if ( !ed.Find(1) ) { throw new ZipException("Internal error cant find extra data"); } if ( patchEntryHeader ) { sizePatchPos = ed.CurrentReadIndex; } } else { ed.Delete(1); } #if !NET_1_1 && !NETCF_2_0 if (entry.AESKeySize > 0) { AddExtraDataAES(entry, ed); } #endif byte[] extra = ed.GetEntryData(); WriteLeShort(name.Length); WriteLeShort(extra.Length); if ( name.Length > 0 ) { baseOutputStream_.Write(name, 0, name.Length); } if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) { sizePatchPos += baseOutputStream_.Position; } if ( extra.Length > 0 ) { baseOutputStream_.Write(extra, 0, extra.Length); } offset += ZipConstants.LocalHeaderBaseSize + name.Length + extra.Length; // Fix offsetOfCentraldir for AES if (entry.AESKeySize > 0) offset += entry.AESOverheadSize; // Activate the entry. curEntry = entry; crc.Reset(); if (method == CompressionMethod.Deflated) { deflater_.Reset(); deflater_.SetLevel(compressionLevel); } size = 0; if (entry.IsCrypted) { #if !NET_1_1 && !NETCF_2_0 if (entry.AESKeySize > 0) { WriteAESHeader(entry); } else #endif { if (entry.Crc < 0) { // so testing Zip will says its ok WriteEncryptionHeader(entry.DosTime << 16); } else { WriteEncryptionHeader(entry.Crc); } } } } /// <summary> /// Closes the current entry, updating header and footer information as required /// </summary> /// <exception cref="System.IO.IOException"> /// An I/O error occurs. /// </exception> /// <exception cref="System.InvalidOperationException"> /// No entry is active. /// </exception> public void CloseEntry() { if (curEntry == null) { throw new InvalidOperationException("No open entry"); } long csize = size; // First finish the deflater, if appropriate if (curMethod == CompressionMethod.Deflated) { if (size >= 0) { base.Finish(); csize = deflater_.TotalOut; } else { deflater_.Reset(); } } // Write the AES Authentication Code (a hash of the compressed and encrypted data) if (curEntry.AESKeySize > 0) { baseOutputStream_.Write(AESAuthCode, 0, 10); } if (curEntry.Size < 0) { curEntry.Size = size; } else if (curEntry.Size != size) { throw new ZipException("size was " + size + ", but I expected " + curEntry.Size); } if (curEntry.CompressedSize < 0) { curEntry.CompressedSize = csize; } else if (curEntry.CompressedSize != csize) { throw new ZipException("compressed size was " + csize + ", but I expected " + curEntry.CompressedSize); } if (curEntry.Crc < 0) { curEntry.Crc = crc.Value; } else if (curEntry.Crc != crc.Value) { throw new ZipException("crc was " + crc.Value + ", but I expected " + curEntry.Crc); } offset += csize; if (curEntry.IsCrypted) { if (curEntry.AESKeySize > 0) { curEntry.CompressedSize += curEntry.AESOverheadSize; } else { curEntry.CompressedSize += ZipConstants.CryptoHeaderSize; } } // Patch the header if possible if (patchEntryHeader) { patchEntryHeader = false; long curPos = baseOutputStream_.Position; baseOutputStream_.Seek(crcPatchPos, SeekOrigin.Begin); WriteLeInt((int)curEntry.Crc); if ( curEntry.LocalHeaderRequiresZip64 ) { if ( sizePatchPos == -1 ) { throw new ZipException("Entry requires zip64 but this has been turned off"); } baseOutputStream_.Seek(sizePatchPos, SeekOrigin.Begin); WriteLeLong(curEntry.Size); WriteLeLong(curEntry.CompressedSize); } else { WriteLeInt((int)curEntry.CompressedSize); WriteLeInt((int)curEntry.Size); } baseOutputStream_.Seek(curPos, SeekOrigin.Begin); } // Add data descriptor if flagged as required if ((curEntry.Flags & 8) != 0) { WriteLeInt(ZipConstants.DataDescriptorSignature); WriteLeInt(unchecked((int)curEntry.Crc)); if ( curEntry.LocalHeaderRequiresZip64 ) { WriteLeLong(curEntry.CompressedSize); WriteLeLong(curEntry.Size); offset += ZipConstants.Zip64DataDescriptorSize; } else { WriteLeInt((int)curEntry.CompressedSize); WriteLeInt((int)curEntry.Size); offset += ZipConstants.DataDescriptorSize; } } entries.Add(curEntry); curEntry = null; } void WriteEncryptionHeader(long crcValue) { offset += ZipConstants.CryptoHeaderSize; InitializePassword(Password); byte[] cryptBuffer = new byte[ZipConstants.CryptoHeaderSize]; Random rnd = new Random(); rnd.NextBytes(cryptBuffer); cryptBuffer[11] = (byte)(crcValue >> 24); EncryptBlock(cryptBuffer, 0, cryptBuffer.Length); baseOutputStream_.Write(cryptBuffer, 0, cryptBuffer.Length); } #if !NET_1_1 && !NETCF_2_0 private static void AddExtraDataAES(ZipEntry entry, ZipExtraData extraData) { // Vendor Version: AE-1 IS 1. AE-2 is 2. With AE-2 no CRC is required and 0 is stored. const int VENDOR_VERSION = 2; // Vendor ID is the two ASCII characters "AE". const int VENDOR_ID = 0x4541; //not 6965; extraData.StartNewEntry(); // Pack AES extra data field see http://www.winzip.com/aes_info.htm //extraData.AddLeShort(7); // Data size (currently 7) extraData.AddLeShort(VENDOR_VERSION); // 2 = AE-2 extraData.AddLeShort(VENDOR_ID); // "AE" extraData.AddData(entry.AESEncryptionStrength); // 1 = 128, 2 = 192, 3 = 256 extraData.AddLeShort((int)entry.CompressionMethod); // The actual compression method used to compress the file extraData.AddNewEntry(0x9901); } // Replaces WriteEncryptionHeader for AES // private void WriteAESHeader(ZipEntry entry) { byte[] salt; byte[] pwdVerifier; InitializeAESPassword(entry, Password, out salt, out pwdVerifier); // File format for AES: // Size (bytes) Content // ------------ ------- // Variable Salt value // 2 Password verification value // Variable Encrypted file data // 10 Authentication code // // Value in the "compressed size" fields of the local file header and the central directory entry // is the total size of all the items listed above. In other words, it is the total size of the // salt value, password verification value, encrypted data, and authentication code. baseOutputStream_.Write(salt, 0, salt.Length); baseOutputStream_.Write(pwdVerifier, 0, pwdVerifier.Length); } #endif /// <summary> /// Writes the given buffer to the current entry. /// </summary> /// <param name="buffer">The buffer containing data to write.</param> /// <param name="offset">The offset of the first byte to write.</param> /// <param name="count">The number of bytes to write.</param> /// <exception cref="ZipException">Archive size is invalid</exception> /// <exception cref="System.InvalidOperationException">No entry is active.</exception> public override void Write(byte[] buffer, int offset, int count) { if (curEntry == null) { throw new InvalidOperationException("No open entry."); } if ( buffer == null ) { throw new ArgumentNullException("buffer"); } if ( offset < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); #endif } if ( count < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "Cannot be negative"); #endif } if ( (buffer.Length - offset) < count ) { throw new ArgumentException("Invalid offset/count combination"); } crc.Update(buffer, offset, count); size += count; switch (curMethod) { case CompressionMethod.Deflated: base.Write(buffer, offset, count); break; case CompressionMethod.Stored: if (Password != null) { CopyAndEncrypt(buffer, offset, count); } else { baseOutputStream_.Write(buffer, offset, count); } break; } } void CopyAndEncrypt(byte[] buffer, int offset, int count) { const int CopyBufferSize = 4096; byte[] localBuffer = new byte[CopyBufferSize]; while ( count > 0 ) { int bufferCount = (count < CopyBufferSize) ? count : CopyBufferSize; Array.Copy(buffer, offset, localBuffer, 0, bufferCount); EncryptBlock(localBuffer, 0, bufferCount); baseOutputStream_.Write(localBuffer, 0, bufferCount); count -= bufferCount; offset += bufferCount; } } /// <summary> /// Finishes the stream. This will write the central directory at the /// end of the zip file and flush the stream. /// </summary> /// <remarks> /// This is automatically called when the stream is closed. /// </remarks> /// <exception cref="System.IO.IOException"> /// An I/O error occurs. /// </exception> /// <exception cref="ZipException"> /// Comment exceeds the maximum length<br/> /// Entry name exceeds the maximum length /// </exception> public override void Finish() { if (entries == null) { return; } if (curEntry != null) { CloseEntry(); } long numEntries = entries.Count; long sizeEntries = 0; foreach (ZipEntry entry in entries) { WriteLeInt(ZipConstants.CentralHeaderSignature); WriteLeShort(ZipConstants.VersionMadeBy); WriteLeShort(entry.Version); WriteLeShort(entry.Flags); WriteLeShort((short)entry.CompressionMethodForHeader); WriteLeInt((int)entry.DosTime); WriteLeInt((int)entry.Crc); if ( entry.IsZip64Forced() || (entry.CompressedSize >= uint.MaxValue) ) { WriteLeInt(-1); } else { WriteLeInt((int)entry.CompressedSize); } if ( entry.IsZip64Forced() || (entry.Size >= uint.MaxValue) ) { WriteLeInt(-1); } else { WriteLeInt((int)entry.Size); } byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name); if (name.Length > 0xffff) { throw new ZipException("Name too long."); } ZipExtraData ed = new ZipExtraData(entry.ExtraData); if ( entry.CentralHeaderRequiresZip64 ) { ed.StartNewEntry(); if ( entry.IsZip64Forced() || (entry.Size >= 0xffffffff) ) { ed.AddLeLong(entry.Size); } if ( entry.IsZip64Forced() || (entry.CompressedSize >= 0xffffffff) ) { ed.AddLeLong(entry.CompressedSize); } if ( entry.Offset >= 0xffffffff ) { ed.AddLeLong(entry.Offset); } ed.AddNewEntry(1); } else { ed.Delete(1); } #if !NET_1_1 && !NETCF_2_0 if (entry.AESKeySize > 0) { AddExtraDataAES(entry, ed); } #endif byte[] extra = ed.GetEntryData(); byte[] entryComment = (entry.Comment != null) ? ZipConstants.ConvertToArray(entry.Flags, entry.Comment) : new byte[0]; if (entryComment.Length > 0xffff) { throw new ZipException("Comment too long."); } WriteLeShort(name.Length); WriteLeShort(extra.Length); WriteLeShort(entryComment.Length); WriteLeShort(0); // disk number WriteLeShort(0); // internal file attributes // external file attributes if (entry.ExternalFileAttributes != -1) { WriteLeInt(entry.ExternalFileAttributes); } else { if (entry.IsDirectory) { // mark entry as directory (from nikolam.AT.perfectinfo.com) WriteLeInt(16); } else { WriteLeInt(0); } } if ( entry.Offset >= uint.MaxValue ) { WriteLeInt(-1); } else { WriteLeInt((int)entry.Offset); } if ( name.Length > 0 ) { baseOutputStream_.Write(name, 0, name.Length); } if ( extra.Length > 0 ) { baseOutputStream_.Write(extra, 0, extra.Length); } if ( entryComment.Length > 0 ) { baseOutputStream_.Write(entryComment, 0, entryComment.Length); } sizeEntries += ZipConstants.CentralHeaderBaseSize + name.Length + extra.Length + entryComment.Length; } using ( ZipHelperStream zhs = new ZipHelperStream(baseOutputStream_) ) { zhs.WriteEndOfCentralDirectory(numEntries, sizeEntries, offset, zipComment); } entries = null; } #region Instance Fields /// <summary> /// The entries for the archive. /// </summary> ArrayList entries = new ArrayList(); /// <summary> /// Used to track the crc of data added to entries. /// </summary> Crc32 crc = new Crc32(); /// <summary> /// The current entry being added. /// </summary> ZipEntry curEntry; int defaultCompressionLevel = Deflater.DEFAULT_COMPRESSION; CompressionMethod curMethod = CompressionMethod.Deflated; /// <summary> /// Used to track the size of data for an entry during writing. /// </summary> long size; /// <summary> /// Offset to be recorded for each entry in the central header. /// </summary> long offset; /// <summary> /// Comment for the entire archive recorded in central header. /// </summary> byte[] zipComment = new byte[0]; /// <summary> /// Flag indicating that header patching is required for the current entry. /// </summary> bool patchEntryHeader; /// <summary> /// Position to patch crc /// </summary> long crcPatchPos = -1; /// <summary> /// Position to patch size. /// </summary> long sizePatchPos = -1; // Default is dynamic which is not backwards compatible and can cause problems // with XP's built in compression which cant read Zip64 archives. // However it does avoid the situation were a large file is added and cannot be completed correctly. // NOTE: Setting the size for entries before they are added is the best solution! UseZip64 useZip64_ = UseZip64.Dynamic; #endregion } } #endif
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using System.Collections.Generic; using System.Data.Common; using System.Threading; using Common.Logging; using Quartz.Spi; namespace Quartz.Core { /// <summary> /// The thread responsible for performing the work of firing <see cref="ITrigger" /> /// s that are registered with the <see cref="QuartzScheduler" />. /// </summary> /// <seealso cref="QuartzScheduler" /> /// <seealso cref="IJob" /> /// <seealso cref="ITrigger" /> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> public class QuartzSchedulerThread : QuartzThread { private readonly ILog log; private QuartzScheduler qs; private QuartzSchedulerResources qsRsrcs; private readonly object sigLock = new object(); private bool signaled; private DateTimeOffset? signaledNextFireTimeUtc; private bool paused; private bool halted; private readonly Random random = new Random((int) DateTimeOffset.Now.Ticks); // When the scheduler finds there is no current trigger to fire, how long // it should wait until checking again... private static readonly TimeSpan DefaultIdleWaitTime = TimeSpan.FromSeconds(30); private TimeSpan idleWaitTime = DefaultIdleWaitTime; private int idleWaitVariableness = 7*1000; /// <summary> /// Gets the log. /// </summary> /// <value>The log.</value> protected ILog Log { get { return log; } } /// <summary> /// Sets the idle wait time. /// </summary> /// <value>The idle wait time.</value> [TimeSpanParseRule(TimeSpanParseRule.Milliseconds)] internal virtual TimeSpan IdleWaitTime { set { idleWaitTime = value; idleWaitVariableness = (int) (value.TotalMilliseconds*0.2); } } /// <summary> /// Gets the randomized idle wait time. /// </summary> /// <value>The randomized idle wait time.</value> private TimeSpan GetRandomizedIdleWaitTime() { return idleWaitTime - TimeSpan.FromMilliseconds(random.Next(idleWaitVariableness)); } /// <summary> /// Gets a value indicating whether this <see cref="QuartzSchedulerThread"/> is paused. /// </summary> /// <value><c>true</c> if paused; otherwise, <c>false</c>.</value> internal virtual bool Paused { get { return paused; } } /// <summary> /// Construct a new <see cref="QuartzSchedulerThread" /> for the given /// <see cref="QuartzScheduler" /> as a non-daemon <see cref="Thread" /> /// with normal priority. /// </summary> internal QuartzSchedulerThread(QuartzScheduler qs, QuartzSchedulerResources qsRsrcs) : this(qs, qsRsrcs, qsRsrcs.MakeSchedulerThreadDaemon, (int) ThreadPriority.Normal) { } /// <summary> /// Construct a new <see cref="QuartzSchedulerThread" /> for the given /// <see cref="QuartzScheduler" /> as a <see cref="Thread" /> with the given /// attributes. /// </summary> internal QuartzSchedulerThread(QuartzScheduler qs, QuartzSchedulerResources qsRsrcs, bool setDaemon, int threadPrio) : base(qsRsrcs.ThreadName) { log = LogManager.GetLogger(GetType()); //ThreadGroup generatedAux = qs.SchedulerThreadGroup; this.qs = qs; this.qsRsrcs = qsRsrcs; IsBackground = setDaemon; Priority = (ThreadPriority) threadPrio; // start the underlying thread, but put this object into the 'paused' // state // so processing doesn't start yet... paused = true; halted = false; } /// <summary> /// Signals the main processing loop to pause at the next possible point. /// </summary> internal virtual void TogglePause(bool pause) { lock (sigLock) { paused = pause; if (paused) { SignalSchedulingChange(SchedulerConstants.SchedulingSignalDateTime); } else { Monitor.PulseAll(sigLock); } } } /// <summary> /// Signals the main processing loop to pause at the next possible point. /// </summary> internal virtual void Halt(bool wait) { lock (sigLock) { halted = true; if (paused) { Monitor.PulseAll(sigLock); } else { SignalSchedulingChange(SchedulerConstants.SchedulingSignalDateTime); } } if (wait) { bool interrupted = false; try { while (true) { try { Join(); break; } catch (ThreadInterruptedException) { interrupted = true; } } } finally { if (interrupted) { Thread.CurrentThread.Interrupt(); } } } } /// <summary> /// Signals the main processing loop that a change in scheduling has been /// made - in order to interrupt any sleeping that may be occurring while /// waiting for the fire time to arrive. /// </summary> /// <param name="candidateNewNextFireTimeUtc"> /// the time when the newly scheduled trigger /// will fire. If this method is being called do to some other even (rather /// than scheduling a trigger), the caller should pass null. /// </param> public void SignalSchedulingChange(DateTimeOffset? candidateNewNextFireTimeUtc) { lock (sigLock) { signaled = true; signaledNextFireTimeUtc = candidateNewNextFireTimeUtc; Monitor.PulseAll(sigLock); } } public void ClearSignaledSchedulingChange() { lock (sigLock) { signaled = false; signaledNextFireTimeUtc = SchedulerConstants.SchedulingSignalDateTime; } } public bool IsScheduleChanged() { lock(sigLock) { return signaled; } } public DateTimeOffset? GetSignaledNextFireTimeUtc() { lock (sigLock) { return signaledNextFireTimeUtc; } } /// <summary> /// The main processing loop of the <see cref="QuartzSchedulerThread" />. /// </summary> public override void Run() { bool lastAcquireFailed = false; while (!halted) { try { // check if we're supposed to pause... lock (sigLock) { while (paused && !halted) { try { // wait until togglePause(false) is called... Monitor.Wait(sigLock, 1000); } catch (ThreadInterruptedException) { } } if (halted) { break; } } int availThreadCount = qsRsrcs.ThreadPool.BlockForAvailableThreads(); if (availThreadCount > 0) // will always be true, due to semantics of blockForAvailableThreads... { IList<IOperableTrigger> triggers = null; DateTimeOffset now = SystemTime.UtcNow(); ClearSignaledSchedulingChange(); try { triggers = qsRsrcs.JobStore.AcquireNextTriggers( now + idleWaitTime, Math.Min(availThreadCount, qsRsrcs.MaxBatchSize), qsRsrcs.BatchTimeWindow); lastAcquireFailed = false; if (log.IsDebugEnabled) { log.DebugFormat("Batch acquisition of {0} triggers", (triggers == null ? 0 : triggers.Count)); } } catch (JobPersistenceException jpe) { if (!lastAcquireFailed) { qs.NotifySchedulerListenersError("An error occurred while scanning for the next trigger to fire.", jpe); } lastAcquireFailed = true; continue; } catch (Exception e) { if (!lastAcquireFailed) { Log.Error("quartzSchedulerThreadLoop: RuntimeException " + e.Message, e); } lastAcquireFailed = true; continue; } if (triggers != null && triggers.Count > 0) { now = SystemTime.UtcNow(); DateTimeOffset triggerTime = triggers[0].GetNextFireTimeUtc().Value; TimeSpan timeUntilTrigger = triggerTime - now; while (timeUntilTrigger > TimeSpan.Zero) { if (ReleaseIfScheduleChangedSignificantly(triggers, triggerTime)) { break; } lock (sigLock) { if (halted) { break; } if (!IsCandidateNewTimeEarlierWithinReason(triggerTime, false)) { try { // we could have blocked a long while // on 'synchronize', so we must recompute now = SystemTime.UtcNow(); timeUntilTrigger = triggerTime - now; if (timeUntilTrigger > TimeSpan.Zero) { Monitor.Wait(sigLock, timeUntilTrigger); } } catch (ThreadInterruptedException) { } } } if (ReleaseIfScheduleChangedSignificantly(triggers, triggerTime)) { break; } now = SystemTime.UtcNow(); timeUntilTrigger = triggerTime - now; } // this happens if releaseIfScheduleChangedSignificantly decided to release triggers if (triggers.Count == 0) { continue; } // set triggers to 'executing' IList<TriggerFiredResult> bndles = new List<TriggerFiredResult>(); bool goAhead = true; lock (sigLock) { goAhead = !halted; } if (goAhead) { try { IList<TriggerFiredResult> res = qsRsrcs.JobStore.TriggersFired(triggers); if (res != null) { bndles = res; } } catch (SchedulerException se) { qs.NotifySchedulerListenersError("An error occurred while firing triggers '" + triggers + "'", se); // QTZ-179 : a problem occurred interacting with the triggers from the db // we release them and loop again foreach (IOperableTrigger t in triggers) { qsRsrcs.JobStore.ReleaseAcquiredTrigger(t); } continue; } } for (int i = 0; i < bndles.Count; i++) { TriggerFiredResult result = bndles[i]; TriggerFiredBundle bndle = result.TriggerFiredBundle; Exception exception = result.Exception; IOperableTrigger trigger = triggers[i]; // TODO SQL exception? if (exception != null && (exception is DbException || exception.InnerException is DbException)) { Log.Error("DbException while firing trigger " + trigger, exception); qsRsrcs.JobStore.ReleaseAcquiredTrigger(trigger); continue; } // it's possible to get 'null' if the triggers was paused, // blocked, or other similar occurrences that prevent it being // fired at this time... or if the scheduler was shutdown (halted) if (bndle == null) { qsRsrcs.JobStore.ReleaseAcquiredTrigger(trigger); continue; } // TODO: improvements: // // 2- make sure we can get a job runshell before firing trigger, or // don't let that throw an exception (right now it never does, // but the signature says it can). // 3- acquire more triggers at a time (based on num threads available?) JobRunShell shell = null; try { shell = qsRsrcs.JobRunShellFactory.CreateJobRunShell(bndle); shell.Initialize(qs); } catch (SchedulerException) { qsRsrcs.JobStore.TriggeredJobComplete(trigger, bndle.JobDetail, SchedulerInstruction.SetAllJobTriggersError); continue; } if (qsRsrcs.ThreadPool.RunInThread(shell) == false) { // this case should never happen, as it is indicative of the // scheduler being shutdown or a bug in the thread pool or // a thread pool being used concurrently - which the docs // say not to do... Log.Error("ThreadPool.runInThread() return false!"); qsRsrcs.JobStore.TriggeredJobComplete(trigger, bndle.JobDetail, SchedulerInstruction.SetAllJobTriggersError); } } continue; // while (!halted) } } else // if(availThreadCount > 0) { // should never happen, if threadPool.blockForAvailableThreads() follows contract continue; // while (!halted) } DateTimeOffset utcNow = SystemTime.UtcNow(); DateTimeOffset waitTime = utcNow.Add(GetRandomizedIdleWaitTime()); TimeSpan timeUntilContinue = waitTime - utcNow; lock (sigLock) { if (!halted) { try { // QTZ-336 A job might have been completed in the mean time and we might have // missed the scheduled changed signal by not waiting for the notify() yet // Check that before waiting for too long in case this very job needs to be // scheduled very soon if (!IsScheduleChanged()) { Monitor.Wait(sigLock, timeUntilContinue); } } catch (ThreadInterruptedException) { } } } } catch (Exception re) { if (Log != null) { Log.Error("Runtime error occurred in main trigger firing loop.", re); } } } // while (!halted) // drop references to scheduler stuff to aid garbage collection... qs = null; qsRsrcs = null; } private bool ReleaseIfScheduleChangedSignificantly(IList<IOperableTrigger> triggers, DateTimeOffset triggerTime) { if (IsCandidateNewTimeEarlierWithinReason(triggerTime, true)) { foreach (IOperableTrigger trigger in triggers) { // above call does a clearSignaledSchedulingChange() qsRsrcs.JobStore.ReleaseAcquiredTrigger(trigger); } triggers.Clear(); return true; } return false; } private bool IsCandidateNewTimeEarlierWithinReason(DateTimeOffset oldTimeUtc, bool clearSignal) { // So here's the deal: We know due to being signaled that 'the schedule' // has changed. We may know (if getSignaledNextFireTime() != DateTimeOffset.MinValue) the // new earliest fire time. We may not (in which case we will assume // that the new time is earlier than the trigger we have acquired). // In either case, we only want to abandon our acquired trigger and // go looking for a new one if "it's worth it". It's only worth it if // the time cost incurred to abandon the trigger and acquire a new one // is less than the time until the currently acquired trigger will fire, // otherwise we're just "thrashing" the job store (e.g. database). // // So the question becomes when is it "worth it"? This will depend on // the job store implementation (and of course the particular database // or whatever behind it). Ideally we would depend on the job store // implementation to tell us the amount of time in which it "thinks" // it can abandon the acquired trigger and acquire a new one. However // we have no current facility for having it tell us that, so we make // a somewhat educated but arbitrary guess ;-). lock (sigLock) { if (!IsScheduleChanged()) { return false; } bool earlier = false; if(!GetSignaledNextFireTimeUtc().HasValue) { earlier = true; } else if (GetSignaledNextFireTimeUtc().Value < oldTimeUtc) { earlier = true; } if(earlier) { // so the new time is considered earlier, but is it enough earlier? TimeSpan diff = oldTimeUtc - SystemTime.UtcNow(); if(diff < (qsRsrcs.JobStore.SupportsPersistence ? TimeSpan.FromMilliseconds(70) : TimeSpan.FromMilliseconds(7))) { earlier = false; } } if (clearSignal) { ClearSignaledSchedulingChange(); } return earlier; } } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; using System.Windows.Forms.VisualStyles; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2005DockPaneCaption : DockPaneCaptionBase { private sealed class InertButton : InertButtonBase { private Bitmap m_image, m_imageAutoHide; public InertButton(VS2005DockPaneCaption dockPaneCaption, Bitmap image, Bitmap imageAutoHide) : base() { m_dockPaneCaption = dockPaneCaption; m_image = image; m_imageAutoHide = imageAutoHide; RefreshChanges(); } private VS2005DockPaneCaption m_dockPaneCaption; private VS2005DockPaneCaption DockPaneCaption { get { return m_dockPaneCaption; } } public bool IsAutoHide { get { return DockPaneCaption.DockPane.IsAutoHide; } } public override Bitmap Image { get { return IsAutoHide ? m_imageAutoHide : m_image; } } protected override void OnRefreshChanges() { if (DockPaneCaption.DockPane.DockPanel != null) { if (DockPaneCaption.TextColor != ForeColor) { ForeColor = DockPaneCaption.TextColor; Invalidate(); } } } } #region consts private const int _TextGapTop = 2; private const int _TextGapBottom = 0; private const int _TextGapLeft = 3; private const int _TextGapRight = 3; private const int _ButtonGapTop = 2; private const int _ButtonGapBottom = 1; private const int _ButtonGapBetween = 1; private const int _ButtonGapLeft = 1; private const int _ButtonGapRight = 2; #endregion private static Bitmap _imageButtonClose; private static Bitmap ImageButtonClose { get { if (_imageButtonClose == null) _imageButtonClose = Resources.DockPane_Close; return _imageButtonClose; } } private InertButton m_buttonClose; private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(this, ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap _imageButtonAutoHide; private static Bitmap ImageButtonAutoHide { get { if (_imageButtonAutoHide == null) _imageButtonAutoHide = Resources.DockPane_AutoHide; return _imageButtonAutoHide; } } private static Bitmap _imageButtonDock; private static Bitmap ImageButtonDock { get { if (_imageButtonDock == null) _imageButtonDock = Resources.DockPane_Dock; return _imageButtonDock; } } private InertButton m_buttonAutoHide; private InertButton ButtonAutoHide { get { if (m_buttonAutoHide == null) { m_buttonAutoHide = new InertButton(this, ImageButtonDock, ImageButtonAutoHide); m_toolTip.SetToolTip(m_buttonAutoHide, ToolTipAutoHide); m_buttonAutoHide.Click += new EventHandler(AutoHide_Click); Controls.Add(m_buttonAutoHide); } return m_buttonAutoHide; } } private static Bitmap _imageButtonOptions; private static Bitmap ImageButtonOptions { get { if (_imageButtonOptions == null) _imageButtonOptions = Resources.DockPane_Option; return _imageButtonOptions; } } private InertButton m_buttonOptions; private InertButton ButtonOptions { get { if (m_buttonOptions == null) { m_buttonOptions = new InertButton(this, ImageButtonOptions, ImageButtonOptions); m_toolTip.SetToolTip(m_buttonOptions, ToolTipOptions); m_buttonOptions.Click += new EventHandler(Options_Click); Controls.Add(m_buttonOptions); } return m_buttonOptions; } } private IContainer m_components; private IContainer Components { get { return m_components; } } private ToolTip m_toolTip; public VS2005DockPaneCaption(DockPane pane) : base(pane) { SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) Components.Dispose(); base.Dispose(disposing); } private static int TextGapTop { get { return _TextGapTop; } } public Font TextFont { get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } } private static int TextGapBottom { get { return _TextGapBottom; } } private static int TextGapLeft { get { return _TextGapLeft; } } private static int TextGapRight { get { return _TextGapRight; } } private static int ButtonGapTop { get { return _ButtonGapTop; } } private static int ButtonGapBottom { get { return _ButtonGapBottom; } } private static int ButtonGapLeft { get { return _ButtonGapLeft; } } private static int ButtonGapRight { get { return _ButtonGapRight; } } private static int ButtonGapBetween { get { return _ButtonGapBetween; } } private static string _toolTipClose; private static string ToolTipClose { get { if (_toolTipClose == null) _toolTipClose = Strings.DockPaneCaption_ToolTipClose; return _toolTipClose; } } private static string _toolTipOptions; private static string ToolTipOptions { get { if (_toolTipOptions == null) _toolTipOptions = Strings.DockPaneCaption_ToolTipOptions; return _toolTipOptions; } } private static string _toolTipAutoHide; private static string ToolTipAutoHide { get { if (_toolTipAutoHide == null) _toolTipAutoHide = Strings.DockPaneCaption_ToolTipAutoHide; return _toolTipAutoHide; } } private static Blend _activeBackColorGradientBlend; private static Blend ActiveBackColorGradientBlend { get { if (_activeBackColorGradientBlend == null) { Blend blend = new Blend(2); blend.Factors = new float[]{0.5F, 1.0F}; blend.Positions = new float[]{0.0F, 1.0F}; _activeBackColorGradientBlend = blend; } return _activeBackColorGradientBlend; } } private Color TextColor { get { if (DockPane.IsActivated) return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor; else return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor; } } private static TextFormatFlags _textFormat = TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter; private TextFormatFlags TextFormat { get { if (RightToLeft == RightToLeft.No) return _textFormat; else return _textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; } } protected internal override int MeasureHeight() { int height = TextFont.Height + TextGapTop + TextGapBottom; if (height < ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom) height = ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom; return height; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint (e); DrawCaption(e.Graphics); } private void DrawCaption(Graphics g) { if (ClientRectangle.Width == 0 || ClientRectangle.Height == 0) return; if (DockPane.IsActivated) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, ClientRectangle); } } else { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) { g.FillRectangle(brush, ClientRectangle); } } Rectangle rectCaption = ClientRectangle; Rectangle rectCaptionText = rectCaption; rectCaptionText.X += TextGapLeft; rectCaptionText.Width -= TextGapLeft + TextGapRight; rectCaptionText.Width -= ButtonGapLeft + ButtonClose.Width + ButtonGapRight; if (ShouldShowAutoHideButton) rectCaptionText.Width -= ButtonAutoHide.Width + ButtonGapBetween; if (HasTabPageContextMenu) rectCaptionText.Width -= ButtonOptions.Width + ButtonGapBetween; rectCaptionText.Y += TextGapTop; rectCaptionText.Height -= TextGapTop + TextGapBottom; Color colorText; if (DockPane.IsActivated) colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor; else colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor; TextRenderer.DrawText(g, DockPane.CaptionText, TextFont, DrawHelper.RtlTransform(this, rectCaptionText), colorText, TextFormat); } protected override void OnLayout(LayoutEventArgs levent) { SetButtonsPosition(); base.OnLayout (levent); } protected override void OnRefreshChanges() { SetButtons(); Invalidate(); } private bool CloseButtonEnabled { get { return (DockPane.ActiveContent != null)? DockPane.ActiveContent.DockHandler.CloseButton : false; } } /// <summary> /// Determines whether the close button is visible on the content /// </summary> private bool CloseButtonVisible { get { return (DockPane.ActiveContent != null) ? DockPane.ActiveContent.DockHandler.CloseButtonVisible : false; } } private bool ShouldShowAutoHideButton { get { return !DockPane.IsFloat; } } private void SetButtons() { ButtonClose.Enabled = CloseButtonEnabled; ButtonClose.Visible = CloseButtonVisible; ButtonAutoHide.Visible = ShouldShowAutoHideButton; ButtonOptions.Visible = HasTabPageContextMenu; ButtonClose.RefreshChanges(); ButtonAutoHide.RefreshChanges(); ButtonOptions.RefreshChanges(); SetButtonsPosition(); } private void SetButtonsPosition() { // set the size and location for close and auto-hide buttons Rectangle rectCaption = ClientRectangle; int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectCaption.Height - ButtonGapTop - ButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectCaption.X + rectCaption.Width - 1 - ButtonGapRight - m_buttonClose.Width; int y = rectCaption.Y + ButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the auto hide button overtop. // Otherwise it is drawn to the left of the close button. if (CloseButtonVisible) point.Offset(-(buttonWidth + ButtonGapBetween), 0); ButtonAutoHide.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); if (ShouldShowAutoHideButton) point.Offset(-(buttonWidth + ButtonGapBetween), 0); ButtonOptions.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { if (DockPane.CanClose) DockPane.CloseActiveContent(); } private void AutoHide_Click(object sender, EventArgs e) { if (!DockPane.CanHide) return; DockPane.DockState = DockHelper.ToggleAutoHideState(DockPane.DockState); if (DockHelper.IsDockStateAutoHide(DockPane.DockState)) { DockPane.DockPanel.ActiveAutoHideContent = null; DockPane.NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(DockPane); } } private void Options_Click(object sender, EventArgs e) { ShowTabPageContextMenu(PointToClient(Control.MousePosition)); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// BillOfLadingCarrierInfoLine /// </summary> [DataContract] public partial class BillOfLadingCarrierInfoLine : IEquatable<BillOfLadingCarrierInfoLine> { /// <summary> /// Initializes a new instance of the <see cref="BillOfLadingCarrierInfoLine" /> class. /// </summary> [JsonConstructorAttribute] protected BillOfLadingCarrierInfoLine() { } /// <summary> /// Initializes a new instance of the <see cref="BillOfLadingCarrierInfoLine" /> class. /// </summary> /// <param name="SeqNo">SeqNo.</param> /// <param name="HuQuantity">HuQuantity.</param> /// <param name="HuType">HuType.</param> /// <param name="PackageQuantity">PackageQuantity.</param> /// <param name="PackageType">PackageType.</param> /// <param name="Weight">Weight.</param> /// <param name="IsHazardousMaterial">IsHazardousMaterial (default to false).</param> /// <param name="CommodityDescription">CommodityDescription (required).</param> /// <param name="NfmcNo">NfmcNo.</param> /// <param name="CarrierClass">CarrierClass.</param> public BillOfLadingCarrierInfoLine(int? SeqNo = null, int? HuQuantity = null, string HuType = null, int? PackageQuantity = null, string PackageType = null, int? Weight = null, bool? IsHazardousMaterial = null, string CommodityDescription = null, string NfmcNo = null, string CarrierClass = null) { // to ensure "CommodityDescription" is required (not null) if (CommodityDescription == null) { throw new InvalidDataException("CommodityDescription is a required property for BillOfLadingCarrierInfoLine and cannot be null"); } else { this.CommodityDescription = CommodityDescription; } this.SeqNo = SeqNo; this.HuQuantity = HuQuantity; this.HuType = HuType; this.PackageQuantity = PackageQuantity; this.PackageType = PackageType; this.Weight = Weight; // use default value if no "IsHazardousMaterial" provided if (IsHazardousMaterial == null) { this.IsHazardousMaterial = false; } else { this.IsHazardousMaterial = IsHazardousMaterial; } this.NfmcNo = NfmcNo; this.CarrierClass = CarrierClass; } /// <summary> /// Gets or Sets SeqNo /// </summary> [DataMember(Name="seqNo", EmitDefaultValue=false)] public int? SeqNo { get; set; } /// <summary> /// Gets or Sets HuQuantity /// </summary> [DataMember(Name="huQuantity", EmitDefaultValue=false)] public int? HuQuantity { get; set; } /// <summary> /// Gets or Sets HuType /// </summary> [DataMember(Name="huType", EmitDefaultValue=false)] public string HuType { get; set; } /// <summary> /// Gets or Sets PackageQuantity /// </summary> [DataMember(Name="packageQuantity", EmitDefaultValue=false)] public int? PackageQuantity { get; set; } /// <summary> /// Gets or Sets PackageType /// </summary> [DataMember(Name="packageType", EmitDefaultValue=false)] public string PackageType { get; set; } /// <summary> /// Gets or Sets Weight /// </summary> [DataMember(Name="weight", EmitDefaultValue=false)] public int? Weight { get; set; } /// <summary> /// Gets or Sets IsHazardousMaterial /// </summary> [DataMember(Name="isHazardousMaterial", EmitDefaultValue=false)] public bool? IsHazardousMaterial { get; set; } /// <summary> /// Gets or Sets CommodityDescription /// </summary> [DataMember(Name="commodityDescription", EmitDefaultValue=false)] public string CommodityDescription { get; set; } /// <summary> /// Gets or Sets NfmcNo /// </summary> [DataMember(Name="nfmcNo", EmitDefaultValue=false)] public string NfmcNo { get; set; } /// <summary> /// Gets or Sets CarrierClass /// </summary> [DataMember(Name="carrierClass", EmitDefaultValue=false)] public string CarrierClass { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class BillOfLadingCarrierInfoLine {\n"); sb.Append(" SeqNo: ").Append(SeqNo).Append("\n"); sb.Append(" HuQuantity: ").Append(HuQuantity).Append("\n"); sb.Append(" HuType: ").Append(HuType).Append("\n"); sb.Append(" PackageQuantity: ").Append(PackageQuantity).Append("\n"); sb.Append(" PackageType: ").Append(PackageType).Append("\n"); sb.Append(" Weight: ").Append(Weight).Append("\n"); sb.Append(" IsHazardousMaterial: ").Append(IsHazardousMaterial).Append("\n"); sb.Append(" CommodityDescription: ").Append(CommodityDescription).Append("\n"); sb.Append(" NfmcNo: ").Append(NfmcNo).Append("\n"); sb.Append(" CarrierClass: ").Append(CarrierClass).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as BillOfLadingCarrierInfoLine); } /// <summary> /// Returns true if BillOfLadingCarrierInfoLine instances are equal /// </summary> /// <param name="other">Instance of BillOfLadingCarrierInfoLine to be compared</param> /// <returns>Boolean</returns> public bool Equals(BillOfLadingCarrierInfoLine other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.SeqNo == other.SeqNo || this.SeqNo != null && this.SeqNo.Equals(other.SeqNo) ) && ( this.HuQuantity == other.HuQuantity || this.HuQuantity != null && this.HuQuantity.Equals(other.HuQuantity) ) && ( this.HuType == other.HuType || this.HuType != null && this.HuType.Equals(other.HuType) ) && ( this.PackageQuantity == other.PackageQuantity || this.PackageQuantity != null && this.PackageQuantity.Equals(other.PackageQuantity) ) && ( this.PackageType == other.PackageType || this.PackageType != null && this.PackageType.Equals(other.PackageType) ) && ( this.Weight == other.Weight || this.Weight != null && this.Weight.Equals(other.Weight) ) && ( this.IsHazardousMaterial == other.IsHazardousMaterial || this.IsHazardousMaterial != null && this.IsHazardousMaterial.Equals(other.IsHazardousMaterial) ) && ( this.CommodityDescription == other.CommodityDescription || this.CommodityDescription != null && this.CommodityDescription.Equals(other.CommodityDescription) ) && ( this.NfmcNo == other.NfmcNo || this.NfmcNo != null && this.NfmcNo.Equals(other.NfmcNo) ) && ( this.CarrierClass == other.CarrierClass || this.CarrierClass != null && this.CarrierClass.Equals(other.CarrierClass) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.SeqNo != null) hash = hash * 59 + this.SeqNo.GetHashCode(); if (this.HuQuantity != null) hash = hash * 59 + this.HuQuantity.GetHashCode(); if (this.HuType != null) hash = hash * 59 + this.HuType.GetHashCode(); if (this.PackageQuantity != null) hash = hash * 59 + this.PackageQuantity.GetHashCode(); if (this.PackageType != null) hash = hash * 59 + this.PackageType.GetHashCode(); if (this.Weight != null) hash = hash * 59 + this.Weight.GetHashCode(); if (this.IsHazardousMaterial != null) hash = hash * 59 + this.IsHazardousMaterial.GetHashCode(); if (this.CommodityDescription != null) hash = hash * 59 + this.CommodityDescription.GetHashCode(); if (this.NfmcNo != null) hash = hash * 59 + this.NfmcNo.GetHashCode(); if (this.CarrierClass != null) hash = hash * 59 + this.CarrierClass.GetHashCode(); return hash; } } } }
// 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.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using Xunit; namespace System.ComponentModel.Composition { public class ScopeExportFactoryTests { public interface IFooContract { } public interface IFooMetadata { string Name { get; } } public interface IBarContract { IFooContract CreateFoo(); } public interface IBlahContract { } [Export(typeof(IFooContract))] [ExportMetadata("Name", "Foo")] public class FooImpl : IFooContract { } [Export(typeof(IFooContract))] [ExportMetadata("Name", "Foo")] public class Foo2Impl : IFooContract { } [Export(typeof(IFooContract))] public class Foo3Impl : IFooContract { [Import] public IBlahContract Blah { get; set; } } [Export(typeof(IFooContract))] public class Foo4Impl : IFooContract { [Import] public ExportFactory<IFooContract> Blah { get; set; } } [Export(typeof(IBlahContract))] public class BlahImpl : IBlahContract { [Import] public IBlahContract Blah { get; set; } } [Export(typeof(IBarContract))] public class BarImpl : IBarContract { [Import] public ExportFactory<IFooContract> FooFactory { get; set; } public IFooContract CreateFoo() { var efv = this.FooFactory.CreateExport(); var value = efv.Value; efv.Dispose(); return value; } } [Export(typeof(IBarContract))] public class BarWithMany : IBarContract { [ImportMany] public ExportFactory<IFooContract>[] FooFactories { get; set; } public IFooContract CreateFoo() { var efv = this.FooFactories[0].CreateExport(); var value = efv.Value; efv.Dispose(); return value; } } [Export(typeof(IBarContract))] public class BarImplWithMetadata : IBarContract { [Import] public ExportFactory<IFooContract, IFooMetadata> FooFactory { get; set; } public IFooContract CreateFoo() { Assert.Equal("Foo", this.FooFactory.Metadata.Name); var efv = this.FooFactory.CreateExport(); var value = efv.Value; efv.Dispose(); return value; } } [Fact] public void SimpleChain() { var parentCatalog = new TypeCatalog(typeof(BarImpl)); var childCatalog = new TypeCatalog(typeof(FooImpl)); var scope = parentCatalog.AsScope(childCatalog.AsScope()); var container = new CompositionContainer(scope); var bar = container.GetExportedValue<IBarContract>(); Assert.NotNull(bar); var foo1 = bar.CreateFoo(); Assert.NotNull(foo1); Assert.True(foo1 is FooImpl); var foo2 = bar.CreateFoo(); Assert.NotNull(foo1); Assert.True(foo2 is FooImpl); Assert.NotEqual(foo1, foo2); } [Fact] public void SimpleChainWithTwoChildren() { var parentCatalog = new TypeCatalog(typeof(BarWithMany)); var childCatalog1 = new TypeCatalog(typeof(FooImpl)); var childCatalog2 = new TypeCatalog(typeof(Foo2Impl)); var scope = parentCatalog.AsScope(childCatalog1.AsScope(), childCatalog2.AsScope()); var container = new CompositionContainer(scope); var bar = container.GetExportedValue<IBarContract>() as BarWithMany; Assert.NotNull(bar); Assert.Equal(2, bar.FooFactories.Length); IFooContract foo1 = null; using (var efFoo1 = bar.FooFactories[0].CreateExport()) { foo1 = efFoo1.Value; } IFooContract foo2 = null; using (var efFoo2 = bar.FooFactories[1].CreateExport()) { foo2 = efFoo2.Value; } Assert.True(((foo1 is FooImpl) && (foo2 is Foo2Impl)) || ((foo2 is FooImpl) && (foo1 is Foo2Impl))); } [Fact] public void SimpleChainWithMetadata() { var parentCatalog = new TypeCatalog(typeof(BarImplWithMetadata)); var childCatalog = new TypeCatalog(typeof(FooImpl)); var scope = parentCatalog.AsScope(childCatalog.AsScope()); var container = new CompositionContainer(scope); var bar = container.GetExportedValue<IBarContract>(); Assert.NotNull(bar); var foo1 = bar.CreateFoo(); Assert.NotNull(foo1); Assert.True(foo1 is FooImpl); var foo2 = bar.CreateFoo(); Assert.NotNull(foo1); Assert.True(foo2 is FooImpl); Assert.NotEqual(foo1, foo2); } [Fact] public void SimpleChainWithLowerLoop() { var parentCatalog = new TypeCatalog(typeof(BarImpl)); var childCatalog = new TypeCatalog(typeof(Foo3Impl), typeof(BlahImpl)); var scope = parentCatalog.AsScope(childCatalog.AsScope()); var container = new CompositionContainer(scope); var bar = container.GetExportedValue<IBarContract>(); Assert.NotNull(bar); var foo1 = bar.CreateFoo(); Assert.NotNull(foo1); Assert.True(foo1 is Foo3Impl); var foo2 = bar.CreateFoo(); Assert.NotNull(foo1); Assert.True(foo2 is Foo3Impl); Assert.NotEqual(foo1, foo2); } [Fact] public void SimpleChainWithCrossLoop() { var parentCatalog = new TypeCatalog(typeof(BarImpl)); var childCatalog = new TypeCatalog(typeof(Foo4Impl)); var scope = parentCatalog.AsScope(childCatalog.AsScope()); var container = new CompositionContainer(scope); var bar = container.GetExportedValue<IBarContract>(); Assert.NotNull(bar); var foo1 = bar.CreateFoo(); Assert.NotNull(foo1); Assert.True(foo1 is Foo4Impl); var foo2 = bar.CreateFoo(); Assert.NotNull(foo1); Assert.True(foo2 is Foo4Impl); Assert.NotEqual(foo1, foo2); } [Fact] public void SimpleChainWithLowerLoopRejection() { var parentCatalog = new TypeCatalog(typeof(BarImpl)); var childCatalog = new TypeCatalog(typeof(Foo3Impl)); var scope = parentCatalog.AsScope(childCatalog.AsScope()); var container = new CompositionContainer(scope); var bar = container.GetExportedValueOrDefault<IBarContract>(); Assert.Null(bar); } [Fact] public void ExportFactoryCausesRejectionBasedOnContract() { var parentCatalog = new TypeCatalog(typeof(BarImpl)); var childCatalog = new TypeCatalog(typeof(BarImpl)); var scope = parentCatalog.AsScope(childCatalog.AsScope()); var container = new CompositionContainer(scope); var bar = container.GetExportedValueOrDefault<IBarContract>(); Assert.Null(bar); } [Fact] public void ExportFactoryCausesRejectionBasedOnCardinality() { var parentCatalog = new TypeCatalog(typeof(BarImpl)); var childCatalog = new TypeCatalog(typeof(FooImpl), typeof(Foo2Impl)); var scope = parentCatalog.AsScope(childCatalog.AsScope()); var container = new CompositionContainer(scope); var bar = container.GetExportedValueOrDefault<IBarContract>(); Assert.Null(bar); } } public class ScopeExportFactoryWithPublicSurface { [Export] public class ClassA { } [Export] public class ClassB { } [Export] public class ClassC { } [Export] public class ClassRoot { [ImportAttribute] public ExportFactory<ClassA> classA; [ImportAttribute] public ExportFactory<ClassB> classB; [ImportAttribute] public ExportFactory<ClassB> classC; } [Fact] public void FilteredScopeFactoryOfTM_ShouldSucceed() { var c1 = new TypeCatalog(typeof(ClassRoot), typeof(ClassA)); var c2 = new TypeCatalog(typeof(ClassA), typeof(ClassB), typeof(ClassC)); var c3 = new TypeCatalog(typeof(ClassA), typeof(ClassB), typeof(ClassC)); var c4 = new TypeCatalog(typeof(ClassA), typeof(ClassB), typeof(ClassC)); var sd = c1.AsScope(c2.AsScopeWithPublicSurface<ClassA>(), c3.AsScopeWithPublicSurface<ClassB>(), c4.AsScopeWithPublicSurface<ClassC>()); var container = new CompositionContainer(sd); var fromRoot = container.GetExportedValue<ClassRoot>(); var a = fromRoot.classA.CreateExport().Value; var b = fromRoot.classB.CreateExport().Value; var c = fromRoot.classC.CreateExport().Value; } } public class ScopeFactoryAutoResolveFromAncestorScope { [Export] public class Root { } [Export] public class Child { } [Export] public class ClassRoot { [ImportAttribute] public ExportFactory<ClassA> classA; [ImportAttribute] public ClassA localClassA; } [Export] public class ClassA { [Import] public ICompositionService CompositionService; [ImportAttribute] public Root classRoot; public int InstanceValue; } public class ImportA { [Import] public ClassA classA; } [Fact] public void ScopeFactoryAutoResolveFromAncestorScopeShouldSucceed() { var c1 = new TypeCatalog(typeof(ClassRoot), typeof(ClassA), typeof(Root)); var c2 = new TypeCatalog(typeof(ClassRoot), typeof(ClassA), typeof(Child)); var sd = c1.AsScope(c2.AsScope()); var container = new CompositionContainer(sd, CompositionOptions.ExportCompositionService); var fromRoot = container.GetExportedValue<ClassRoot>(); var a1 = fromRoot.classA.CreateExport().Value; var a2 = fromRoot.classA.CreateExport().Value; fromRoot.localClassA.InstanceValue = 101; a1.InstanceValue = 202; a2.InstanceValue = 303; Assert.NotEqual(a1.InstanceValue, a2.InstanceValue); Assert.NotNull(fromRoot.localClassA.classRoot); Assert.NotNull(a1.classRoot); Assert.NotNull(a2.classRoot); } } public class DeeplyNestedCatalog { [Export] public class ClassRoot { [ImportAttribute] public ExportFactory<ClassA> classA; } [Export] public class ClassA { [ImportAttribute] public ExportFactory<ClassB> classB; } [Export] public class ClassB { [ImportAttribute] public ExportFactory<ClassC> classC; public int InstanceValue; } [Export] public class ClassC { [ImportAttribute] public ExportFactory<ClassD> classD; } [Export] public class ClassD { } [Fact] public void DeeplyNestedCatalogPartitionedCatalog_ShouldWork() { var cat1 = new TypeCatalog(typeof(ClassRoot)); var cat2 = new TypeCatalog(typeof(ClassA)); var cat3 = new TypeCatalog(typeof(ClassB)); var cat4 = new TypeCatalog(typeof(ClassC)); var cat5 = new TypeCatalog(typeof(ClassD)); var sd = cat1.AsScope(cat2.AsScope(cat3.AsScope(cat4.AsScope(cat5.AsScope())))); var container = new CompositionContainer(sd); var fromRoot = container.GetExportedValue<ClassRoot>(); var a1 = fromRoot.classA.CreateExport().Value; var b1 = a1.classB.CreateExport().Value; var c1 = b1.classC.CreateExport().Value; var d1 = c1.classD.CreateExport().Value; } [Fact] public void DeeplyNestedCatalogOverlappedCatalog_ShouldWork() { var cat1 = new TypeCatalog(typeof(ClassRoot), typeof(ClassA), typeof(ClassB), typeof(ClassC), typeof(ClassD)); var cat2 = cat1; var cat3 = cat1; var cat4 = cat1; var cat5 = cat1; var sd = cat1.AsScope(cat2.AsScope(cat3.AsScope(cat4.AsScope(cat5.AsScope())))); var container = new CompositionContainer(sd); var fromRoot = container.GetExportedValue<ClassRoot>(); var a1 = fromRoot.classA.CreateExport().Value; var b1 = a1.classB.CreateExport().Value; var c1 = b1.classC.CreateExport().Value; var d1 = c1.classD.CreateExport().Value; } } public class LocalSharedNonLocalInSameContainer { [Export] public class ClassRoot { [ImportAttribute] public ExportFactory<ClassA> classA; [ImportAttribute] public ClassXXXX xxxx; } [Export] public class ClassA { [ImportAttribute] public ExportFactory<ClassB> classB; [ImportAttribute] public ClassXXXX xxxx; } [Export] public class ClassB { [ImportAttribute] public ExportFactory<ClassC> classC; [ImportAttribute] public ClassXXXX xxxx; } [Export] public class ClassC { [ImportAttribute(Source = ImportSource.NonLocal)] public ClassXXXX xxxx; [Import] public ClassD classD; } [Export] public class ClassD { [ImportAttribute] public ClassXXXX xxxx; } [Export] public class ClassXXXX { public int InstanceValue; } [Fact] public void LocalSharedNonLocalInSameContainer_ShouldSucceed() { var cat1 = new TypeCatalog(typeof(ClassRoot), typeof(ClassXXXX)); var cat2 = new TypeCatalog(typeof(ClassA)); var cat3 = new TypeCatalog(typeof(ClassB)); var cat4 = new TypeCatalog(typeof(ClassC), typeof(ClassD), typeof(ClassXXXX)); var sd = cat1.AsScope(cat2.AsScope(cat3.AsScope(cat4.AsScope()))); var container = new CompositionContainer(sd); var fromRoot = container.GetExportedValue<ClassRoot>(); var a1 = fromRoot.classA.CreateExport().Value; fromRoot.xxxx.InstanceValue = 16; var b1 = a1.classB.CreateExport().Value; var c1 = b1.classC.CreateExport().Value; Assert.Equal(16, fromRoot.xxxx.InstanceValue); Assert.Equal(16, a1.xxxx.InstanceValue); Assert.Equal(16, b1.xxxx.InstanceValue); Assert.Equal(16, c1.xxxx.InstanceValue); Assert.Equal(0, c1.classD.xxxx.InstanceValue); c1.xxxx.InstanceValue = 8; Assert.Equal(8, fromRoot.xxxx.InstanceValue); Assert.Equal(8, a1.xxxx.InstanceValue); Assert.Equal(8, b1.xxxx.InstanceValue); Assert.Equal(8, c1.xxxx.InstanceValue); Assert.Equal(0, c1.classD.xxxx.InstanceValue); c1.classD.xxxx.InstanceValue = 2; Assert.Equal(8, fromRoot.xxxx.InstanceValue); Assert.Equal(8, a1.xxxx.InstanceValue); Assert.Equal(8, b1.xxxx.InstanceValue); Assert.Equal(8, c1.xxxx.InstanceValue); Assert.Equal(2, c1.classD.xxxx.InstanceValue); } } public class ScopeBridgingAdaptersConstructorInjection { [Export] public class ClassRoot { [ImportAttribute] public ExportFactory<ClassC> classC; [ImportAttribute] public ClassXXXX xxxx; } [Export] public class ClassC { [ImportingConstructor] public ClassC([ImportAttribute(RequiredCreationPolicy = CreationPolicy.NonShared, Source = ImportSource.NonLocal)]ClassXXXX xxxx) { this.xxxx = xxxx; } [Export] public ClassXXXX xxxx; [Import] public ClassD classD; } [Export] public class ClassD { [Import] public ClassXXXX xxxx; } [Export] public class ClassXXXX { public int InstanceValue; } [Fact] public void ScopeBridgingAdapters_ShouldSucceed() { var cat1 = new TypeCatalog(typeof(ClassRoot), typeof(ClassXXXX)); var cat2 = new TypeCatalog(typeof(ClassC), typeof(ClassD)); var sd = cat1.AsScope(cat2.AsScope()); var container = new CompositionContainer(sd); var fromRoot = container.GetExportedValue<ClassRoot>(); var c1 = fromRoot.classC.CreateExport().Value; var c2 = fromRoot.classC.CreateExport().Value; var c3 = fromRoot.classC.CreateExport().Value; var c4 = fromRoot.classC.CreateExport().Value; var c5 = fromRoot.classC.CreateExport().Value; Assert.Equal(0, fromRoot.xxxx.InstanceValue); Assert.Equal(0, c1.xxxx.InstanceValue); Assert.Equal(0, c1.classD.xxxx.InstanceValue); Assert.Equal(0, c2.xxxx.InstanceValue); Assert.Equal(0, c2.classD.xxxx.InstanceValue); Assert.Equal(0, c3.xxxx.InstanceValue); Assert.Equal(0, c3.classD.xxxx.InstanceValue); Assert.Equal(0, c4.xxxx.InstanceValue); Assert.Equal(0, c4.classD.xxxx.InstanceValue); Assert.Equal(0, c5.xxxx.InstanceValue); Assert.Equal(0, c5.classD.xxxx.InstanceValue); c1.xxxx.InstanceValue = 1; c2.xxxx.InstanceValue = 2; c3.xxxx.InstanceValue = 3; c4.xxxx.InstanceValue = 4; c5.xxxx.InstanceValue = 5; Assert.Equal(0, fromRoot.xxxx.InstanceValue); Assert.Equal(1, c1.xxxx.InstanceValue); Assert.Equal(1, c1.classD.xxxx.InstanceValue); Assert.Equal(2, c2.xxxx.InstanceValue); Assert.Equal(2, c2.classD.xxxx.InstanceValue); Assert.Equal(3, c3.xxxx.InstanceValue); Assert.Equal(3, c3.classD.xxxx.InstanceValue); Assert.Equal(4, c4.xxxx.InstanceValue); Assert.Equal(4, c4.classD.xxxx.InstanceValue); Assert.Equal(5, c5.xxxx.InstanceValue); Assert.Equal(5, c5.classD.xxxx.InstanceValue); } } public class ScopeBridgingAdaptersImportExportProperty { [Export] public class ClassRoot { [ImportAttribute] public ExportFactory<ClassC> classC; [ImportAttribute] public ClassXXXX xxxx; } [Export] public class ClassC { [Export] [ImportAttribute(RequiredCreationPolicy = CreationPolicy.NonShared, Source = ImportSource.NonLocal)] public ClassXXXX xxxx; [Import] public ClassD classD; } [Export] public class ClassD { [Import] public ClassXXXX xxxx; } [Export] public class ClassXXXX { public int InstanceValue; } [Fact] public void ScopeBridgingAdaptersImportExportProperty_ShouldSucceed() { var cat1 = new TypeCatalog(typeof(ClassRoot), typeof(ClassXXXX)); var cat2 = new TypeCatalog(typeof(ClassC), typeof(ClassD)); var sd = cat1.AsScope(cat2.AsScope()); var container = new CompositionContainer(sd); var fromRoot = container.GetExportedValue<ClassRoot>(); var c1 = fromRoot.classC.CreateExport().Value; var c2 = fromRoot.classC.CreateExport().Value; var c3 = fromRoot.classC.CreateExport().Value; var c4 = fromRoot.classC.CreateExport().Value; var c5 = fromRoot.classC.CreateExport().Value; Assert.Equal(0, fromRoot.xxxx.InstanceValue); Assert.Equal(0, c1.xxxx.InstanceValue); Assert.Equal(0, c1.classD.xxxx.InstanceValue); Assert.Equal(0, c2.xxxx.InstanceValue); Assert.Equal(0, c2.classD.xxxx.InstanceValue); Assert.Equal(0, c3.xxxx.InstanceValue); Assert.Equal(0, c3.classD.xxxx.InstanceValue); Assert.Equal(0, c4.xxxx.InstanceValue); Assert.Equal(0, c4.classD.xxxx.InstanceValue); Assert.Equal(0, c5.xxxx.InstanceValue); Assert.Equal(0, c5.classD.xxxx.InstanceValue); c1.xxxx.InstanceValue = 1; c2.xxxx.InstanceValue = 2; c3.xxxx.InstanceValue = 3; c4.xxxx.InstanceValue = 4; c5.xxxx.InstanceValue = 5; Assert.Equal(0, fromRoot.xxxx.InstanceValue); Assert.Equal(1, c1.xxxx.InstanceValue); Assert.Equal(1, c1.classD.xxxx.InstanceValue); Assert.Equal(2, c2.xxxx.InstanceValue); Assert.Equal(2, c2.classD.xxxx.InstanceValue); Assert.Equal(3, c3.xxxx.InstanceValue); Assert.Equal(3, c3.classD.xxxx.InstanceValue); Assert.Equal(4, c4.xxxx.InstanceValue); Assert.Equal(4, c4.classD.xxxx.InstanceValue); Assert.Equal(5, c5.xxxx.InstanceValue); Assert.Equal(5, c5.classD.xxxx.InstanceValue); } } public class SelfExportFromExportFactory { [Export] public class ClassRoot { [ImportAttribute] public ExportFactory<ClassA> classA; } [Export] public class ClassA { [ImportAttribute] public ClassB classB; [ImportAttribute] public ClassC classC; [ImportAttribute] public ClassD classD; public int InstanceValue; } [Export] public class ClassB { [ImportAttribute] public ClassA classA; } [Export] public class ClassC { [ImportAttribute] public ClassA classA; } [Export] public class ClassD { [ImportAttribute] public ClassA classA; } [Fact] public void SelfExportFromExportFactory_ShouldSucceed() { var cat1 = new TypeCatalog(typeof(ClassRoot)); var cat2 = new TypeCatalog(typeof(ClassA), typeof(ClassB), typeof(ClassC), typeof(ClassD)); var sd = cat1.AsScope(cat2.AsScope()); var container = new CompositionContainer(sd); var fromRoot = container.GetExportedValue<ClassRoot>(); var a1 = fromRoot.classA.CreateExport().Value; a1.InstanceValue = 8; Assert.Equal(8, a1.classB.classA.InstanceValue); Assert.Equal(8, a1.classC.classA.InstanceValue); Assert.Equal(8, a1.classD.classA.InstanceValue); } } }
// 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.Text; /// <summary> /// GetByteCount(System.Char[],System.Int32,System.Int32) [v-jianq] /// </summary> public class UTF8EncodingGetByteCount1 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; // // TODO: Add your negative test cases here // // TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method GetByteCount(Char[],Int32,Int32) with non-null char[]"); try { Char[] chars = new Char[] { '\u0023', '\u0025', '\u03a0', '\u03a3' }; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, 1, 2); } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method GetByteCount(Char[],Int32,Int32) with null char[]"); try { Char[] chars = new Char[] { }; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, 0, 0); if (byteCount != 0) { TestLibrary.TestFramework.LogError("001.1", "Method GetByteCount Err."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown when chars is a null reference"); try { Char[] chars = null; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, 0, 0); TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown when chars is a null reference."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException is not thrown when index is less than zero."); try { Char[] chars = new Char[] { '\u0023', '\u0025', '\u03a0', '\u03a3' }; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, -1, 2); TestLibrary.TestFramework.LogError("102.1", "ArgumentOutOfRangeException is not thrown when index is less than zero."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException is not thrown when count is less than zero."); try { Char[] chars = new Char[] { '\u0023', '\u0025', '\u03a0', '\u03a3' }; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, 1, -2); TestLibrary.TestFramework.LogError("103.1", "ArgumentOutOfRangeException is not thrown when count is less than zero."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentOutOfRangeException is not thrown when index and count do not denote a valid range in chars."); try { Char[] chars = new Char[] { '\u0023', '\u0025', '\u03a0', '\u03a3' }; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, 1, chars.Length); TestLibrary.TestFramework.LogError("104.1", "ArgumentOutOfRangeException is not thrown when index and count do not denote a valid range in chars."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { UTF8EncodingGetByteCount1 test = new UTF8EncodingGetByteCount1(); TestLibrary.TestFramework.BeginTestCase("UTF8EncodingGetByteCount1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Lucene.Net.Util { /* * 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. */ /// <summary> /// A simple append only random-access <see cref="BytesRef"/> array that stores full /// copies of the appended bytes in a <see cref="ByteBlockPool"/>. /// <para/> /// <b>Note: this class is not Thread-Safe!</b> /// <para/> /// @lucene.internal /// @lucene.experimental /// </summary> public sealed class BytesRefArray { private readonly ByteBlockPool pool; private int[] offsets = new int[1]; private int lastElement = 0; private int currentOffset = 0; private readonly Counter bytesUsed; /// <summary> /// Creates a new <see cref="BytesRefArray"/> with a counter to track allocated bytes /// </summary> public BytesRefArray(Counter bytesUsed) { this.pool = new ByteBlockPool(new ByteBlockPool.DirectTrackingAllocator(bytesUsed)); pool.NextBuffer(); bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + RamUsageEstimator.NUM_BYTES_INT32); this.bytesUsed = bytesUsed; } /// <summary> /// Clears this <see cref="BytesRefArray"/> /// </summary> public void Clear() { lastElement = 0; currentOffset = 0; Array.Clear(offsets, 0, offsets.Length); pool.Reset(false, true); // no need to 0 fill the buffers we control the allocator } /// <summary> /// Appends a copy of the given <see cref="BytesRef"/> to this <see cref="BytesRefArray"/>. </summary> /// <param name="bytes"> The bytes to append </param> /// <returns> The index of the appended bytes </returns> public int Append(BytesRef bytes) { if (lastElement >= offsets.Length) { int oldLen = offsets.Length; offsets = ArrayUtil.Grow(offsets, offsets.Length + 1); bytesUsed.AddAndGet((offsets.Length - oldLen) * RamUsageEstimator.NUM_BYTES_INT32); } pool.Append(bytes); offsets[lastElement++] = currentOffset; currentOffset += bytes.Length; return lastElement - 1; } /// <summary> /// Returns the current size of this <see cref="BytesRefArray"/>. /// <para/> /// NOTE: This was size() in Lucene. /// </summary> /// <returns> The current size of this <see cref="BytesRefArray"/> </returns> public int Length => lastElement; /// <summary> /// Returns the <i>n'th</i> element of this <see cref="BytesRefArray"/> </summary> /// <param name="spare"> A spare <see cref="BytesRef"/> instance </param> /// <param name="index"> The elements index to retrieve </param> /// <returns> The <i>n'th</i> element of this <see cref="BytesRefArray"/> </returns> public BytesRef Get(BytesRef spare, int index) { if (lastElement > index) { int offset = offsets[index]; int length = index == lastElement - 1 ? currentOffset - offset : offsets[index + 1] - offset; if (Debugging.AssertsEnabled) Debugging.Assert(spare.Offset == 0); spare.Grow(length); spare.Length = length; pool.ReadBytes(offset, spare.Bytes, spare.Offset, spare.Length); return spare; } throw new IndexOutOfRangeException("index " + index + " must be less than the size: " + lastElement); } private int[] Sort(IComparer<BytesRef> comp) { int[] orderedEntries = new int[Length]; for (int i = 0; i < orderedEntries.Length; i++) { orderedEntries[i] = i; } new IntroSorterAnonymousClass(this, comp, orderedEntries).Sort(0, Length); return orderedEntries; } private class IntroSorterAnonymousClass : IntroSorter { private readonly BytesRefArray outerInstance; private readonly IComparer<BytesRef> comp; private readonly int[] orderedEntries; public IntroSorterAnonymousClass(BytesRefArray outerInstance, IComparer<BytesRef> comp, int[] orderedEntries) { this.outerInstance = outerInstance; this.comp = comp; this.orderedEntries = orderedEntries; pivot = new BytesRef(); scratch1 = new BytesRef(); scratch2 = new BytesRef(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override void Swap(int i, int j) { int o = orderedEntries[i]; orderedEntries[i] = orderedEntries[j]; orderedEntries[j] = o; } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override int Compare(int i, int j) { int idx1 = orderedEntries[i], idx2 = orderedEntries[j]; return comp.Compare(outerInstance.Get(scratch1, idx1), outerInstance.Get(scratch2, idx2)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override void SetPivot(int i) { int index = orderedEntries[i]; outerInstance.Get(pivot, index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override int ComparePivot(int j) { int index = orderedEntries[j]; return comp.Compare(pivot, outerInstance.Get(scratch2, index)); } private readonly BytesRef pivot; private readonly BytesRef scratch1; private readonly BytesRef scratch2; } /// <summary> /// Sugar for <see cref="GetIterator(IComparer{BytesRef})"/> with a <c>null</c> comparer /// </summary> [Obsolete("Use GetEnumerator() instead. This method will be removed in 4.8.0 release candidate."), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public IBytesRefIterator GetIterator() { return GetIterator(null); } /// <summary> /// <para> /// Returns a <see cref="IBytesRefIterator"/> with point in time semantics. The /// iterator provides access to all so far appended <see cref="BytesRef"/> instances. /// </para> /// <para> /// If a non <c>null</c> <see cref="T:IComparer{BytesRef}"/> is provided the iterator will /// iterate the byte values in the order specified by the comparer. Otherwise /// the order is the same as the values were appended. /// </para> /// <para> /// This is a non-destructive operation. /// </para> /// </summary> [Obsolete("Use GetEnumerator(IComparer<BytesRef>) instead. This method will be removed in 4.8.0 release candidate"), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public IBytesRefIterator GetIterator(IComparer<BytesRef> comp) { BytesRef spare = new BytesRef(); int size = Length; int[] indices = comp == null ? null : Sort(comp); return new BytesRefIteratorAnonymousClass(this, comp, spare, size, indices); } [Obsolete("This class will be removed in 4.8.0 release candidate"), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] private class BytesRefIteratorAnonymousClass : IBytesRefIterator { private readonly BytesRefArray outerInstance; private readonly IComparer<BytesRef> comp; private readonly BytesRef spare; private readonly int size; private readonly int[] indices; public BytesRefIteratorAnonymousClass(BytesRefArray outerInstance, IComparer<BytesRef> comp, BytesRef spare, int size, int[] indices) { this.outerInstance = outerInstance; this.comp = comp; this.spare = spare; this.size = size; this.indices = indices; pos = 0; } internal int pos; public virtual BytesRef Next() { if (pos < size) { return outerInstance.Get(spare, indices == null ? pos++ : indices[pos++]); } return null; } public virtual IComparer<BytesRef> Comparer => comp; } /// <summary> /// Sugar for <see cref="GetEnumerator(IComparer{BytesRef})"/> with a <c>null</c> comparer. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public IBytesRefEnumerator GetEnumerator() => GetEnumerator(null); /// <summary> /// <para> /// Returns a <see cref="IBytesRefEnumerator"/> with point in time semantics. The /// enumerator provides access to all so far appended <see cref="BytesRef"/> instances. /// </para> /// <para> /// If a non <c>null</c> <see cref="T:IComparer{BytesRef}"/> is provided the enumerator will /// iterate the byte values in the order specified by the comparer. Otherwise /// the order is the same as the values were appended. /// </para> /// <para> /// This is a non-destructive operation. /// </para> /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public IBytesRefEnumerator GetEnumerator(IComparer<BytesRef> comparer) { int[] indices = comparer == null ? null : Sort(comparer); return new Enumerator(this, comparer, this.Length, indices); } private struct Enumerator : IBytesRefEnumerator { private readonly IComparer<BytesRef> comparer; private readonly BytesRef spare; private readonly int size; private readonly int[] indices; private readonly BytesRefArray bytesRefArray; private int pos; public Enumerator(BytesRefArray bytesRefArray, IComparer<BytesRef> comparer, int size, int[] indices) { this.spare = new BytesRef(); this.pos = 0; this.Current = null; this.bytesRefArray = bytesRefArray; this.comparer = comparer; this.size = size; this.indices = indices; } public BytesRef Current { get; private set; } public bool MoveNext() { if (pos < size) { Current = bytesRefArray.Get(spare, indices == null ? pos++ : indices[pos++]); return true; } Current = null; return false; } public IComparer<BytesRef> Comparer => comparer; } } }
using System; using System.Collections.Generic; using System.Linq; using Nop.Core; using Nop.Core.Caching; using Nop.Core.Data; using Nop.Core.Domain.Directory; using Nop.Services.Events; namespace Nop.Services.Directory { /// <summary> /// Measure dimension service /// </summary> public partial class MeasureService : IMeasureService { #region Constants /// <summary> /// Key for caching /// </summary> private const string MEASUREDIMENSIONS_ALL_KEY = "Nop.measuredimension.all"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : dimension ID /// </remarks> private const string MEASUREDIMENSIONS_BY_ID_KEY = "Nop.measuredimension.id-{0}"; /// <summary> /// Key for caching /// </summary> private const string MEASUREWEIGHTS_ALL_KEY = "Nop.measureweight.all"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : weight ID /// </remarks> private const string MEASUREWEIGHTS_BY_ID_KEY = "Nop.measureweight.id-{0}"; /// <summary> /// Key pattern to clear cache /// </summary> private const string MEASUREDIMENSIONS_PATTERN_KEY = "Nop.measuredimension."; /// <summary> /// Key pattern to clear cache /// </summary> private const string MEASUREWEIGHTS_PATTERN_KEY = "Nop.measureweight."; #endregion #region Fields private readonly IRepository<MeasureDimension> _measureDimensionRepository; private readonly IRepository<MeasureWeight> _measureWeightRepository; private readonly ICacheManager _cacheManager; private readonly MeasureSettings _measureSettings; private readonly IEventPublisher _eventPublisher; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="cacheManager">Cache manager</param> /// <param name="measureDimensionRepository">Dimension repository</param> /// <param name="measureWeightRepository">Weight repository</param> /// <param name="measureSettings">Measure settings</param> /// <param name="eventPublisher">Event published</param> public MeasureService(ICacheManager cacheManager, IRepository<MeasureDimension> measureDimensionRepository, IRepository<MeasureWeight> measureWeightRepository, MeasureSettings measureSettings, IEventPublisher eventPublisher) { _cacheManager = cacheManager; _measureDimensionRepository = measureDimensionRepository; _measureWeightRepository = measureWeightRepository; _measureSettings = measureSettings; _eventPublisher = eventPublisher; } #endregion #region Methods #region Dimensions /// <summary> /// Deletes measure dimension /// </summary> /// <param name="measureDimension">Measure dimension</param> public virtual void DeleteMeasureDimension(MeasureDimension measureDimension) { if (measureDimension == null) throw new ArgumentNullException("measureDimension"); _measureDimensionRepository.Delete(measureDimension); _cacheManager.RemoveByPattern(MEASUREDIMENSIONS_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(measureDimension); } /// <summary> /// Gets a measure dimension by identifier /// </summary> /// <param name="measureDimensionId">Measure dimension identifier</param> /// <returns>Measure dimension</returns> public virtual MeasureDimension GetMeasureDimensionById(int measureDimensionId) { if (measureDimensionId == 0) return null; string key = string.Format(MEASUREDIMENSIONS_BY_ID_KEY, measureDimensionId); return _cacheManager.Get(key, () => _measureDimensionRepository.GetById(measureDimensionId)); } /// <summary> /// Gets a measure dimension by system keyword /// </summary> /// <param name="systemKeyword">The system keyword</param> /// <returns>Measure dimension</returns> public virtual MeasureDimension GetMeasureDimensionBySystemKeyword(string systemKeyword) { if (String.IsNullOrEmpty(systemKeyword)) return null; var measureDimensions = GetAllMeasureDimensions(); foreach (var measureDimension in measureDimensions) if (measureDimension.SystemKeyword.ToLowerInvariant() == systemKeyword.ToLowerInvariant()) return measureDimension; return null; } /// <summary> /// Gets all measure dimensions /// </summary> /// <returns>Measure dimensions</returns> public virtual IList<MeasureDimension> GetAllMeasureDimensions() { string key = MEASUREDIMENSIONS_ALL_KEY; return _cacheManager.Get(key, () => { var query = from md in _measureDimensionRepository.Table orderby md.DisplayOrder, md.Id select md; var measureDimensions = query.ToList(); return measureDimensions; }); } /// <summary> /// Inserts a measure dimension /// </summary> /// <param name="measure">Measure dimension</param> public virtual void InsertMeasureDimension(MeasureDimension measure) { if (measure == null) throw new ArgumentNullException("measure"); _measureDimensionRepository.Insert(measure); _cacheManager.RemoveByPattern(MEASUREDIMENSIONS_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(measure); } /// <summary> /// Updates the measure dimension /// </summary> /// <param name="measure">Measure dimension</param> public virtual void UpdateMeasureDimension(MeasureDimension measure) { if (measure == null) throw new ArgumentNullException("measure"); _measureDimensionRepository.Update(measure); _cacheManager.RemoveByPattern(MEASUREDIMENSIONS_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(measure); } /// <summary> /// Converts dimension /// </summary> /// <param name="value">Value to convert</param> /// <param name="sourceMeasureDimension">Source dimension</param> /// <param name="targetMeasureDimension">Target dimension</param> /// <param name="round">A value indicating whether a result should be rounded</param> /// <returns>Converted value</returns> public virtual decimal ConvertDimension(decimal value, MeasureDimension sourceMeasureDimension, MeasureDimension targetMeasureDimension, bool round = true) { if (sourceMeasureDimension == null) throw new ArgumentNullException("sourceMeasureDimension"); if (targetMeasureDimension == null) throw new ArgumentNullException("targetMeasureDimension"); decimal result = value; if (result != decimal.Zero && sourceMeasureDimension.Id != targetMeasureDimension.Id) { result = ConvertToPrimaryMeasureDimension(result, sourceMeasureDimension); result = ConvertFromPrimaryMeasureDimension(result, targetMeasureDimension); } if (round) result = Math.Round(result, 2); return result; } /// <summary> /// Converts to primary measure dimension /// </summary> /// <param name="value">Value to convert</param> /// <param name="sourceMeasureDimension">Source dimension</param> /// <returns>Converted value</returns> public virtual decimal ConvertToPrimaryMeasureDimension(decimal value, MeasureDimension sourceMeasureDimension) { if (sourceMeasureDimension == null) throw new ArgumentNullException("sourceMeasureDimension"); decimal result = value; var baseDimensionIn = GetMeasureDimensionById(_measureSettings.BaseDimensionId); if (result != decimal.Zero && sourceMeasureDimension.Id != baseDimensionIn.Id) { decimal exchangeRatio = sourceMeasureDimension.Ratio; if (exchangeRatio == decimal.Zero) throw new NopException(string.Format("Exchange ratio not set for dimension [{0}]", sourceMeasureDimension.Name)); result = result / exchangeRatio; } return result; } /// <summary> /// Converts from primary dimension /// </summary> /// <param name="value">Value to convert</param> /// <param name="targetMeasureDimension">Target dimension</param> /// <returns>Converted value</returns> public virtual decimal ConvertFromPrimaryMeasureDimension(decimal value, MeasureDimension targetMeasureDimension) { if (targetMeasureDimension == null) throw new ArgumentNullException("targetMeasureDimension"); decimal result = value; var baseDimensionIn = GetMeasureDimensionById(_measureSettings.BaseDimensionId); if (result != decimal.Zero && targetMeasureDimension.Id != baseDimensionIn.Id) { decimal exchangeRatio = targetMeasureDimension.Ratio; if (exchangeRatio == decimal.Zero) throw new NopException(string.Format("Exchange ratio not set for dimension [{0}]", targetMeasureDimension.Name)); result = result * exchangeRatio; } return result; } #endregion #region Weights /// <summary> /// Deletes measure weight /// </summary> /// <param name="measureWeight">Measure weight</param> public virtual void DeleteMeasureWeight(MeasureWeight measureWeight) { if (measureWeight == null) throw new ArgumentNullException("measureWeight"); _measureWeightRepository.Delete(measureWeight); _cacheManager.RemoveByPattern(MEASUREWEIGHTS_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(measureWeight); } /// <summary> /// Gets a measure weight by identifier /// </summary> /// <param name="measureWeightId">Measure weight identifier</param> /// <returns>Measure weight</returns> public virtual MeasureWeight GetMeasureWeightById(int measureWeightId) { if (measureWeightId == 0) return null; string key = string.Format(MEASUREWEIGHTS_BY_ID_KEY, measureWeightId); return _cacheManager.Get(key, () => _measureWeightRepository.GetById(measureWeightId)); } /// <summary> /// Gets a measure weight by system keyword /// </summary> /// <param name="systemKeyword">The system keyword</param> /// <returns>Measure weight</returns> public virtual MeasureWeight GetMeasureWeightBySystemKeyword(string systemKeyword) { if (String.IsNullOrEmpty(systemKeyword)) return null; var measureWeights = GetAllMeasureWeights(); foreach (var measureWeight in measureWeights) if (measureWeight.SystemKeyword.ToLowerInvariant() == systemKeyword.ToLowerInvariant()) return measureWeight; return null; } /// <summary> /// Gets all measure weights /// </summary> /// <returns>Measure weights</returns> public virtual IList<MeasureWeight> GetAllMeasureWeights() { string key = MEASUREWEIGHTS_ALL_KEY; return _cacheManager.Get(key, () => { var query = from mw in _measureWeightRepository.Table orderby mw.DisplayOrder, mw.Id select mw; var measureWeights = query.ToList(); return measureWeights; }); } /// <summary> /// Inserts a measure weight /// </summary> /// <param name="measure">Measure weight</param> public virtual void InsertMeasureWeight(MeasureWeight measure) { if (measure == null) throw new ArgumentNullException("measure"); _measureWeightRepository.Insert(measure); _cacheManager.RemoveByPattern(MEASUREWEIGHTS_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(measure); } /// <summary> /// Updates the measure weight /// </summary> /// <param name="measure">Measure weight</param> public virtual void UpdateMeasureWeight(MeasureWeight measure) { if (measure == null) throw new ArgumentNullException("measure"); _measureWeightRepository.Update(measure); _cacheManager.RemoveByPattern(MEASUREWEIGHTS_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(measure); } /// <summary> /// Converts weight /// </summary> /// <param name="value">Value to convert</param> /// <param name="sourceMeasureWeight">Source weight</param> /// <param name="targetMeasureWeight">Target weight</param> /// <param name="round">A value indicating whether a result should be rounded</param> /// <returns>Converted value</returns> public virtual decimal ConvertWeight(decimal value, MeasureWeight sourceMeasureWeight, MeasureWeight targetMeasureWeight, bool round = true) { if (sourceMeasureWeight == null) throw new ArgumentNullException("sourceMeasureWeight"); if (targetMeasureWeight == null) throw new ArgumentNullException("targetMeasureWeight"); decimal result = value; if (result != decimal.Zero && sourceMeasureWeight.Id != targetMeasureWeight.Id) { result = ConvertToPrimaryMeasureWeight(result, sourceMeasureWeight); result = ConvertFromPrimaryMeasureWeight(result, targetMeasureWeight); } if (round) result = Math.Round(result, 2); return result; } /// <summary> /// Converts to primary measure weight /// </summary> /// <param name="value">Value to convert</param> /// <param name="sourceMeasureWeight">Source weight</param> /// <returns>Converted value</returns> public virtual decimal ConvertToPrimaryMeasureWeight(decimal value, MeasureWeight sourceMeasureWeight) { if (sourceMeasureWeight == null) throw new ArgumentNullException("sourceMeasureWeight"); decimal result = value; var baseWeightIn = GetMeasureWeightById(_measureSettings.BaseWeightId); if (result != decimal.Zero && sourceMeasureWeight.Id != baseWeightIn.Id) { decimal exchangeRatio = sourceMeasureWeight.Ratio; if (exchangeRatio == decimal.Zero) throw new NopException(string.Format("Exchange ratio not set for weight [{0}]", sourceMeasureWeight.Name)); result = result / exchangeRatio; } return result; } /// <summary> /// Converts from primary weight /// </summary> /// <param name="value">Value to convert</param> /// <param name="targetMeasureWeight">Target weight</param> /// <returns>Converted value</returns> public virtual decimal ConvertFromPrimaryMeasureWeight(decimal value, MeasureWeight targetMeasureWeight) { if (targetMeasureWeight == null) throw new ArgumentNullException("targetMeasureWeight"); decimal result = value; var baseWeightIn = GetMeasureWeightById(_measureSettings.BaseWeightId); if (result != decimal.Zero && targetMeasureWeight.Id != baseWeightIn.Id) { decimal exchangeRatio = targetMeasureWeight.Ratio; if (exchangeRatio == decimal.Zero) throw new NopException(string.Format("Exchange ratio not set for weight [{0}]", targetMeasureWeight.Name)); result = result * exchangeRatio; } return result; } #endregion #endregion } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Settings/Master/EquippedBadgeSettings.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Settings.Master { /// <summary>Holder for reflection information generated from POGOProtos/Settings/Master/EquippedBadgeSettings.proto</summary> public static partial class EquippedBadgeSettingsReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Settings/Master/EquippedBadgeSettings.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static EquippedBadgeSettingsReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjZQT0dPUHJvdG9zL1NldHRpbmdzL01hc3Rlci9FcXVpcHBlZEJhZGdlU2V0", "dGluZ3MucHJvdG8SGlBPR09Qcm90b3MuU2V0dGluZ3MuTWFzdGVyInkKFUVx", "dWlwcGVkQmFkZ2VTZXR0aW5ncxIfChdlcXVpcF9iYWRnZV9jb29sZG93bl9t", "cxgBIAEoAxIfChdjYXRjaF9wcm9iYWJpbGl0eV9ib251cxgCIAMoAhIeChZm", "bGVlX3Byb2JhYmlsaXR5X2JvbnVzGAMgAygCYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Settings.Master.EquippedBadgeSettings), global::POGOProtos.Settings.Master.EquippedBadgeSettings.Parser, new[]{ "EquipBadgeCooldownMs", "CatchProbabilityBonus", "FleeProbabilityBonus" }, null, null, null) })); } #endregion } #region Messages public sealed partial class EquippedBadgeSettings : pb::IMessage<EquippedBadgeSettings> { private static readonly pb::MessageParser<EquippedBadgeSettings> _parser = new pb::MessageParser<EquippedBadgeSettings>(() => new EquippedBadgeSettings()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<EquippedBadgeSettings> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Settings.Master.EquippedBadgeSettingsReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EquippedBadgeSettings() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EquippedBadgeSettings(EquippedBadgeSettings other) : this() { equipBadgeCooldownMs_ = other.equipBadgeCooldownMs_; catchProbabilityBonus_ = other.catchProbabilityBonus_.Clone(); fleeProbabilityBonus_ = other.fleeProbabilityBonus_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EquippedBadgeSettings Clone() { return new EquippedBadgeSettings(this); } /// <summary>Field number for the "equip_badge_cooldown_ms" field.</summary> public const int EquipBadgeCooldownMsFieldNumber = 1; private long equipBadgeCooldownMs_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long EquipBadgeCooldownMs { get { return equipBadgeCooldownMs_; } set { equipBadgeCooldownMs_ = value; } } /// <summary>Field number for the "catch_probability_bonus" field.</summary> public const int CatchProbabilityBonusFieldNumber = 2; private static readonly pb::FieldCodec<float> _repeated_catchProbabilityBonus_codec = pb::FieldCodec.ForFloat(18); private readonly pbc::RepeatedField<float> catchProbabilityBonus_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> CatchProbabilityBonus { get { return catchProbabilityBonus_; } } /// <summary>Field number for the "flee_probability_bonus" field.</summary> public const int FleeProbabilityBonusFieldNumber = 3; private static readonly pb::FieldCodec<float> _repeated_fleeProbabilityBonus_codec = pb::FieldCodec.ForFloat(26); private readonly pbc::RepeatedField<float> fleeProbabilityBonus_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> FleeProbabilityBonus { get { return fleeProbabilityBonus_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as EquippedBadgeSettings); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(EquippedBadgeSettings other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (EquipBadgeCooldownMs != other.EquipBadgeCooldownMs) return false; if(!catchProbabilityBonus_.Equals(other.catchProbabilityBonus_)) return false; if(!fleeProbabilityBonus_.Equals(other.fleeProbabilityBonus_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (EquipBadgeCooldownMs != 0L) hash ^= EquipBadgeCooldownMs.GetHashCode(); hash ^= catchProbabilityBonus_.GetHashCode(); hash ^= fleeProbabilityBonus_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (EquipBadgeCooldownMs != 0L) { output.WriteRawTag(8); output.WriteInt64(EquipBadgeCooldownMs); } catchProbabilityBonus_.WriteTo(output, _repeated_catchProbabilityBonus_codec); fleeProbabilityBonus_.WriteTo(output, _repeated_fleeProbabilityBonus_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (EquipBadgeCooldownMs != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(EquipBadgeCooldownMs); } size += catchProbabilityBonus_.CalculateSize(_repeated_catchProbabilityBonus_codec); size += fleeProbabilityBonus_.CalculateSize(_repeated_fleeProbabilityBonus_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(EquippedBadgeSettings other) { if (other == null) { return; } if (other.EquipBadgeCooldownMs != 0L) { EquipBadgeCooldownMs = other.EquipBadgeCooldownMs; } catchProbabilityBonus_.Add(other.catchProbabilityBonus_); fleeProbabilityBonus_.Add(other.fleeProbabilityBonus_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { EquipBadgeCooldownMs = input.ReadInt64(); break; } case 18: case 21: { catchProbabilityBonus_.AddEntriesFrom(input, _repeated_catchProbabilityBonus_codec); break; } case 26: case 29: { fleeProbabilityBonus_.AddEntriesFrom(input, _repeated_fleeProbabilityBonus_codec); break; } } } } } #endregion } #endregion Designer generated code
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Rulesets; using osu.Game.Screens.Select; using osu.Game.Screens.Select.Carousel; using osu.Game.Screens.Select.Filter; namespace osu.Game.Tests.Visual.SongSelect { [TestFixture] public class TestSceneBeatmapCarousel : OsuTestScene { private TestBeatmapCarousel carousel; private RulesetStore rulesets; public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(CarouselItem), typeof(CarouselGroup), typeof(CarouselGroupEagerSelect), typeof(CarouselBeatmap), typeof(CarouselBeatmapSet), typeof(DrawableCarouselItem), typeof(CarouselItemState), typeof(DrawableCarouselBeatmap), typeof(DrawableCarouselBeatmapSet), }; private readonly Stack<BeatmapSetInfo> selectedSets = new Stack<BeatmapSetInfo>(); private readonly HashSet<int> eagerSelectedIDs = new HashSet<int>(); private BeatmapInfo currentSelection => carousel.SelectedBeatmap; private const int set_count = 5; [BackgroundDependencyLoader] private void load(RulesetStore rulesets) { this.rulesets = rulesets; } [Test] public void TestRecommendedSelection() { loadBeatmaps(); AddStep("set recommendation function", () => carousel.GetRecommendedBeatmap = beatmaps => beatmaps.LastOrDefault()); // check recommended was selected advanceSelection(direction: 1, diff: false); waitForSelection(1, 3); // change away from recommended advanceSelection(direction: -1, diff: true); waitForSelection(1, 2); // next set, check recommended advanceSelection(direction: 1, diff: false); waitForSelection(2, 3); // next set, check recommended advanceSelection(direction: 1, diff: false); waitForSelection(3, 3); // go back to first set and ensure user selection was retained advanceSelection(direction: -1, diff: false); advanceSelection(direction: -1, diff: false); waitForSelection(1, 2); } /// <summary> /// Test keyboard traversal /// </summary> [Test] public void TestTraversal() { loadBeatmaps(); advanceSelection(direction: 1, diff: false); waitForSelection(1, 1); advanceSelection(direction: 1, diff: true); waitForSelection(1, 2); advanceSelection(direction: -1, diff: false); waitForSelection(set_count, 1); advanceSelection(direction: -1, diff: true); waitForSelection(set_count - 1, 3); advanceSelection(diff: false); advanceSelection(diff: false); waitForSelection(1, 2); advanceSelection(direction: -1, diff: true); advanceSelection(direction: -1, diff: true); waitForSelection(set_count, 3); } [TestCase(true)] [TestCase(false)] public void TestTraversalBeyondVisible(bool forwards) { var sets = new List<BeatmapSetInfo>(); const int total_set_count = 200; for (int i = 0; i < total_set_count; i++) sets.Add(createTestBeatmapSet(i + 1)); loadBeatmaps(sets); for (int i = 1; i < total_set_count; i += i) selectNextAndAssert(i); void selectNextAndAssert(int amount) { setSelected(forwards ? 1 : total_set_count, 1); AddStep($"{(forwards ? "Next" : "Previous")} beatmap {amount} times", () => { for (int i = 0; i < amount; i++) { carousel.SelectNext(forwards ? 1 : -1); } }); waitForSelection(forwards ? amount + 1 : total_set_count - amount); } } [Test] public void TestTraversalBeyondVisibleDifficulties() { var sets = new List<BeatmapSetInfo>(); const int total_set_count = 20; for (int i = 0; i < total_set_count; i++) sets.Add(createTestBeatmapSet(i + 1)); loadBeatmaps(sets); // Selects next set once, difficulty index doesn't change selectNextAndAssert(3, true, 2, 1); // Selects next set 16 times (50 \ 3 == 16), difficulty index changes twice (50 % 3 == 2) selectNextAndAssert(50, true, 17, 3); // Travels around the carousel thrice (200 \ 60 == 3) // continues to select 20 times (200 \ 60 == 20) // selects next set 6 times (20 \ 3 == 6) // difficulty index changes twice (20 % 3 == 2) selectNextAndAssert(200, true, 7, 3); // All same but in reverse selectNextAndAssert(3, false, 19, 3); selectNextAndAssert(50, false, 4, 1); selectNextAndAssert(200, false, 14, 1); void selectNextAndAssert(int amount, bool forwards, int expectedSet, int expectedDiff) { // Select very first or very last difficulty setSelected(forwards ? 1 : 20, forwards ? 1 : 3); AddStep($"{(forwards ? "Next" : "Previous")} difficulty {amount} times", () => { for (int i = 0; i < amount; i++) carousel.SelectNext(forwards ? 1 : -1, false); }); waitForSelection(expectedSet, expectedDiff); } } /// <summary> /// Test filtering /// </summary> [Test] public void TestFiltering() { loadBeatmaps(); // basic filtering setSelected(1, 1); AddStep("Filter", () => carousel.Filter(new FilterCriteria { SearchText = "set #3!" }, false)); checkVisibleItemCount(diff: false, count: 1); checkVisibleItemCount(diff: true, count: 3); waitForSelection(3, 1); advanceSelection(diff: true, count: 4); waitForSelection(3, 2); AddStep("Un-filter (debounce)", () => carousel.Filter(new FilterCriteria())); AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask); checkVisibleItemCount(diff: false, count: set_count); checkVisibleItemCount(diff: true, count: 3); // test filtering some difficulties (and keeping current beatmap set selected). setSelected(1, 2); AddStep("Filter some difficulties", () => carousel.Filter(new FilterCriteria { SearchText = "Normal" }, false)); waitForSelection(1, 1); AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false)); waitForSelection(1, 1); AddStep("Filter all", () => carousel.Filter(new FilterCriteria { SearchText = "Dingo" }, false)); checkVisibleItemCount(false, 0); checkVisibleItemCount(true, 0); AddAssert("Selection is null", () => currentSelection == null); advanceSelection(true); AddAssert("Selection is null", () => currentSelection == null); advanceSelection(false); AddAssert("Selection is null", () => currentSelection == null); AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false)); AddAssert("Selection is non-null", () => currentSelection != null); setSelected(1, 3); } [Test] public void TestFilterRange() { loadBeatmaps(); // buffer the selection setSelected(3, 2); setSelected(1, 3); AddStep("Apply a range filter", () => carousel.Filter(new FilterCriteria { SearchText = "#3", StarDifficulty = new FilterCriteria.OptionalRange<double> { Min = 2, Max = 5.5, IsLowerInclusive = true } }, false)); // should reselect the buffered selection. waitForSelection(3, 2); } /// <summary> /// Test random non-repeating algorithm /// </summary> [Test] public void TestRandom() { loadBeatmaps(); setSelected(1, 1); nextRandom(); ensureRandomDidntRepeat(); nextRandom(); ensureRandomDidntRepeat(); nextRandom(); ensureRandomDidntRepeat(); prevRandom(); ensureRandomFetchSuccess(); prevRandom(); ensureRandomFetchSuccess(); nextRandom(); ensureRandomDidntRepeat(); nextRandom(); ensureRandomDidntRepeat(); nextRandom(); AddAssert("ensure repeat", () => selectedSets.Contains(carousel.SelectedBeatmapSet)); AddStep("Add set with 100 difficulties", () => carousel.UpdateBeatmapSet(createTestBeatmapSetWithManyDifficulties(set_count + 1))); AddStep("Filter Extra", () => carousel.Filter(new FilterCriteria { SearchText = "Extra 10" }, false)); checkInvisibleDifficultiesUnselectable(); checkInvisibleDifficultiesUnselectable(); checkInvisibleDifficultiesUnselectable(); checkInvisibleDifficultiesUnselectable(); checkInvisibleDifficultiesUnselectable(); AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false)); } /// <summary> /// Test adding and removing beatmap sets /// </summary> [Test] public void TestAddRemove() { loadBeatmaps(); AddStep("Add new set", () => carousel.UpdateBeatmapSet(createTestBeatmapSet(set_count + 1))); AddStep("Add new set", () => carousel.UpdateBeatmapSet(createTestBeatmapSet(set_count + 2))); checkVisibleItemCount(false, set_count + 2); AddStep("Remove set", () => carousel.RemoveBeatmapSet(createTestBeatmapSet(set_count + 2))); checkVisibleItemCount(false, set_count + 1); setSelected(set_count + 1, 1); AddStep("Remove set", () => carousel.RemoveBeatmapSet(createTestBeatmapSet(set_count + 1))); checkVisibleItemCount(false, set_count); waitForSelection(set_count); } [Test] public void TestSelectionEnteringFromEmptyRuleset() { var sets = new List<BeatmapSetInfo>(); AddStep("Create beatmaps for taiko only", () => { sets.Clear(); var rulesetBeatmapSet = createTestBeatmapSet(1); var taikoRuleset = rulesets.AvailableRulesets.ElementAt(1); rulesetBeatmapSet.Beatmaps.ForEach(b => { b.Ruleset = taikoRuleset; b.RulesetID = 1; }); sets.Add(rulesetBeatmapSet); }); loadBeatmaps(sets, () => new FilterCriteria { Ruleset = rulesets.AvailableRulesets.ElementAt(0) }); AddStep("Set non-empty mode filter", () => carousel.Filter(new FilterCriteria { Ruleset = rulesets.AvailableRulesets.ElementAt(1) }, false)); AddAssert("Something is selected", () => carousel.SelectedBeatmap != null); } /// <summary> /// Test sorting /// </summary> [Test] public void TestSorting() { loadBeatmaps(); AddStep("Sort by author", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Author }, false)); AddAssert("Check zzzzz is at bottom", () => carousel.BeatmapSets.Last().Metadata.AuthorString == "zzzzz"); AddStep("Sort by artist", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Artist }, false)); AddAssert($"Check #{set_count} is at bottom", () => carousel.BeatmapSets.Last().Metadata.Title.EndsWith($"#{set_count}!")); } [Test] public void TestSortingStability() { var sets = new List<BeatmapSetInfo>(); for (int i = 0; i < 20; i++) { var set = createTestBeatmapSet(i); set.Metadata.Artist = "same artist"; set.Metadata.Title = "same title"; sets.Add(set); } loadBeatmaps(sets); AddStep("Sort by artist", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Artist }, false)); AddAssert("Items remain in original order", () => carousel.BeatmapSets.Select((set, index) => set.ID == index).All(b => b)); AddStep("Sort by title", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Title }, false)); AddAssert("Items remain in original order", () => carousel.BeatmapSets.Select((set, index) => set.ID == index).All(b => b)); } [Test] public void TestSortingWithFiltered() { List<BeatmapSetInfo> sets = new List<BeatmapSetInfo>(); for (int i = 0; i < 3; i++) { var set = createTestBeatmapSet(i); set.Beatmaps[0].StarDifficulty = 3 - i; set.Beatmaps[2].StarDifficulty = 6 + i; sets.Add(set); } loadBeatmaps(sets); AddStep("Filter to normal", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Difficulty, SearchText = "Normal" }, false)); AddAssert("Check first set at end", () => carousel.BeatmapSets.First() == sets.Last()); AddAssert("Check last set at start", () => carousel.BeatmapSets.Last() == sets.First()); AddStep("Filter to insane", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Difficulty, SearchText = "Insane" }, false)); AddAssert("Check first set at start", () => carousel.BeatmapSets.First() == sets.First()); AddAssert("Check last set at end", () => carousel.BeatmapSets.Last() == sets.Last()); } [Test] public void TestRemoveAll() { loadBeatmaps(); setSelected(2, 1); AddAssert("Selection is non-null", () => currentSelection != null); AddStep("Remove selected", () => carousel.RemoveBeatmapSet(carousel.SelectedBeatmapSet)); waitForSelection(2); AddStep("Remove first", () => carousel.RemoveBeatmapSet(carousel.BeatmapSets.First())); AddStep("Remove first", () => carousel.RemoveBeatmapSet(carousel.BeatmapSets.First())); waitForSelection(1); AddUntilStep("Remove all", () => { if (!carousel.BeatmapSets.Any()) return true; carousel.RemoveBeatmapSet(carousel.BeatmapSets.Last()); return false; }); checkNoSelection(); } [Test] public void TestEmptyTraversal() { loadBeatmaps(new List<BeatmapSetInfo>()); advanceSelection(direction: 1, diff: false); checkNoSelection(); advanceSelection(direction: 1, diff: true); checkNoSelection(); advanceSelection(direction: -1, diff: false); checkNoSelection(); advanceSelection(direction: -1, diff: true); checkNoSelection(); } [Test] public void TestHiding() { BeatmapSetInfo hidingSet = null; List<BeatmapSetInfo> hiddenList = new List<BeatmapSetInfo>(); AddStep("create hidden set", () => { hidingSet = createTestBeatmapSet(1); hidingSet.Beatmaps[1].Hidden = true; hiddenList.Clear(); hiddenList.Add(hidingSet); }); loadBeatmaps(hiddenList); setSelected(1, 1); checkVisibleItemCount(true, 2); advanceSelection(true); waitForSelection(1, 3); setHidden(3); waitForSelection(1, 1); setHidden(2, false); advanceSelection(true); waitForSelection(1, 2); setHidden(1); waitForSelection(1, 2); setHidden(2); checkNoSelection(); void setHidden(int diff, bool hidden = true) { AddStep((hidden ? "" : "un") + $"hide diff {diff}", () => { hidingSet.Beatmaps[diff - 1].Hidden = hidden; carousel.UpdateBeatmapSet(hidingSet); }); } } [Test] public void TestSelectingFilteredRuleset() { BeatmapSetInfo testMixed = null; createCarousel(); AddStep("add mixed ruleset beatmapset", () => { testMixed = createTestBeatmapSet(set_count + 1); for (int i = 0; i <= 2; i++) { testMixed.Beatmaps[i].Ruleset = rulesets.AvailableRulesets.ElementAt(i); testMixed.Beatmaps[i].RulesetID = i; } carousel.UpdateBeatmapSet(testMixed); }); AddStep("filter to ruleset 0", () => carousel.Filter(new FilterCriteria { Ruleset = rulesets.AvailableRulesets.ElementAt(0) }, false)); AddStep("select filtered map skipping filtered", () => carousel.SelectBeatmap(testMixed.Beatmaps[1], false)); AddAssert("unfiltered beatmap not selected", () => carousel.SelectedBeatmap.RulesetID == 0); AddStep("remove mixed set", () => { carousel.RemoveBeatmapSet(testMixed); testMixed = null; }); BeatmapSetInfo testSingle = null; AddStep("add single ruleset beatmapset", () => { testSingle = createTestBeatmapSet(set_count + 2); testSingle.Beatmaps.ForEach(b => { b.Ruleset = rulesets.AvailableRulesets.ElementAt(1); b.RulesetID = b.Ruleset.ID ?? 1; }); carousel.UpdateBeatmapSet(testSingle); }); AddStep("select filtered map skipping filtered", () => carousel.SelectBeatmap(testSingle.Beatmaps[0], false)); checkNoSelection(); AddStep("remove single ruleset set", () => carousel.RemoveBeatmapSet(testSingle)); } [Test] public void TestCarouselRemembersSelection() { List<BeatmapSetInfo> manySets = new List<BeatmapSetInfo>(); for (int i = 1; i <= 50; i++) manySets.Add(createTestBeatmapSet(i)); loadBeatmaps(manySets); advanceSelection(direction: 1, diff: false); for (int i = 0; i < 5; i++) { AddStep("Toggle non-matching filter", () => { carousel.Filter(new FilterCriteria { SearchText = Guid.NewGuid().ToString() }, false); }); AddStep("Restore no filter", () => { carousel.Filter(new FilterCriteria(), false); eagerSelectedIDs.Add(carousel.SelectedBeatmapSet.ID); }); } // always returns to same selection as long as it's available. AddAssert("Selection was remembered", () => eagerSelectedIDs.Count == 1); } [Test] public void TestRandomFallbackOnNonMatchingPrevious() { List<BeatmapSetInfo> manySets = new List<BeatmapSetInfo>(); AddStep("populate maps", () => { for (int i = 0; i < 10; i++) { var set = createTestBeatmapSet(i); foreach (var b in set.Beatmaps) { // all taiko except for first int ruleset = i > 0 ? 1 : 0; b.Ruleset = rulesets.GetRuleset(ruleset); b.RulesetID = ruleset; } manySets.Add(set); } }); loadBeatmaps(manySets); for (int i = 0; i < 10; i++) { AddStep("Reset filter", () => carousel.Filter(new FilterCriteria(), false)); AddStep("select first beatmap", () => carousel.SelectBeatmap(manySets.First().Beatmaps.First())); AddStep("Toggle non-matching filter", () => { carousel.Filter(new FilterCriteria { SearchText = Guid.NewGuid().ToString() }, false); }); AddAssert("selection lost", () => carousel.SelectedBeatmap == null); AddStep("Restore different ruleset filter", () => { carousel.Filter(new FilterCriteria { Ruleset = rulesets.GetRuleset(1) }, false); eagerSelectedIDs.Add(carousel.SelectedBeatmapSet.ID); }); AddAssert("selection changed", () => carousel.SelectedBeatmap != manySets.First().Beatmaps.First()); } AddAssert("Selection was random", () => eagerSelectedIDs.Count > 2); } [Test] public void TestFilteringByUserStarDifficulty() { BeatmapSetInfo set = null; loadBeatmaps(new List<BeatmapSetInfo>()); AddStep("add mixed difficulty set", () => { set = createTestBeatmapSet(1); set.Beatmaps.Clear(); for (int i = 1; i <= 15; i++) { set.Beatmaps.Add(new BeatmapInfo { Version = $"Stars: {i}", StarDifficulty = i, }); } carousel.UpdateBeatmapSet(set); }); AddStep("select added set", () => carousel.SelectBeatmap(set.Beatmaps[0], false)); AddStep("filter [5..]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 5 } })); AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask); checkVisibleItemCount(true, 11); AddStep("filter to [0..7]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Max = 7 } })); AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask); checkVisibleItemCount(true, 7); AddStep("filter to [5..7]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 5, Max = 7 } })); AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask); checkVisibleItemCount(true, 3); AddStep("filter [2..2]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 2, Max = 2 } })); AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask); checkVisibleItemCount(true, 1); AddStep("filter to [0..]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 0 } })); AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask); checkVisibleItemCount(true, 15); } private void loadBeatmaps(List<BeatmapSetInfo> beatmapSets = null, Func<FilterCriteria> initialCriteria = null) { createCarousel(); if (beatmapSets == null) { beatmapSets = new List<BeatmapSetInfo>(); for (int i = 1; i <= set_count; i++) beatmapSets.Add(createTestBeatmapSet(i)); } bool changed = false; AddStep($"Load {(beatmapSets.Count > 0 ? beatmapSets.Count.ToString() : "some")} beatmaps", () => { carousel.Filter(initialCriteria?.Invoke() ?? new FilterCriteria()); carousel.BeatmapSetsChanged = () => changed = true; carousel.BeatmapSets = beatmapSets; }); AddUntilStep("Wait for load", () => changed); } private void createCarousel(Container target = null) { AddStep("Create carousel", () => { selectedSets.Clear(); eagerSelectedIDs.Clear(); (target ?? this).Child = carousel = new TestBeatmapCarousel { RelativeSizeAxes = Axes.Both, }; }); } private void ensureRandomFetchSuccess() => AddAssert("ensure prev random fetch worked", () => selectedSets.Peek() == carousel.SelectedBeatmapSet); private void waitForSelection(int set, int? diff = null) => AddUntilStep($"selected is set{set}{(diff.HasValue ? $" diff{diff.Value}" : "")}", () => { if (diff != null) return carousel.SelectedBeatmap == carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Skip(diff.Value - 1).First(); return carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Contains(carousel.SelectedBeatmap); }); private void setSelected(int set, int diff) => AddStep($"select set{set} diff{diff}", () => carousel.SelectBeatmap(carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Skip(diff - 1).First())); private void advanceSelection(bool diff, int direction = 1, int count = 1) { if (count == 1) { AddStep($"select {(direction > 0 ? "next" : "prev")} {(diff ? "diff" : "set")}", () => carousel.SelectNext(direction, !diff)); } else { AddRepeatStep($"select {(direction > 0 ? "next" : "prev")} {(diff ? "diff" : "set")}", () => carousel.SelectNext(direction, !diff), count); } } private void checkVisibleItemCount(bool diff, int count) => AddAssert($"{count} {(diff ? "diffs" : "sets")} visible", () => carousel.Items.Count(s => (diff ? s.Item is CarouselBeatmap : s.Item is CarouselBeatmapSet) && s.Item.Visible) == count); private void checkNoSelection() => AddAssert("Selection is null", () => currentSelection == null); private void nextRandom() => AddStep("select random next", () => { carousel.RandomAlgorithm.Value = RandomSelectAlgorithm.RandomPermutation; if (!selectedSets.Any() && carousel.SelectedBeatmap != null) selectedSets.Push(carousel.SelectedBeatmapSet); carousel.SelectNextRandom(); selectedSets.Push(carousel.SelectedBeatmapSet); }); private void ensureRandomDidntRepeat() => AddAssert("ensure no repeats", () => selectedSets.Distinct().Count() == selectedSets.Count); private void prevRandom() => AddStep("select random last", () => { carousel.SelectPreviousRandom(); selectedSets.Pop(); }); private bool selectedBeatmapVisible() { var currentlySelected = carousel.Items.Find(s => s.Item is CarouselBeatmap && s.Item.State.Value == CarouselItemState.Selected); if (currentlySelected == null) return true; return currentlySelected.Item.Visible; } private void checkInvisibleDifficultiesUnselectable() { nextRandom(); AddAssert("Selection is visible", selectedBeatmapVisible); } private BeatmapSetInfo createTestBeatmapSet(int id) { return new BeatmapSetInfo { ID = id, OnlineBeatmapSetID = id, Hash = new MemoryStream(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString())).ComputeMD5Hash(), Metadata = new BeatmapMetadata { // Create random metadata, then we can check if sorting works based on these Artist = $"peppy{id.ToString().PadLeft(6, '0')}", Title = $"test set #{id}!", AuthorString = string.Concat(Enumerable.Repeat((char)('z' - Math.Min(25, id - 1)), 5)) }, Beatmaps = new List<BeatmapInfo>(new[] { new BeatmapInfo { OnlineBeatmapID = id * 10, Path = "normal.osu", Version = "Normal", StarDifficulty = 2, BaseDifficulty = new BeatmapDifficulty { OverallDifficulty = 3.5f, } }, new BeatmapInfo { OnlineBeatmapID = id * 10 + 1, Path = "hard.osu", Version = "Hard", StarDifficulty = 5, BaseDifficulty = new BeatmapDifficulty { OverallDifficulty = 5, } }, new BeatmapInfo { OnlineBeatmapID = id * 10 + 2, Path = "insane.osu", Version = "Insane", StarDifficulty = 6, BaseDifficulty = new BeatmapDifficulty { OverallDifficulty = 7, } }, }), }; } private BeatmapSetInfo createTestBeatmapSetWithManyDifficulties(int id) { var toReturn = new BeatmapSetInfo { ID = id, OnlineBeatmapSetID = id, Hash = new MemoryStream(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString())).ComputeMD5Hash(), Metadata = new BeatmapMetadata { // Create random metadata, then we can check if sorting works based on these Artist = $"peppy{id.ToString().PadLeft(6, '0')}", Title = $"test set #{id}!", AuthorString = string.Concat(Enumerable.Repeat((char)('z' - Math.Min(25, id - 1)), 5)) }, Beatmaps = new List<BeatmapInfo>(), }; for (int b = 1; b < 101; b++) { toReturn.Beatmaps.Add(new BeatmapInfo { OnlineBeatmapID = b * 10, Path = $"extra{b}.osu", Version = $"Extra {b}", Ruleset = rulesets.GetRuleset((b - 1) % 4), StarDifficulty = 2, BaseDifficulty = new BeatmapDifficulty { OverallDifficulty = 3.5f, } }); } return toReturn; } private class TestBeatmapCarousel : BeatmapCarousel { public new List<DrawableCarouselItem> Items => base.Items; public bool PendingFilterTask => PendingFilter != null; protected override IEnumerable<BeatmapSetInfo> GetLoadableBeatmaps() => Enumerable.Empty<BeatmapSetInfo>(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using System.Windows.Forms; using System.Text; using System.Text.RegularExpressions; using GongSolutions.Shell.Interop; namespace GongSolutions.Shell { /// <summary> /// A file-filter combo box suitable for use in open/save file dialogs. /// </summary> /// /// <remarks> /// <para> /// This control extends the <see cref="ComboBox"/> class to provide /// automatic filtering of shell items according to wildcard patterns. /// By setting the control's <see cref="ShellView"/> property, the control /// will automatically filter items in a ShellView. /// </para> /// /// <para> /// The <see cref="FilterItems"/> property accepts a filter string /// similar to that accepted by the standard <see cref="FileDialog"/> /// class, for example: /// <b>"Text files (*.txt)|*.txt|All files (*.*)|*.*"</b> /// </para> /// /// <para> /// The currently selected filter is selected by the <see cref="Filter"/> /// property. This should be set to one of the filter patterns specified /// in <see cref="FilterItems"/>, e.g. <b>"*.txt"</b>. /// </para> /// </remarks> public class FileFilterComboBox : ComboBox { /// <summary> /// Initializes a new instance of the <see cref="FileFilterComboBox"/> /// class. /// </summary> public FileFilterComboBox() { DropDownStyle = ComboBoxStyle.DropDownList; m_Regex = GenerateRegex(m_Filter); } /// <summary> /// Gets or sets the current filter string, which determines the /// items that appear in the control's <see cref="ShellView"/>. /// </summary> [Category("Behaviour"), DefaultValue("*.*")] public string Filter { get { return m_Filter; } set { if ((value != null) && (value.Length > 0)) { m_Filter = value; } else { m_Filter = "*.*"; } m_Regex = GenerateRegex(m_Filter); foreach (FilterItem item in Items) { if (item.Contains(m_Filter)) { try { m_IgnoreSelectionChange = true; SelectedItem = item; } finally { m_IgnoreSelectionChange = false; } } } if (m_ShellView != null) { m_ShellView.RefreshContents(); } } } /// <summary> /// This property does not apply to <see cref="FileFilterComboBox"/>. /// </summary> [Browsable(false)] [DefaultValue(ComboBoxStyle.DropDownList)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [EditorBrowsable(EditorBrowsableState.Never)] public new ComboBoxStyle DropDownStyle { get { return base.DropDownStyle; } set { base.DropDownStyle = value; } } /// <summary> /// Gets/sets the filter string which determines the choices that /// appear in the control's drop-down list. /// </summary> /// /// <remarks> /// <para> /// For each filtering option, the filter string contains a /// description of the filter, followed by the vertical bar (|) and /// the filter pattern. The strings for different filtering options /// are separated by the vertical bar. /// </para> /// /// <para> /// If the filter itself does not appear in the description then /// it will be automatically added when the control is displayed. /// For example, in the example below the "Video files" entry will /// be displayed as "Video files (*.avi, *.wmv)". Beacuse the "All /// files" entry already has the filter string present in its /// description, it will not be added again. /// </para> /// /// <para> /// <example> /// "Video files|*.avi, *.wmv|All files (*.*)|*.*" /// </example> /// </para> /// </remarks> [Category("Behaviour")] public string FilterItems { get { return m_FilterItems; } set { int selection; Items.Clear(); Items.AddRange(FilterItem.ParseFilterString(value, m_Filter, out selection)); if (selection != -1) { SelectedIndex = selection; } else { try { m_IgnoreSelectionChange = true; SelectedIndex = Items.Count - 1; } finally { m_IgnoreSelectionChange = false; } } m_FilterItems = value; } } /// <summary> /// This property does not apply to <see cref="FileFilterComboBox"/>. /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new ComboBox.ObjectCollection Items { get { return base.Items; } } /// <summary> /// Gets/sets the <see cref="ShellView"/> control that the /// <see cref="FileFilterComboBox"/> should filter the items of. /// </summary> [DefaultValue(null)] [Category("Behaviour")] public ShellView ShellView { get { return m_ShellView; } set { if (m_ShellView != null) { m_ShellView.FilterItem -= new FilterItemEventHandler(m_ShellView_FilterItem); } m_ShellView = value; if (m_ShellView != null) { m_ShellView.FilterItem += new FilterItemEventHandler(m_ShellView_FilterItem); } } } /// <summary> /// Generates a <see cref="Regex"/> object equivalent to the /// provided wildcard. /// </summary> /// /// <param name="wildcard"> /// The wildcard to generate a regex for. /// </param> /// /// <returns> /// A regex equivalent to the wildcard. /// </returns> public static Regex GenerateRegex(string wildcard) { string[] wildcards = wildcard.Split(','); StringBuilder regexString = new StringBuilder(); foreach (string s in wildcards) { if (regexString.Length > 0) { regexString.Append('|'); } regexString.Append( Regex.Escape(s). Replace(@"\*", ".*"). Replace(@"\?", ".")); } return new Regex(regexString.ToString(), RegexOptions.IgnoreCase | RegexOptions.Compiled); } /// <summary> /// Raises the <see cref="Control.TextChanged"/> event. /// </summary> /// /// <param name="e"> /// An EventArgs that contains the event data. /// </param> protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); if (!m_IgnoreSelectionChange) { if (SelectedItem != null) { Filter = ((FilterItem)SelectedItem).Filter; } } } void m_ShellView_FilterItem(object sender, FilterItemEventArgs e) { // Include items that are present in the filesystem, and are a // folder, or match the current regex. if (e.Include) { e.Include = (e.Item.IsFileSystem || e.Item.IsFileSystemAncestor) && (e.Item.IsFolder || m_Regex.IsMatch(e.Item.FileSystemPath)); } } string m_Filter = "*.*"; string m_FilterItems = ""; ShellView m_ShellView; Regex m_Regex; bool m_IgnoreSelectionChange; } }
// Cyotek MD5 Utility // https://github.com/cyotek/Md5 // Copyright (c) 2018-2021 Cyotek Ltd. // This work is licensed under the MIT License. // See LICENSE.TXT for the full text // Found this code useful? // https://www.cyotek.com/contribute using System; using System.Collections.Generic; // IsMatch routine based on http://www.c-sharpcorner.com/uploadfile/b81385/efficient-string-matching-algorithm-with-use-of-wildcard-characters/ namespace Cyotek { internal sealed class WildcardPatternMatcher { #region Public Fields public const char DefaultMultipleWildcard = '*'; public const char DefaultSingleWildcard = '?'; public static readonly WildcardPatternMatcher Default = new WildcardPatternMatcher(DefaultSingleWildcard, DefaultMultipleWildcard); #endregion Public Fields #region Private Fields private readonly char _multiple; private readonly char _single; private string[] _patterns; #endregion Private Fields #region Public Constructors public WildcardPatternMatcher() : this(DefaultSingleWildcard, DefaultMultipleWildcard) { } public WildcardPatternMatcher(char single, char multiple) { _single = single; _multiple = multiple; } public WildcardPatternMatcher(char single, char multiple, string pattern) : this(single, multiple, new[] { pattern }) { } public WildcardPatternMatcher(string pattern) : this(new[] { pattern }) { } public WildcardPatternMatcher(string[] patterns) : this(DefaultSingleWildcard, DefaultMultipleWildcard, patterns) { } public WildcardPatternMatcher(ICollection<string> patterns) : this(DefaultSingleWildcard, DefaultMultipleWildcard) { _patterns = new string[patterns.Count]; patterns.CopyTo(_patterns, 0); } public WildcardPatternMatcher(char single, char multiple, string[] patterns) : this(single, multiple) { _patterns = patterns; } #endregion Public Constructors #region Public Properties public string[] Patterns { get => _patterns; set => _patterns = value; } #endregion Public Properties #region Public Methods public bool IsMatch(string input, string pattern) { return this.IsMatch(input, pattern, false, _single, _multiple); } public bool IsMatch(string input, string pattern, bool ignoreCase) { return this.IsMatch(input, pattern, ignoreCase, _single, _multiple); } public bool IsMatch(string input, string[] patterns) { return this.IsMatch(input, patterns, false); } public bool IsMatch(string input, string[] patterns, bool ignoreCase) { bool result; result = false; // ReSharper disable once ForCanBeConvertedToForeach for (int i = 0; i < patterns.Length; i++) { result = this.IsMatch(input, patterns[i], ignoreCase, _single, _multiple); if (result) { break; } } return result; } public bool IsMatch(string input) { return this.IsMatch(input, _patterns, false); } public bool IsMatch(string input, bool ignoreCase) { return this.IsMatch(input, _patterns, ignoreCase); } #endregion Public Methods #region Private Methods /// <summary> /// Tests whether specified string can be matched agains provided pattern string. Pattern may contain single- and multiple-replacing /// wildcard characters. /// </summary> /// <param name="input">String which is matched against the pattern.</param> /// <param name="pattern">Pattern against which string is matched.</param> /// <param name="singleWildcard">Character which can be used to replace any single character in input string.</param> /// <param name="multipleWildcard">Character which can be used to replace zero or more characters in input string.</param> /// <param name="ignoreCase"><c>true</c> if characters should be compared in a case-insensitive manner; otherwise <c>false</c>.</param> /// <returns>true if <paramref name="pattern"/> matches the string <paramref name="input"/>; otherwise false.</returns> private bool IsMatch(string input, string pattern, bool ignoreCase, char singleWildcard, char multipleWildcard) { int patternLength; int inputLength; int[] inputPosStack; int[] patternPosStack; bool[,] pointTested; int stackPos; int inputPos; int patternPos; bool matched; if (string.IsNullOrEmpty(input)) { throw new ArgumentNullException(nameof(input)); } if (string.IsNullOrEmpty(pattern)) { throw new ArgumentNullException(nameof(input)); } patternLength = pattern.Length; inputLength = input.Length; inputPosStack = new int[(inputLength + 1) * (patternLength + 1)]; // Stack containing input positions that should be tested for further matching patternPosStack = new int[inputPosStack.Length]; // Stack containing pattern positions that should be tested for further matching pointTested = new bool[inputLength + 1, patternLength + 1]; // Each true value indicates that input position vs. pattern position has been tested stackPos = -1; // Points to last occupied entry in stack; -1 indicates that stack is empty inputPos = 0; // Position in input matched up to the first multiple wildcard in pattern patternPos = 0; // Position in pattern matched up to the first multiple wildcard in pattern // by default, we have not made a match matched = false; // Match beginning of the string until first multiple wildcard in pattern while (inputPos < inputLength && patternPos < patternLength && pattern[patternPos] != multipleWildcard && (input[inputPos] == pattern[patternPos] || pattern[patternPos] == singleWildcard || (ignoreCase && char.IsLetter(input[patternPos]) && char.ToUpperInvariant(input[patternPos]) == char.ToUpperInvariant(pattern[patternPos])))) { inputPos++; patternPos++; } // Push this position to stack if it points to end of pattern or to a general wildcard if (patternPos == patternLength || pattern[patternPos] == multipleWildcard) { pointTested[inputPos, patternPos] = true; inputPosStack[++stackPos] = inputPos; patternPosStack[stackPos] = patternPos; } // Repeat matching until either string is matched against the pattern or no more parts remain on stack to test while (stackPos >= 0 && !matched) { inputPos = inputPosStack[stackPos]; // Pop input and pattern positions from stack patternPos = patternPosStack[stackPos--]; // Matching will succeed if rest of the input string matches rest of the pattern if (inputPos == inputLength) { if (patternPos == patternLength) { matched = true; // Reached end of both pattern and input string, hence matching is successful } else if (patternPos == patternLength - 1 && pattern[patternLength - 1] == '*') { // Reached the end of the input, and the last part of the pattern is a multiple wildcard matched = true; } } else { // First character in next pattern block is guaranteed to be multiple wildcard // So skip it and search for all matches in value string until next multiple wildcard character is reached in pattern for (int curInputStart = inputPos; curInputStart < inputLength; curInputStart++) { int curInputPos = curInputStart; int curPatternPos = patternPos + 1; if (curPatternPos == patternLength) { // Pattern ends with multiple wildcard, hence rest of the input string is matched with that character curInputPos = inputLength; } else { while (curInputPos < inputLength && curPatternPos < patternLength && pattern[curPatternPos] != multipleWildcard && (input[curInputPos] == pattern[curPatternPos] || pattern[curPatternPos] == singleWildcard || (ignoreCase && char.IsLetter(input[curInputPos]) && char.ToUpperInvariant(input[curInputPos]) == char.ToUpperInvariant(pattern[curPatternPos])))) { curInputPos++; curPatternPos++; } } // If we have reached next multiple wildcard character in pattern without breaking the matching sequence, then we have another candidate for full match // This candidate should be pushed to stack for further processing // At the same time, pair (input position, pattern position) will be marked as tested, so that it will not be pushed to stack later again if (((curPatternPos == patternLength && curInputPos == inputLength) || (curPatternPos < patternLength && pattern[curPatternPos] == multipleWildcard)) && !pointTested[curInputPos, curPatternPos]) { pointTested[curInputPos, curPatternPos] = true; inputPosStack[++stackPos] = curInputPos; patternPosStack[stackPos] = curPatternPos; } } } } return matched; } #endregion Private Methods } }
// 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.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyDate { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class DateExtensions { /// <summary> /// Get null date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetNull(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get null date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetNullAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Get invalid date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetInvalidDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetInvalidDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetInvalidDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetInvalidDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Get overflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetOverflowDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetOverflowDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetOverflowDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetOverflowDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Get underflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetUnderflowDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetUnderflowDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetUnderflowDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetUnderflowDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Put max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dateBody'> /// </param> public static void PutMaxDate(this IDate operations, DateTime? dateBody) { Task.Factory.StartNew(s => ((IDate)s).PutMaxDateAsync(dateBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dateBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMaxDateAsync( this IDate operations, DateTime? dateBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMaxDateWithHttpMessagesAsync(dateBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetMaxDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetMaxDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetMaxDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetMaxDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Put min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dateBody'> /// </param> public static void PutMinDate(this IDate operations, DateTime? dateBody) { Task.Factory.StartNew(s => ((IDate)s).PutMinDateAsync(dateBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dateBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMinDateAsync( this IDate operations, DateTime? dateBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMinDateWithHttpMessagesAsync(dateBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetMinDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetMinDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetMinDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetMinDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Adxstudio.Xrm.Mapping; namespace Adxstudio.Xrm.Web.UI.WebControls { /// <summary> /// Renders a Bing map. /// </summary> [Description("Renders a Bing map")] [ToolboxData(@"<{0}:BingMap runat=""server""></{0}:BingMap>")] [DefaultProperty("")] public class BingMap : CompositeControl { /// <summary> /// Credentials for Bing maps. /// </summary> [Description("Bing maps credentials.")] [DefaultValue("")] public string Credentials { get { return ((string)ViewState["Credentials"]) ?? string.Empty; } set { ViewState["Credentials"] = value; } } public MappingFieldMetadataCollection MappingFieldCollection { get; set; } /// <summary> /// Script files to be included /// </summary> protected virtual string[] ScriptIncludes { get { var list = new List<string>(); var scripts = new[] { "https://www.bing.com/api/maps/mapcontrol", "~/xrm-adx/js/bingmap.js" }; list.AddRange(scripts); return list.ToArray(); } } protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Div; } } protected override void CreateChildControls() { Controls.Clear(); RegisterClientSideDependencies(this); ClientIDMode = ClientIDMode.Static; //here we will add hidden input fields containing the values of the MappingFieldsMetadataCollection var latitudeFieldName = new HiddenField() { Value = MappingFieldCollection.LatitudeFieldName ?? "adx_latitude", ID = "geolocation_latitudefieldname" }; Controls.Add(latitudeFieldName); var longitudeFieldName = new HiddenField() { Value = MappingFieldCollection.LongitudeFieldName ?? "adx_longitude", ID = "geolocation_longitudefieldname" }; Controls.Add(longitudeFieldName); var addressLineFieldName = new HiddenField() { Value = MappingFieldCollection.AddressLineFieldName ?? "adx_location_addressline", ID = "geolocation_addresslinefieldname" }; Controls.Add(addressLineFieldName); var neighbourhoodFieldName = new HiddenField() { Value = MappingFieldCollection.NeightbourhoodFieldName ?? "adx_location_neighorhood", ID = "geolocation_neighbourhoodfieldname" }; Controls.Add(neighbourhoodFieldName); var cityFieldName = new HiddenField() { Value = MappingFieldCollection.CityFieldName ?? "adx_location_city", ID = "geolocation_cityfieldname" }; Controls.Add(cityFieldName); var countyFieldName = new HiddenField() { Value = MappingFieldCollection.CountyFieldName ?? "adx_location_county", ID = "geolocation_countyfieldname" }; Controls.Add(countyFieldName); var stateFieldName = new HiddenField() { Value = MappingFieldCollection.StateProvinceFieldName ?? "adx_location_stateorprovince", ID = "geolocation_statefieldname" }; Controls.Add(stateFieldName); var countryFieldName = new HiddenField() { Value = MappingFieldCollection.CountryFieldName ?? "adx_location_country", ID = "geolocation_countryfieldname" }; Controls.Add(countryFieldName); var postalCodeFieldName = new HiddenField() { Value = MappingFieldCollection.PostalCodeFieldName ?? "adx_location_postalcode", ID = "geolocation_portalcodefieldname" }; Controls.Add(postalCodeFieldName); var formattedLocationFieldName = new HiddenField() { Value = MappingFieldCollection.FormattedLocationFieldName ?? "adx_location", ID = "geolocation_formattedlocationfieldname" }; Controls.Add(formattedLocationFieldName); var bingMapsRestUrl = new HiddenField() { Value = MappingFieldCollection.BingMapsURL, ID = "bingmapsresturl" }; Controls.Add(bingMapsRestUrl); var bingMapsCredentials = new HiddenField() { Value = MappingFieldCollection.BingMapsCredentials, ID = "bingmapscredentials" }; Controls.Add(bingMapsCredentials); } /// <summary> /// Add the <see cref="ScriptIncludes"/> to the <see cref="ScriptManager"/> if one exists. /// </summary> /// <param name="control"></param> protected virtual void RegisterClientSideDependencies(Control control) { foreach (var script in ScriptIncludes) { if (string.IsNullOrWhiteSpace(script)) { continue; } var scriptManager = ScriptManager.GetCurrent(control.Page); if (scriptManager == null) { continue; } var absolutePath = script.StartsWith("http", true, CultureInfo.InvariantCulture) ? script : VirtualPathUtility.ToAbsolute(script); scriptManager.Scripts.Add(new ScriptReference(absolutePath)); } } } }
namespace VersionOne.ServiceHost.ConfigurationTool.UI.Controls { public partial class ClearQuestPageControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.grpConnection = new System.Windows.Forms.GroupBox(); this.lblConnectionValidation = new System.Windows.Forms.Label(); this.btnValidate = new System.Windows.Forms.Button(); this.txtPassword = new System.Windows.Forms.TextBox(); this.lblPassword = new System.Windows.Forms.Label(); this.txtUserName = new System.Windows.Forms.TextBox(); this.lblUserName = new System.Windows.Forms.Label(); this.txtConnectionName = new System.Windows.Forms.TextBox(); this.lblUrl = new System.Windows.Forms.Label(); this.lblDatabase = new System.Windows.Forms.Label(); this.txtDatabase = new System.Windows.Forms.TextBox(); this.grpMandatoryFields = new System.Windows.Forms.GroupBox(); this.btnDelete = new System.Windows.Forms.Button(); this.grdMandatoryFields = new System.Windows.Forms.DataGridView(); this.colName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colValue = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.txtSubmitedToAction = new System.Windows.Forms.TextBox(); this.txtWaitedSubmit = new System.Windows.Forms.TextBox(); this.lblEntityType = new System.Windows.Forms.Label(); this.lblCloseAction = new System.Windows.Forms.Label(); this.lblSubmitedToState = new System.Windows.Forms.Label(); this.lblWaitedSubmitToV1State = new System.Windows.Forms.Label(); this.lblFieldId = new System.Windows.Forms.Label(); this.txtCloseAction = new System.Windows.Forms.TextBox(); this.txtSubmitedToState = new System.Windows.Forms.TextBox(); this.lblSubmitedToAction = new System.Windows.Forms.Label(); this.txtEntityType = new System.Windows.Forms.TextBox(); this.lblDefectTitle = new System.Windows.Forms.Label(); this.txtUrlTitle = new System.Windows.Forms.TextBox(); this.lblUrlTitle = new System.Windows.Forms.Label(); this.txtUrlTemplate = new System.Windows.Forms.TextBox(); this.lblUrlTempl = new System.Windows.Forms.Label(); this.cboSourceFieldValue = new System.Windows.Forms.ComboBox(); this.lblSourceFieldValue = new System.Windows.Forms.Label(); this.chkDisable = new System.Windows.Forms.CheckBox(); this.txtDescription = new System.Windows.Forms.TextBox(); this.txtOwnerLogin = new System.Windows.Forms.TextBox(); this.txtProjectName = new System.Windows.Forms.TextBox(); this.txtFieldId = new System.Windows.Forms.TextBox(); this.txtDefectTitle = new System.Windows.Forms.TextBox(); this.lblDescription = new System.Windows.Forms.Label(); this.lblOwnerLogin = new System.Windows.Forms.Label(); this.lblProjectName = new System.Windows.Forms.Label(); this.lblState = new System.Windows.Forms.Label(); this.lblModifyAction = new System.Windows.Forms.Label(); this.txtModifyAction = new System.Windows.Forms.TextBox(); this.txtState = new System.Windows.Forms.TextBox(); this.grpState = new System.Windows.Forms.GroupBox(); this.lblPollIntervalSuffix = new System.Windows.Forms.Label(); this.lblPollIntervalPrefix = new System.Windows.Forms.Label(); this.numIntervalMinutes = new System.Windows.Forms.NumericUpDown(); this.grpNativeFields = new System.Windows.Forms.GroupBox(); this.lblPriority = new System.Windows.Forms.Label(); this.txtPriorityField = new System.Windows.Forms.TextBox(); this.bsMandatoryFields = new System.Windows.Forms.BindingSource(this.components); this.grpVersionOne = new System.Windows.Forms.GroupBox(); this.tcData = new System.Windows.Forms.TabControl(); this.tpSettings = new System.Windows.Forms.TabPage(); this.ccScrollabablePanel = new System.Windows.Forms.ContainerControl(); this.tpMappings = new System.Windows.Forms.TabPage(); this.grpPriorityMappings = new System.Windows.Forms.GroupBox(); this.btnDeletePriorityMapping = new System.Windows.Forms.Button(); this.grdPriorityMappings = new System.Windows.Forms.DataGridView(); this.colVersionOnePriority = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.colClearQuestPriorityName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.grpProjectMappings = new System.Windows.Forms.GroupBox(); this.btnDeleteProjectMapping = new System.Windows.Forms.Button(); this.grdProjectMappings = new System.Windows.Forms.DataGridView(); this.colVersionOneProjectId = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.colClearQuestProject = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.bsProjectMappings = new System.Windows.Forms.BindingSource(this.components); this.bsPriorityMappings = new System.Windows.Forms.BindingSource(this.components); this.grpConnection.SuspendLayout(); this.grpMandatoryFields.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.grdMandatoryFields)).BeginInit(); this.grpState.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numIntervalMinutes)).BeginInit(); this.grpNativeFields.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.bsMandatoryFields)).BeginInit(); this.grpVersionOne.SuspendLayout(); this.tcData.SuspendLayout(); this.tpSettings.SuspendLayout(); this.ccScrollabablePanel.SuspendLayout(); this.tpMappings.SuspendLayout(); this.grpPriorityMappings.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.grdPriorityMappings)).BeginInit(); this.grpProjectMappings.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.grdProjectMappings)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bsProjectMappings)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bsPriorityMappings)).BeginInit(); this.SuspendLayout(); // // grpConnection // this.grpConnection.Controls.Add(this.lblConnectionValidation); this.grpConnection.Controls.Add(this.btnValidate); this.grpConnection.Controls.Add(this.txtPassword); this.grpConnection.Controls.Add(this.lblPassword); this.grpConnection.Controls.Add(this.txtUserName); this.grpConnection.Controls.Add(this.lblUserName); this.grpConnection.Controls.Add(this.txtConnectionName); this.grpConnection.Controls.Add(this.lblUrl); this.grpConnection.Controls.Add(this.lblDatabase); this.grpConnection.Controls.Add(this.txtDatabase); this.grpConnection.Location = new System.Drawing.Point(6, 3); this.grpConnection.Name = "grpConnection"; this.grpConnection.Size = new System.Drawing.Size(495, 108); this.grpConnection.TabIndex = 1; this.grpConnection.TabStop = false; this.grpConnection.Text = "Connection"; // // lblConnectionValidation // this.lblConnectionValidation.AutoSize = true; this.lblConnectionValidation.Location = new System.Drawing.Point(108, 80); this.lblConnectionValidation.Name = "lblConnectionValidation"; this.lblConnectionValidation.Size = new System.Drawing.Size(137, 13); this.lblConnectionValidation.TabIndex = 8; this.lblConnectionValidation.Text = "Connection validation result"; this.lblConnectionValidation.Visible = false; // // btnValidate // this.btnValidate.Location = new System.Drawing.Point(367, 73); this.btnValidate.Name = "btnValidate"; this.btnValidate.Size = new System.Drawing.Size(87, 27); this.btnValidate.TabIndex = 9; this.btnValidate.Text = "Validate"; this.btnValidate.UseVisualStyleBackColor = true; // // txtPassword // this.txtPassword.Location = new System.Drawing.Point(339, 43); this.txtPassword.Name = "txtPassword"; this.txtPassword.Size = new System.Drawing.Size(115, 20); this.txtPassword.TabIndex = 7; // // lblPassword // this.lblPassword.AutoSize = true; this.lblPassword.Location = new System.Drawing.Point(278, 46); this.lblPassword.Name = "lblPassword"; this.lblPassword.Size = new System.Drawing.Size(53, 13); this.lblPassword.TabIndex = 6; this.lblPassword.Text = "Password"; // // txtUserName // this.txtUserName.Location = new System.Drawing.Point(111, 43); this.txtUserName.Name = "txtUserName"; this.txtUserName.Size = new System.Drawing.Size(115, 20); this.txtUserName.TabIndex = 5; // // lblUserName // this.lblUserName.AutoSize = true; this.lblUserName.Location = new System.Drawing.Point(17, 46); this.lblUserName.Name = "lblUserName"; this.lblUserName.Size = new System.Drawing.Size(55, 13); this.lblUserName.TabIndex = 4; this.lblUserName.Text = "Username"; // // txtConnectionName // this.txtConnectionName.Location = new System.Drawing.Point(111, 17); this.txtConnectionName.Name = "txtConnectionName"; this.txtConnectionName.Size = new System.Drawing.Size(115, 20); this.txtConnectionName.TabIndex = 1; // // lblUrl // this.lblUrl.AutoSize = true; this.lblUrl.Location = new System.Drawing.Point(17, 20); this.lblUrl.Name = "lblUrl"; this.lblUrl.Size = new System.Drawing.Size(92, 13); this.lblUrl.TabIndex = 0; this.lblUrl.Text = "Connection Name"; // // lblDatabase // this.lblDatabase.AutoSize = true; this.lblDatabase.Location = new System.Drawing.Point(278, 20); this.lblDatabase.Name = "lblDatabase"; this.lblDatabase.Size = new System.Drawing.Size(53, 13); this.lblDatabase.TabIndex = 2; this.lblDatabase.Text = "Database"; // // txtDatabase // this.txtDatabase.AcceptsReturn = true; this.txtDatabase.Location = new System.Drawing.Point(339, 17); this.txtDatabase.Name = "txtDatabase"; this.txtDatabase.Size = new System.Drawing.Size(115, 20); this.txtDatabase.TabIndex = 3; // // grpMandatoryFields // this.grpMandatoryFields.Controls.Add(this.btnDelete); this.grpMandatoryFields.Controls.Add(this.grdMandatoryFields); this.grpMandatoryFields.Location = new System.Drawing.Point(6, 392); this.grpMandatoryFields.Name = "grpMandatoryFields"; this.grpMandatoryFields.Size = new System.Drawing.Size(495, 116); this.grpMandatoryFields.TabIndex = 4; this.grpMandatoryFields.TabStop = false; this.grpMandatoryFields.Text = "ClearQuest Mandatory Close Fields"; // // btnDelete // this.btnDelete.Location = new System.Drawing.Point(367, 19); this.btnDelete.Name = "btnDelete"; this.btnDelete.Size = new System.Drawing.Size(87, 27); this.btnDelete.TabIndex = 1; this.btnDelete.Text = "Delete"; this.btnDelete.UseVisualStyleBackColor = true; // // grdMandatoryFields // this.grdMandatoryFields.AllowUserToResizeColumns = false; this.grdMandatoryFields.AllowUserToResizeRows = false; this.grdMandatoryFields.BorderStyle = System.Windows.Forms.BorderStyle.None; this.grdMandatoryFields.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.grdMandatoryFields.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colName, this.colValue}); this.grdMandatoryFields.Location = new System.Drawing.Point(19, 19); this.grdMandatoryFields.MultiSelect = false; this.grdMandatoryFields.Name = "grdMandatoryFields"; this.grdMandatoryFields.Size = new System.Drawing.Size(243, 91); this.grdMandatoryFields.TabIndex = 0; // // colName // this.colName.DataPropertyName = "Name"; this.colName.HeaderText = "Name"; this.colName.Name = "colName"; // // colValue // this.colValue.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colValue.DataPropertyName = "Value"; this.colValue.HeaderText = "Value"; this.colValue.Name = "colValue"; // // txtSubmitedToAction // this.txtSubmitedToAction.Location = new System.Drawing.Point(145, 71); this.txtSubmitedToAction.Name = "txtSubmitedToAction"; this.txtSubmitedToAction.Size = new System.Drawing.Size(101, 20); this.txtSubmitedToAction.TabIndex = 5; // // txtWaitedSubmit // this.txtWaitedSubmit.Location = new System.Drawing.Point(145, 19); this.txtWaitedSubmit.Name = "txtWaitedSubmit"; this.txtWaitedSubmit.Size = new System.Drawing.Size(309, 20); this.txtWaitedSubmit.TabIndex = 1; // // lblEntityType // this.lblEntityType.AutoSize = true; this.lblEntityType.Location = new System.Drawing.Point(17, 25); this.lblEntityType.Name = "lblEntityType"; this.lblEntityType.Size = new System.Drawing.Size(74, 13); this.lblEntityType.TabIndex = 0; this.lblEntityType.Text = "CQ Entity type"; // // lblCloseAction // this.lblCloseAction.AutoSize = true; this.lblCloseAction.Location = new System.Drawing.Point(296, 74); this.lblCloseAction.Name = "lblCloseAction"; this.lblCloseAction.Size = new System.Drawing.Size(65, 13); this.lblCloseAction.TabIndex = 6; this.lblCloseAction.Text = "Close action"; // // lblSubmitedToState // this.lblSubmitedToState.AutoSize = true; this.lblSubmitedToState.Location = new System.Drawing.Point(16, 48); this.lblSubmitedToState.Name = "lblSubmitedToState"; this.lblSubmitedToState.Size = new System.Drawing.Size(118, 13); this.lblSubmitedToState.TabIndex = 2; this.lblSubmitedToState.Text = "Already Submitted state"; // // lblWaitedSubmitToV1State // this.lblWaitedSubmitToV1State.AutoSize = true; this.lblWaitedSubmitToV1State.Location = new System.Drawing.Point(17, 22); this.lblWaitedSubmitToV1State.Name = "lblWaitedSubmitToV1State"; this.lblWaitedSubmitToV1State.Size = new System.Drawing.Size(108, 13); this.lblWaitedSubmitToV1State.TabIndex = 0; this.lblWaitedSubmitToV1State.Text = "Awaiting Submit state"; // // lblFieldId // this.lblFieldId.AutoSize = true; this.lblFieldId.Location = new System.Drawing.Point(16, 51); this.lblFieldId.Name = "lblFieldId"; this.lblFieldId.Size = new System.Drawing.Size(40, 13); this.lblFieldId.TabIndex = 2; this.lblFieldId.Text = "ID field"; // // txtCloseAction // this.txtCloseAction.Location = new System.Drawing.Point(369, 71); this.txtCloseAction.Name = "txtCloseAction"; this.txtCloseAction.Size = new System.Drawing.Size(85, 20); this.txtCloseAction.TabIndex = 7; // // txtSubmitedToState // this.txtSubmitedToState.AcceptsTab = true; this.txtSubmitedToState.Location = new System.Drawing.Point(145, 45); this.txtSubmitedToState.Name = "txtSubmitedToState"; this.txtSubmitedToState.Size = new System.Drawing.Size(309, 20); this.txtSubmitedToState.TabIndex = 3; // // lblSubmitedToAction // this.lblSubmitedToAction.AutoSize = true; this.lblSubmitedToAction.Location = new System.Drawing.Point(17, 74); this.lblSubmitedToAction.Name = "lblSubmitedToAction"; this.lblSubmitedToAction.Size = new System.Drawing.Size(71, 13); this.lblSubmitedToAction.TabIndex = 4; this.lblSubmitedToAction.Text = "Submit action"; // // txtEntityType // this.txtEntityType.AcceptsReturn = true; this.txtEntityType.AcceptsTab = true; this.txtEntityType.Location = new System.Drawing.Point(105, 22); this.txtEntityType.Name = "txtEntityType"; this.txtEntityType.Size = new System.Drawing.Size(105, 20); this.txtEntityType.TabIndex = 1; // // lblDefectTitle // this.lblDefectTitle.AutoSize = true; this.lblDefectTitle.Location = new System.Drawing.Point(16, 77); this.lblDefectTitle.Name = "lblDefectTitle"; this.lblDefectTitle.Size = new System.Drawing.Size(84, 13); this.lblDefectTitle.TabIndex = 4; this.lblDefectTitle.Text = "Defect Title field"; // // txtUrlTitle // this.txtUrlTitle.Location = new System.Drawing.Point(111, 72); this.txtUrlTitle.Name = "txtUrlTitle"; this.txtUrlTitle.Size = new System.Drawing.Size(343, 20); this.txtUrlTitle.TabIndex = 5; // // lblUrlTitle // this.lblUrlTitle.AutoSize = true; this.lblUrlTitle.Location = new System.Drawing.Point(16, 75); this.lblUrlTitle.Name = "lblUrlTitle"; this.lblUrlTitle.Size = new System.Drawing.Size(52, 13); this.lblUrlTitle.TabIndex = 4; this.lblUrlTitle.Text = "URL Title"; // // txtUrlTemplate // this.txtUrlTemplate.Location = new System.Drawing.Point(111, 46); this.txtUrlTemplate.Name = "txtUrlTemplate"; this.txtUrlTemplate.Size = new System.Drawing.Size(343, 20); this.txtUrlTemplate.TabIndex = 3; // // lblUrlTempl // this.lblUrlTempl.AutoSize = true; this.lblUrlTempl.Location = new System.Drawing.Point(16, 49); this.lblUrlTempl.Name = "lblUrlTempl"; this.lblUrlTempl.Size = new System.Drawing.Size(76, 13); this.lblUrlTempl.TabIndex = 2; this.lblUrlTempl.Text = "URL Template"; // // cboSourceFieldValue // this.cboSourceFieldValue.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboSourceFieldValue.FormattingEnabled = true; this.cboSourceFieldValue.Location = new System.Drawing.Point(111, 19); this.cboSourceFieldValue.Name = "cboSourceFieldValue"; this.cboSourceFieldValue.Size = new System.Drawing.Size(343, 21); this.cboSourceFieldValue.TabIndex = 1; // // lblSourceFieldValue // this.lblSourceFieldValue.AutoSize = true; this.lblSourceFieldValue.Location = new System.Drawing.Point(17, 22); this.lblSourceFieldValue.Name = "lblSourceFieldValue"; this.lblSourceFieldValue.Size = new System.Drawing.Size(41, 13); this.lblSourceFieldValue.TabIndex = 0; this.lblSourceFieldValue.Text = "Source"; // // chkDisable // this.chkDisable.AutoSize = true; this.chkDisable.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.chkDisable.Location = new System.Drawing.Point(397, 3); this.chkDisable.Name = "chkDisable"; this.chkDisable.Size = new System.Drawing.Size(67, 17); this.chkDisable.TabIndex = 0; this.chkDisable.Text = "Disabled"; this.chkDisable.UseVisualStyleBackColor = true; // // txtDescription // this.txtDescription.Location = new System.Drawing.Point(105, 100); this.txtDescription.Name = "txtDescription"; this.txtDescription.Size = new System.Drawing.Size(105, 20); this.txtDescription.TabIndex = 7; // // txtOwnerLogin // this.txtOwnerLogin.Location = new System.Drawing.Point(349, 48); this.txtOwnerLogin.Name = "txtOwnerLogin"; this.txtOwnerLogin.Size = new System.Drawing.Size(105, 20); this.txtOwnerLogin.TabIndex = 11; // // txtProjectName // this.txtProjectName.Location = new System.Drawing.Point(349, 22); this.txtProjectName.Name = "txtProjectName"; this.txtProjectName.Size = new System.Drawing.Size(105, 20); this.txtProjectName.TabIndex = 9; // // txtFieldId // this.txtFieldId.AcceptsTab = true; this.txtFieldId.Location = new System.Drawing.Point(105, 48); this.txtFieldId.Name = "txtFieldId"; this.txtFieldId.Size = new System.Drawing.Size(105, 20); this.txtFieldId.TabIndex = 3; // // txtDefectTitle // this.txtDefectTitle.Location = new System.Drawing.Point(105, 74); this.txtDefectTitle.Name = "txtDefectTitle"; this.txtDefectTitle.Size = new System.Drawing.Size(105, 20); this.txtDefectTitle.TabIndex = 5; // // lblDescription // this.lblDescription.AutoSize = true; this.lblDescription.Location = new System.Drawing.Point(17, 103); this.lblDescription.Name = "lblDescription"; this.lblDescription.Size = new System.Drawing.Size(82, 13); this.lblDescription.TabIndex = 6; this.lblDescription.Text = "Description field"; // // lblOwnerLogin // this.lblOwnerLogin.AutoSize = true; this.lblOwnerLogin.Location = new System.Drawing.Point(255, 51); this.lblOwnerLogin.Name = "lblOwnerLogin"; this.lblOwnerLogin.Size = new System.Drawing.Size(89, 13); this.lblOwnerLogin.TabIndex = 10; this.lblOwnerLogin.Text = "Owner Login field"; // // lblProjectName // this.lblProjectName.AutoSize = true; this.lblProjectName.Location = new System.Drawing.Point(255, 25); this.lblProjectName.Name = "lblProjectName"; this.lblProjectName.Size = new System.Drawing.Size(69, 13); this.lblProjectName.TabIndex = 8; this.lblProjectName.Text = "Project name"; // // lblState // this.lblState.AutoSize = true; this.lblState.Location = new System.Drawing.Point(255, 77); this.lblState.Name = "lblState"; this.lblState.Size = new System.Drawing.Size(54, 13); this.lblState.TabIndex = 12; this.lblState.Text = "State field"; // // lblModifyAction // this.lblModifyAction.AutoSize = true; this.lblModifyAction.Location = new System.Drawing.Point(17, 100); this.lblModifyAction.Name = "lblModifyAction"; this.lblModifyAction.Size = new System.Drawing.Size(70, 13); this.lblModifyAction.TabIndex = 8; this.lblModifyAction.Text = "Modify action"; // // txtModifyAction // this.txtModifyAction.Location = new System.Drawing.Point(145, 97); this.txtModifyAction.Name = "txtModifyAction"; this.txtModifyAction.Size = new System.Drawing.Size(309, 20); this.txtModifyAction.TabIndex = 9; // // txtState // this.txtState.AcceptsReturn = true; this.txtState.Location = new System.Drawing.Point(349, 74); this.txtState.Name = "txtState"; this.txtState.Size = new System.Drawing.Size(105, 20); this.txtState.TabIndex = 13; // // grpState // this.grpState.Controls.Add(this.lblWaitedSubmitToV1State); this.grpState.Controls.Add(this.lblPollIntervalSuffix); this.grpState.Controls.Add(this.lblSubmitedToState); this.grpState.Controls.Add(this.lblPollIntervalPrefix); this.grpState.Controls.Add(this.numIntervalMinutes); this.grpState.Controls.Add(this.lblCloseAction); this.grpState.Controls.Add(this.txtSubmitedToState); this.grpState.Controls.Add(this.lblSubmitedToAction); this.grpState.Controls.Add(this.txtWaitedSubmit); this.grpState.Controls.Add(this.txtCloseAction); this.grpState.Controls.Add(this.txtSubmitedToAction); this.grpState.Controls.Add(this.lblModifyAction); this.grpState.Controls.Add(this.txtModifyAction); this.grpState.Location = new System.Drawing.Point(6, 227); this.grpState.Name = "grpState"; this.grpState.Size = new System.Drawing.Size(495, 159); this.grpState.TabIndex = 3; this.grpState.TabStop = false; this.grpState.Text = "ClearQuest States and Actions"; // // lblPollIntervalSuffix // this.lblPollIntervalSuffix.AutoSize = true; this.lblPollIntervalSuffix.Location = new System.Drawing.Point(203, 131); this.lblPollIntervalSuffix.Name = "lblPollIntervalSuffix"; this.lblPollIntervalSuffix.Size = new System.Drawing.Size(43, 13); this.lblPollIntervalSuffix.TabIndex = 12; this.lblPollIntervalSuffix.Text = "minutes"; // // lblPollIntervalPrefix // this.lblPollIntervalPrefix.AutoSize = true; this.lblPollIntervalPrefix.Location = new System.Drawing.Point(17, 131); this.lblPollIntervalPrefix.Name = "lblPollIntervalPrefix"; this.lblPollIntervalPrefix.Size = new System.Drawing.Size(62, 13); this.lblPollIntervalPrefix.TabIndex = 10; this.lblPollIntervalPrefix.Text = "Poll Interval"; // // numIntervalMinutes // this.numIntervalMinutes.Location = new System.Drawing.Point(145, 129); this.numIntervalMinutes.Maximum = new decimal(new int[] { 1440, 0, 0, 0}); this.numIntervalMinutes.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.numIntervalMinutes.Name = "numIntervalMinutes"; this.numIntervalMinutes.Size = new System.Drawing.Size(52, 20); this.numIntervalMinutes.TabIndex = 11; this.numIntervalMinutes.Value = new decimal(new int[] { 30, 0, 0, 0}); // // grpNativeFields // this.grpNativeFields.Controls.Add(this.lblPriority); this.grpNativeFields.Controls.Add(this.txtPriorityField); this.grpNativeFields.Controls.Add(this.lblState); this.grpNativeFields.Controls.Add(this.lblEntityType); this.grpNativeFields.Controls.Add(this.txtEntityType); this.grpNativeFields.Controls.Add(this.txtDefectTitle); this.grpNativeFields.Controls.Add(this.txtState); this.grpNativeFields.Controls.Add(this.txtFieldId); this.grpNativeFields.Controls.Add(this.lblProjectName); this.grpNativeFields.Controls.Add(this.txtProjectName); this.grpNativeFields.Controls.Add(this.lblOwnerLogin); this.grpNativeFields.Controls.Add(this.lblFieldId); this.grpNativeFields.Controls.Add(this.lblDescription); this.grpNativeFields.Controls.Add(this.lblDefectTitle); this.grpNativeFields.Controls.Add(this.txtDescription); this.grpNativeFields.Controls.Add(this.txtOwnerLogin); this.grpNativeFields.Location = new System.Drawing.Point(6, 514); this.grpNativeFields.Name = "grpNativeFields"; this.grpNativeFields.Size = new System.Drawing.Size(495, 135); this.grpNativeFields.TabIndex = 5; this.grpNativeFields.TabStop = false; this.grpNativeFields.Text = "ClearQuest Entity and Attribute Names"; // // lblPriority // this.lblPriority.AutoSize = true; this.lblPriority.Location = new System.Drawing.Point(255, 103); this.lblPriority.Name = "lblPriority"; this.lblPriority.Size = new System.Drawing.Size(60, 13); this.lblPriority.TabIndex = 14; this.lblPriority.Text = "Priority field"; // // txtPriorityField // this.txtPriorityField.Location = new System.Drawing.Point(349, 100); this.txtPriorityField.Name = "txtPriorityField"; this.txtPriorityField.Size = new System.Drawing.Size(105, 20); this.txtPriorityField.TabIndex = 15; // // grpVersionOne // this.grpVersionOne.Controls.Add(this.lblUrlTempl); this.grpVersionOne.Controls.Add(this.txtUrlTemplate); this.grpVersionOne.Controls.Add(this.lblUrlTitle); this.grpVersionOne.Controls.Add(this.lblSourceFieldValue); this.grpVersionOne.Controls.Add(this.txtUrlTitle); this.grpVersionOne.Controls.Add(this.cboSourceFieldValue); this.grpVersionOne.Location = new System.Drawing.Point(6, 117); this.grpVersionOne.Name = "grpVersionOne"; this.grpVersionOne.Size = new System.Drawing.Size(495, 104); this.grpVersionOne.TabIndex = 2; this.grpVersionOne.TabStop = false; this.grpVersionOne.Text = "VersionOne Defect Attributes"; // // tcData // this.tcData.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tcData.Controls.Add(this.tpSettings); this.tcData.Controls.Add(this.tpMappings); this.tcData.Location = new System.Drawing.Point(0, 25); this.tcData.Name = "tcData"; this.tcData.SelectedIndex = 0; this.tcData.Size = new System.Drawing.Size(531, 688); this.tcData.TabIndex = 0; // // tpSettings // this.tpSettings.Controls.Add(this.ccScrollabablePanel); this.tpSettings.Location = new System.Drawing.Point(4, 22); this.tpSettings.Name = "tpSettings"; this.tpSettings.Padding = new System.Windows.Forms.Padding(3); this.tpSettings.Size = new System.Drawing.Size(523, 662); this.tpSettings.TabIndex = 0; this.tpSettings.Text = "Settings"; this.tpSettings.UseVisualStyleBackColor = true; // // ccScrollabablePanel // this.ccScrollabablePanel.AutoScroll = true; this.ccScrollabablePanel.AutoScrollMinSize = new System.Drawing.Size(550, 850); this.ccScrollabablePanel.BackColor = System.Drawing.SystemColors.Window; this.ccScrollabablePanel.Controls.Add(this.grpMandatoryFields); this.ccScrollabablePanel.Controls.Add(this.grpConnection); this.ccScrollabablePanel.Controls.Add(this.grpVersionOne); this.ccScrollabablePanel.Controls.Add(this.grpNativeFields); this.ccScrollabablePanel.Controls.Add(this.grpState); this.ccScrollabablePanel.Dock = System.Windows.Forms.DockStyle.Fill; this.ccScrollabablePanel.Location = new System.Drawing.Point(3, 3); this.ccScrollabablePanel.Name = "ccScrollabablePanel"; this.ccScrollabablePanel.Size = new System.Drawing.Size(517, 656); this.ccScrollabablePanel.TabIndex = 10; // // tpMappings // this.tpMappings.Controls.Add(this.grpPriorityMappings); this.tpMappings.Controls.Add(this.grpProjectMappings); this.tpMappings.Location = new System.Drawing.Point(4, 22); this.tpMappings.Name = "tpMappings"; this.tpMappings.Padding = new System.Windows.Forms.Padding(3); this.tpMappings.Size = new System.Drawing.Size(523, 662); this.tpMappings.TabIndex = 1; this.tpMappings.Text = "Project and Priority Mappings"; this.tpMappings.UseVisualStyleBackColor = true; // // grpPriorityMappings // this.grpPriorityMappings.Controls.Add(this.btnDeletePriorityMapping); this.grpPriorityMappings.Controls.Add(this.grdPriorityMappings); this.grpPriorityMappings.Location = new System.Drawing.Point(6, 251); this.grpPriorityMappings.Name = "grpPriorityMappings"; this.grpPriorityMappings.Size = new System.Drawing.Size(495, 236); this.grpPriorityMappings.TabIndex = 3; this.grpPriorityMappings.TabStop = false; this.grpPriorityMappings.Text = "Priority Mappings"; // // btnDeletePriorityMapping // this.btnDeletePriorityMapping.Image = global::VersionOne.ServiceHost.ConfigurationTool.Resources.DeleteIcon; this.btnDeletePriorityMapping.Location = new System.Drawing.Point(322, 195); this.btnDeletePriorityMapping.Name = "btnDeletePriorityMapping"; this.btnDeletePriorityMapping.Size = new System.Drawing.Size(132, 26); this.btnDeletePriorityMapping.TabIndex = 1; this.btnDeletePriorityMapping.Text = "Delete selected row"; this.btnDeletePriorityMapping.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.btnDeletePriorityMapping.UseVisualStyleBackColor = true; // // grdPriorityMappings // this.grdPriorityMappings.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.grdPriorityMappings.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colVersionOnePriority, this.colClearQuestPriorityName}); this.grdPriorityMappings.Location = new System.Drawing.Point(15, 20); this.grdPriorityMappings.MultiSelect = false; this.grdPriorityMappings.Name = "grdPriorityMappings"; this.grdPriorityMappings.Size = new System.Drawing.Size(439, 169); this.grdPriorityMappings.TabIndex = 0; // // colVersionOnePriority // this.colVersionOnePriority.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colVersionOnePriority.DataPropertyName = "VersionOnePriorityId"; this.colVersionOnePriority.HeaderText = "VersionOne Priority"; this.colVersionOnePriority.MinimumWidth = 100; this.colVersionOnePriority.Name = "colVersionOnePriority"; // // colClearQuestPriorityName // this.colClearQuestPriorityName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colClearQuestPriorityName.DataPropertyName = "ClearQuestPriorityName"; this.colClearQuestPriorityName.HeaderText = "ClearQuest Priority"; this.colClearQuestPriorityName.MinimumWidth = 100; this.colClearQuestPriorityName.Name = "colClearQuestPriorityName"; // // grpProjectMappings // this.grpProjectMappings.Controls.Add(this.btnDeleteProjectMapping); this.grpProjectMappings.Controls.Add(this.grdProjectMappings); this.grpProjectMappings.Location = new System.Drawing.Point(6, 9); this.grpProjectMappings.Name = "grpProjectMappings"; this.grpProjectMappings.Size = new System.Drawing.Size(495, 236); this.grpProjectMappings.TabIndex = 2; this.grpProjectMappings.TabStop = false; this.grpProjectMappings.Text = "Project Mappings"; // // btnDeleteProjectMapping // this.btnDeleteProjectMapping.Image = global::VersionOne.ServiceHost.ConfigurationTool.Resources.DeleteIcon; this.btnDeleteProjectMapping.Location = new System.Drawing.Point(322, 195); this.btnDeleteProjectMapping.Name = "btnDeleteProjectMapping"; this.btnDeleteProjectMapping.Size = new System.Drawing.Size(132, 26); this.btnDeleteProjectMapping.TabIndex = 1; this.btnDeleteProjectMapping.Text = "Delete selected row"; this.btnDeleteProjectMapping.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.btnDeleteProjectMapping.UseVisualStyleBackColor = true; // // grdProjectMappings // this.grdProjectMappings.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.grdProjectMappings.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colVersionOneProjectId, this.colClearQuestProject}); this.grdProjectMappings.Location = new System.Drawing.Point(15, 20); this.grdProjectMappings.MultiSelect = false; this.grdProjectMappings.Name = "grdProjectMappings"; this.grdProjectMappings.Size = new System.Drawing.Size(439, 169); this.grdProjectMappings.TabIndex = 0; // // colVersionOneProjectId // this.colVersionOneProjectId.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colVersionOneProjectId.DataPropertyName = "VersionOneProjectToken"; this.colVersionOneProjectId.HeaderText = "VersionOne Project"; this.colVersionOneProjectId.MinimumWidth = 100; this.colVersionOneProjectId.Name = "colVersionOneProjectId"; // // colClearQuestProject // this.colClearQuestProject.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colClearQuestProject.DataPropertyName = "ClearQuestProjectName"; this.colClearQuestProject.HeaderText = "ClearQuest Project"; this.colClearQuestProject.MinimumWidth = 100; this.colClearQuestProject.Name = "colClearQuestProject"; // // ClearQuestPageControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; this.Controls.Add(this.tcData); this.Controls.Add(this.chkDisable); this.Name = "ClearQuestPageControl"; this.Size = new System.Drawing.Size(534, 716); this.grpConnection.ResumeLayout(false); this.grpConnection.PerformLayout(); this.grpMandatoryFields.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.grdMandatoryFields)).EndInit(); this.grpState.ResumeLayout(false); this.grpState.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numIntervalMinutes)).EndInit(); this.grpNativeFields.ResumeLayout(false); this.grpNativeFields.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.bsMandatoryFields)).EndInit(); this.grpVersionOne.ResumeLayout(false); this.grpVersionOne.PerformLayout(); this.tcData.ResumeLayout(false); this.tpSettings.ResumeLayout(false); this.ccScrollabablePanel.ResumeLayout(false); this.tpMappings.ResumeLayout(false); this.grpPriorityMappings.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.grdPriorityMappings)).EndInit(); this.grpProjectMappings.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.grdProjectMappings)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bsProjectMappings)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bsPriorityMappings)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox grpConnection; private System.Windows.Forms.Button btnValidate; private System.Windows.Forms.TextBox txtPassword; private System.Windows.Forms.Label lblPassword; private System.Windows.Forms.TextBox txtUserName; private System.Windows.Forms.Label lblUserName; private System.Windows.Forms.TextBox txtConnectionName; private System.Windows.Forms.Label lblUrl; private System.Windows.Forms.GroupBox grpMandatoryFields; private System.Windows.Forms.TextBox txtWaitedSubmit; private System.Windows.Forms.Label lblCloseAction; private System.Windows.Forms.Label lblSubmitedToState; private System.Windows.Forms.Label lblWaitedSubmitToV1State; private System.Windows.Forms.TextBox txtSubmitedToAction; private System.Windows.Forms.Label lblEntityType; private System.Windows.Forms.TextBox txtUrlTitle; private System.Windows.Forms.Label lblUrlTitle; private System.Windows.Forms.TextBox txtUrlTemplate; private System.Windows.Forms.Label lblUrlTempl; private System.Windows.Forms.TextBox txtSubmitedToState; private System.Windows.Forms.Label lblSubmitedToAction; private System.Windows.Forms.TextBox txtEntityType; private System.Windows.Forms.Label lblDefectTitle; private System.Windows.Forms.Label lblSourceFieldValue; private System.Windows.Forms.CheckBox chkDisable; private System.Windows.Forms.ComboBox cboSourceFieldValue; private System.Windows.Forms.Label lblConnectionValidation; private System.Windows.Forms.Label lblDatabase; private System.Windows.Forms.TextBox txtDatabase; private System.Windows.Forms.Label lblFieldId; private System.Windows.Forms.TextBox txtCloseAction; private System.Windows.Forms.TextBox txtDescription; private System.Windows.Forms.TextBox txtOwnerLogin; private System.Windows.Forms.TextBox txtProjectName; private System.Windows.Forms.TextBox txtFieldId; private System.Windows.Forms.TextBox txtDefectTitle; private System.Windows.Forms.Label lblDescription; private System.Windows.Forms.Label lblOwnerLogin; private System.Windows.Forms.Label lblProjectName; private System.Windows.Forms.Label lblState; private System.Windows.Forms.Label lblModifyAction; private System.Windows.Forms.TextBox txtModifyAction; private System.Windows.Forms.TextBox txtState; private System.Windows.Forms.GroupBox grpState; private System.Windows.Forms.GroupBox grpNativeFields; private System.Windows.Forms.BindingSource bsMandatoryFields; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.DataGridView grdMandatoryFields; private System.Windows.Forms.Label lblPollIntervalSuffix; private System.Windows.Forms.Label lblPollIntervalPrefix; private System.Windows.Forms.NumericUpDown numIntervalMinutes; private System.Windows.Forms.GroupBox grpVersionOne; private System.Windows.Forms.Label lblPriority; private System.Windows.Forms.TextBox txtPriorityField; private System.Windows.Forms.TabControl tcData; private System.Windows.Forms.TabPage tpSettings; private System.Windows.Forms.TabPage tpMappings; private System.Windows.Forms.GroupBox grpPriorityMappings; private System.Windows.Forms.Button btnDeletePriorityMapping; private System.Windows.Forms.DataGridView grdPriorityMappings; private System.Windows.Forms.GroupBox grpProjectMappings; private System.Windows.Forms.Button btnDeleteProjectMapping; private System.Windows.Forms.DataGridView grdProjectMappings; private System.Windows.Forms.BindingSource bsProjectMappings; private System.Windows.Forms.BindingSource bsPriorityMappings; private System.Windows.Forms.DataGridViewComboBoxColumn colVersionOnePriority; private System.Windows.Forms.DataGridViewTextBoxColumn colClearQuestPriorityName; private System.Windows.Forms.DataGridViewComboBoxColumn colVersionOneProjectId; private System.Windows.Forms.DataGridViewTextBoxColumn colClearQuestProject; private System.Windows.Forms.ContainerControl ccScrollabablePanel; private System.Windows.Forms.DataGridViewTextBoxColumn colName; private System.Windows.Forms.DataGridViewTextBoxColumn colValue; } }
using EdiEngine.Common.Enums; using EdiEngine.Common.Definitions; using EdiEngine.Standards.X12_004010.Segments; namespace EdiEngine.Standards.X12_004010.Maps { public class M_143 : MapLoop { public M_143() : base(null) { Content.AddRange(new MapBaseEntity[] { new BGN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N1(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 }, new L_LIN(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 }, }); } //1000 public class L_N1 : MapLoop { public L_N1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, }); } } //2000 public class L_LIN : MapLoop { public L_LIN(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LIN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new LOC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new CID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_PRR(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_SLN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2100 public class L_N1_1 : MapLoop { public L_N1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2200 public class L_PRR : MapLoop { public L_PRR(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PRR() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N9(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_REP(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_PRT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_ITA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2210 public class L_N9 : MapLoop { public L_N9(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2220 public class L_REP : MapLoop { public L_REP(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new REP() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_N9_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2221 public class L_N9_1 : MapLoop { public L_N9_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2230 public class L_PRT : MapLoop { public L_PRT(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PRT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, }); } } //2240 public class L_ITA : MapLoop { public L_ITA(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new ITA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2300 public class L_SLN : MapLoop { public L_SLN(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SLN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new LOC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new L_N1_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_PRR_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2310 public class L_N1_2 : MapLoop { public L_N1_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, }); } } //2320 public class L_PRR_1 : MapLoop { public L_PRR_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PRR() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_REP_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_PRT_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_ITA_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2321 public class L_REP_1 : MapLoop { public L_REP_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new REP() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2322 public class L_PRT_1 : MapLoop { public L_PRT_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PRT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, }); } } //2323 public class L_ITA_1 : MapLoop { public L_ITA_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new ITA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Windows.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; using Roslyn.Test.EditorUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces { public partial class TestWorkspaceFactory { /// <summary> /// This place-holder value is used to set a project's file path to be null. It was explicitly chosen to be /// convoluted to avoid any accidental usage (e.g., what if I really wanted FilePath to be the string "null"?), /// obvious to anybody debugging that it is a special value, and invalid as an actual file path. /// </summary> public const string NullFilePath = "NullFilePath::{AFA13775-BB7D-4020-9E58-C68CF43D8A68}"; private class TestDocumentationProvider : DocumentationProvider { protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken)) { return string.Format("<member name='{0}'><summary>{0}</summary></member>", documentationMemberID); } public override bool Equals(object obj) { return ReferenceEquals(this, obj); } public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } } public static TestWorkspace CreateWorkspace(string xmlDefinition, bool completed = true, bool openDocuments = true, ExportProvider exportProvider = null) { return CreateWorkspace(XElement.Parse(xmlDefinition), completed, openDocuments, exportProvider); } public static TestWorkspace CreateWorkspace( XElement workspaceElement, bool completed = true, bool openDocuments = true, ExportProvider exportProvider = null, string workspaceKind = null) { SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext()); if (workspaceElement.Name != WorkspaceElementName) { throw new ArgumentException(); } exportProvider = exportProvider ?? TestExportProvider.ExportProviderWithCSharpAndVisualBasic; var workspace = new TestWorkspace(exportProvider, workspaceKind); var projectMap = new Dictionary<string, TestHostProject>(); var documentElementToFilePath = new Dictionary<XElement, string>(); var projectElementToAssemblyName = new Dictionary<XElement, string>(); var filePathToTextBufferMap = new Dictionary<string, ITextBuffer>(); int projectIdentifier = 0; int documentIdentifier = 0; foreach (var projectElement in workspaceElement.Elements(ProjectElementName)) { var project = CreateProject( workspaceElement, projectElement, exportProvider, workspace, projectElementToAssemblyName, documentElementToFilePath, filePathToTextBufferMap, ref projectIdentifier, ref documentIdentifier); Assert.False(projectMap.ContainsKey(project.AssemblyName)); projectMap.Add(project.AssemblyName, project); workspace.Projects.Add(project); } var documentFilePaths = new HashSet<string>(); foreach (var project in projectMap.Values) { foreach (var document in project.Documents) { Assert.True(document.IsLinkFile || documentFilePaths.Add(document.FilePath)); } } var submissions = CreateSubmissions(workspace, workspaceElement.Elements(SubmissionElementName), exportProvider); foreach (var submission in submissions) { projectMap.Add(submission.AssemblyName, submission); } var solution = new TestHostSolution(projectMap.Values.ToArray()); workspace.AddTestSolution(solution); foreach (var projectElement in workspaceElement.Elements(ProjectElementName)) { foreach (var projectReference in projectElement.Elements(ProjectReferenceElementName)) { var fromName = projectElementToAssemblyName[projectElement]; var toName = projectReference.Value; var fromProject = projectMap[fromName]; var toProject = projectMap[toName]; var aliases = projectReference.Attributes(AliasAttributeName).Select(a => a.Value).ToImmutableArray(); workspace.OnProjectReferenceAdded(fromProject.Id, new ProjectReference(toProject.Id, aliases.Any() ? aliases : default(ImmutableArray<string>))); } } for (int i = 1; i < submissions.Count; i++) { if (submissions[i].CompilationOptions == null) { continue; } for (int j = i - 1; j >= 0; j--) { if (submissions[j].CompilationOptions != null) { workspace.OnProjectReferenceAdded(submissions[i].Id, new ProjectReference(submissions[j].Id)); break; } } } foreach (var project in projectMap.Values) { foreach (var document in project.Documents) { if (openDocuments) { workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer(), isCurrentContext: !document.IsLinkFile); } workspace.Documents.Add(document); } } return workspace; } private static IList<TestHostProject> CreateSubmissions( TestWorkspace workspace, IEnumerable<XElement> submissionElements, ExportProvider exportProvider) { var submissions = new List<TestHostProject>(); var submissionIndex = 0; foreach (var submissionElement in submissionElements) { var submissionName = "Submission" + (submissionIndex++); var languageName = GetLanguage(workspace, submissionElement); // The document var markupCode = submissionElement.NormalizedValue(); string code; int? cursorPosition; IDictionary<string, IList<TextSpan>> spans; MarkupTestFile.GetPositionAndSpans(markupCode, out code, out cursorPosition, out spans); var languageServices = workspace.Services.GetLanguageServices(languageName); var contentTypeLanguageService = languageServices.GetService<IContentTypeLanguageService>(); var contentType = contentTypeLanguageService.GetDefaultContentType(); var textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code); // The project var document = new TestHostDocument(exportProvider, languageServices, textBuffer, submissionName, cursorPosition, spans, SourceCodeKind.Interactive); var documents = new List<TestHostDocument> { document }; if (languageName == NoCompilationConstants.LanguageName) { submissions.Add( new TestHostProject( languageServices, compilationOptions: null, parseOptions: null, assemblyName: submissionName, references: null, documents: documents, isSubmission: true)); continue; } var syntaxFactory = languageServices.GetService<ISyntaxTreeFactoryService>(); var compilationFactory = languageServices.GetService<ICompilationFactoryService>(); var compilationOptions = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary); var parseOptions = syntaxFactory.GetDefaultParseOptions().WithKind(SourceCodeKind.Interactive); var references = CreateCommonReferences(workspace, submissionElement); var project = new TestHostProject( languageServices, compilationOptions, parseOptions, submissionName, references, documents, isSubmission: true); submissions.Add(project); } return submissions; } private static TestHostProject CreateProject( XElement workspaceElement, XElement projectElement, ExportProvider exportProvider, TestWorkspace workspace, Dictionary<XElement, string> projectElementToAssemblyName, Dictionary<XElement, string> documentElementToFilePath, Dictionary<string, ITextBuffer> filePathToTextBufferMap, ref int projectId, ref int documentId) { var language = GetLanguage(workspace, projectElement); var assemblyName = GetAssemblyName(workspace, projectElement, ref projectId); projectElementToAssemblyName.Add(projectElement, assemblyName); string filePath; if (projectElement.Attribute(FilePathAttributeName) != null) { filePath = projectElement.Attribute(FilePathAttributeName).Value; if (string.Compare(filePath, NullFilePath, StringComparison.Ordinal) == 0) { // allow explicit null file path filePath = null; } } else { filePath = assemblyName + (language == LanguageNames.CSharp ? ".csproj" : language == LanguageNames.VisualBasic ? ".vbproj" : ("." + language)); } var contentTypeRegistryService = exportProvider.GetExportedValue<IContentTypeRegistryService>(); var languageServices = workspace.Services.GetLanguageServices(language); var compilationOptions = CreateCompilationOptions(workspace, projectElement, language); var parseOptions = GetParseOptions(projectElement, language, languageServices); var references = CreateReferenceList(workspace, projectElement); var analyzers = CreateAnalyzerList(workspace, projectElement); var documents = new List<TestHostDocument>(); var documentElements = projectElement.Elements(DocumentElementName).ToList(); foreach (var documentElement in documentElements) { var document = CreateDocument( workspace, workspaceElement, documentElement, language, exportProvider, languageServices, filePathToTextBufferMap, ref documentId); documents.Add(document); documentElementToFilePath.Add(documentElement, document.FilePath); } return new TestHostProject(languageServices, compilationOptions, parseOptions, assemblyName, references, documents, filePath: filePath, analyzerReferences: analyzers); } private static ParseOptions GetParseOptions(XElement projectElement, string language, HostLanguageServices languageServices) { return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic ? GetParseOptionsWorker(projectElement, language, languageServices) : null; } private static ParseOptions GetParseOptionsWorker(XElement projectElement, string language, HostLanguageServices languageServices) { ParseOptions parseOptions; var preprocessorSymbolsAttribute = projectElement.Attribute(PreprocessorSymbolsAttributeName); if (preprocessorSymbolsAttribute != null) { parseOptions = GetPreProcessorParseOptions(language, preprocessorSymbolsAttribute); } else { parseOptions = languageServices.GetService<ISyntaxTreeFactoryService>().GetDefaultParseOptions(); } var languageVersionAttribute = projectElement.Attribute(LanguageVersionAttributeName); if (languageVersionAttribute != null) { parseOptions = GetParseOptionsWithLanguageVersion(language, parseOptions, languageVersionAttribute); } var documentationMode = GetDocumentationMode(projectElement); if (documentationMode != null) { parseOptions = parseOptions.WithDocumentationMode(documentationMode.Value); } return parseOptions; } private static ParseOptions GetPreProcessorParseOptions(string language, XAttribute preprocessorSymbolsAttribute) { if (language == LanguageNames.CSharp) { return new CSharpParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value.Split(',')); } else if (language == LanguageNames.VisualBasic) { return new VisualBasicParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value .Split(',').Select(v => KeyValuePair.Create(v.Split('=').ElementAt(0), (object)v.Split('=').ElementAt(1))).ToImmutableArray()); } else { throw new ArgumentException("Unexpected language '{0}' for generating custom parse options.", language); } } private static ParseOptions GetParseOptionsWithLanguageVersion(string language, ParseOptions parseOptions, XAttribute languageVersionAttribute) { if (language == LanguageNames.CSharp) { var languageVersion = (CodeAnalysis.CSharp.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.CSharp.LanguageVersion), languageVersionAttribute.Value); parseOptions = ((CSharpParseOptions)parseOptions).WithLanguageVersion(languageVersion); } else if (language == LanguageNames.VisualBasic) { var languageVersion = (CodeAnalysis.VisualBasic.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.VisualBasic.LanguageVersion), languageVersionAttribute.Value); parseOptions = ((VisualBasicParseOptions)parseOptions).WithLanguageVersion(languageVersion); } return parseOptions; } private static DocumentationMode? GetDocumentationMode(XElement projectElement) { var documentationModeAttribute = projectElement.Attribute(DocumentationModeAttributeName); if (documentationModeAttribute != null) { return (DocumentationMode)Enum.Parse(typeof(DocumentationMode), documentationModeAttribute.Value); } else { return null; } } private static string GetAssemblyName(TestWorkspace workspace, XElement projectElement, ref int projectId) { var assemblyNameAttribute = projectElement.Attribute(AssemblyNameAttributeName); if (assemblyNameAttribute != null) { return assemblyNameAttribute.Value; } var language = GetLanguage(workspace, projectElement); projectId++; return language == LanguageNames.CSharp ? "CSharpAssembly" + projectId : language == LanguageNames.VisualBasic ? "VisualBasicAssembly" + projectId : language + "Assembly" + projectId; } private static string GetLanguage(TestWorkspace workspace, XElement projectElement) { string languageName = projectElement.Attribute(LanguageAttributeName).Value; if (!workspace.Services.SupportedLanguages.Contains(languageName)) { throw new ArgumentException(string.Format("Language should be one of '{0}' and it is {1}", string.Join(", ", workspace.Services.SupportedLanguages), languageName)); } return languageName; } private static CompilationOptions CreateCompilationOptions( TestWorkspace workspace, XElement projectElement, string language) { var compilationOptionsElement = projectElement.Element(CompilationOptionsElementName); return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic ? CreateCompilationOptions(workspace, language, compilationOptionsElement) : null; } private static CompilationOptions CreateCompilationOptions(TestWorkspace workspace, string language, XElement compilationOptionsElement) { var rootNamespace = new VisualBasicCompilationOptions(OutputKind.ConsoleApplication).RootNamespace; var globalImports = new List<GlobalImport>(); var reportDiagnostic = ReportDiagnostic.Default; if (compilationOptionsElement != null) { globalImports = compilationOptionsElement.Elements(GlobalImportElementName) .Select(x => GlobalImport.Parse(x.Value)).ToList(); var rootNamespaceAttribute = compilationOptionsElement.Attribute(RootNamespaceAttributeName); if (rootNamespaceAttribute != null) { rootNamespace = rootNamespaceAttribute.Value; } var reportDiagnosticAttribute = compilationOptionsElement.Attribute(ReportDiagnosticAttributeName); if (reportDiagnosticAttribute != null) { reportDiagnostic = (ReportDiagnostic)Enum.Parse(typeof(ReportDiagnostic), (string)reportDiagnosticAttribute); } var outputTypeAttribute = compilationOptionsElement.Attribute(OutputTypeAttributeName); if (outputTypeAttribute != null && outputTypeAttribute.Value == "WindowsRuntimeMetadata") { if (rootNamespaceAttribute == null) { rootNamespace = new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).RootNamespace; } return language == LanguageNames.CSharp ? (CompilationOptions)new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata) : new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).WithGlobalImports(globalImports).WithRootNamespace(rootNamespace); } } else { // Add some common global imports by default for VB globalImports.Add(GlobalImport.Parse("System")); globalImports.Add(GlobalImport.Parse("System.Collections.Generic")); globalImports.Add(GlobalImport.Parse("System.Linq")); } // TODO: Allow these to be specified. var languageServices = workspace.Services.GetLanguageServices(language); var compilationOptions = languageServices.GetService<ICompilationFactoryService>().GetDefaultCompilationOptions(); compilationOptions = compilationOptions.WithOutputKind(OutputKind.DynamicallyLinkedLibrary) .WithGeneralDiagnosticOption(reportDiagnostic) .WithSourceReferenceResolver(SourceFileResolver.Default) .WithXmlReferenceResolver(XmlFileResolver.Default) .WithMetadataReferenceResolver(RuntimeMetadataReferenceResolver.Default) .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); if (language == LanguageNames.VisualBasic) { compilationOptions = ((VisualBasicCompilationOptions)compilationOptions).WithRootNamespace(rootNamespace) .WithGlobalImports(globalImports); } return compilationOptions; } private static TestHostDocument CreateDocument( TestWorkspace workspace, XElement workspaceElement, XElement documentElement, string language, ExportProvider exportProvider, HostLanguageServices languageServiceProvider, Dictionary<string, ITextBuffer> filePathToTextBufferMap, ref int documentId) { string markupCode; string filePath; var isLinkFileAttribute = documentElement.Attribute(IsLinkFileAttributeName); bool isLinkFile = isLinkFileAttribute != null && ((bool?)isLinkFileAttribute).HasValue && ((bool?)isLinkFileAttribute).Value; if (isLinkFile) { // This is a linked file. Use the filePath and markup from the referenced document. var originalProjectName = documentElement.Attribute(LinkAssemblyNameAttributeName); var originalDocumentPath = documentElement.Attribute(LinkFilePathAttributeName); if (originalProjectName == null || originalDocumentPath == null) { throw new ArgumentException("Linked file specified without LinkAssemblyName or LinkFilePath."); } var originalProjectNameStr = originalProjectName.Value; var originalDocumentPathStr = originalDocumentPath.Value; var originalProject = workspaceElement.Elements(ProjectElementName).First(p => { var assemblyName = p.Attribute(AssemblyNameAttributeName); return assemblyName != null && assemblyName.Value == originalProjectNameStr; }); if (originalProject == null) { throw new ArgumentException("Linked file's LinkAssemblyName '{0}' project not found.", originalProjectNameStr); } var originalDocument = originalProject.Elements(DocumentElementName).First(d => { var documentPath = d.Attribute(FilePathAttributeName); return documentPath != null && documentPath.Value == originalDocumentPathStr; }); if (originalDocument == null) { throw new ArgumentException("Linked file's LinkFilePath '{0}' file not found.", originalDocumentPathStr); } markupCode = originalDocument.NormalizedValue(); filePath = GetFilePath(workspace, originalDocument, ref documentId); } else { markupCode = documentElement.NormalizedValue(); filePath = GetFilePath(workspace, documentElement, ref documentId); } var folders = GetFolders(documentElement); var optionsElement = documentElement.Element(ParseOptionsElementName); // TODO: Allow these to be specified. var codeKind = SourceCodeKind.Regular; if (optionsElement != null) { var attr = optionsElement.Attribute(KindAttributeName); codeKind = attr == null ? SourceCodeKind.Regular : (SourceCodeKind)Enum.Parse(typeof(SourceCodeKind), attr.Value); } var contentTypeLanguageService = languageServiceProvider.GetService<IContentTypeLanguageService>(); var contentType = contentTypeLanguageService.GetDefaultContentType(); string code; int? cursorPosition; IDictionary<string, IList<TextSpan>> spans; MarkupTestFile.GetPositionAndSpans(markupCode, out code, out cursorPosition, out spans); // For linked files, use the same ITextBuffer for all linked documents ITextBuffer textBuffer; if (!filePathToTextBufferMap.TryGetValue(filePath, out textBuffer)) { textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code); filePathToTextBufferMap.Add(filePath, textBuffer); } return new TestHostDocument(exportProvider, languageServiceProvider, textBuffer, filePath, cursorPosition, spans, codeKind, folders, isLinkFile); } private static string GetFilePath( TestWorkspace workspace, XElement documentElement, ref int documentId) { var filePathAttribute = documentElement.Attribute(FilePathAttributeName); if (filePathAttribute != null) { return filePathAttribute.Value; } var language = GetLanguage(workspace, documentElement.Ancestors(ProjectElementName).Single()); documentId++; var name = "Test" + documentId; return language == LanguageNames.CSharp ? name + ".cs" : name + ".vb"; } private static IReadOnlyList<string> GetFolders(XElement documentElement) { var folderAttribute = documentElement.Attribute(FoldersAttributeName); if (folderAttribute == null) { return null; } var folderContainers = folderAttribute.Value.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); return new ReadOnlyCollection<string>(folderContainers.ToList()); } /// <summary> /// Takes completely valid code, compiles it, and emits it to a MetadataReference without using /// the file system /// </summary> private static MetadataReference CreateMetadataReferenceFromSource(TestWorkspace workspace, XElement referencedSource) { var compilation = CreateCompilation(workspace, referencedSource); var aliasElement = referencedSource.Attribute("Aliases") != null ? referencedSource.Attribute("Aliases").Value : null; var aliases = aliasElement != null ? aliasElement.Split(',').Select(s => s.Trim()).ToImmutableArray() : default(ImmutableArray<string>); bool includeXmlDocComments = false; var includeXmlDocCommentsAttribute = referencedSource.Attribute(IncludeXmlDocCommentsAttributeName); if (includeXmlDocCommentsAttribute != null && ((bool?)includeXmlDocCommentsAttribute).HasValue && ((bool?)includeXmlDocCommentsAttribute).Value) { includeXmlDocComments = true; } return MetadataReference.CreateFromImage(compilation.EmitToArray(), new MetadataReferenceProperties(aliases: aliases), includeXmlDocComments ? new DeferredDocumentationProvider(compilation) : null); } private static Compilation CreateCompilation(TestWorkspace workspace, XElement referencedSource) { string languageName = GetLanguage(workspace, referencedSource); string assemblyName = "ReferencedAssembly"; var assemblyNameAttribute = referencedSource.Attribute(AssemblyNameAttributeName); if (assemblyNameAttribute != null) { assemblyName = assemblyNameAttribute.Value; } var languageServices = workspace.Services.GetLanguageServices(languageName); var compilationFactory = languageServices.GetService<ICompilationFactoryService>(); var options = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary); var compilation = compilationFactory.CreateCompilation(assemblyName, options); var documentElements = referencedSource.Elements(DocumentElementName).ToList(); foreach (var documentElement in documentElements) { compilation = compilation.AddSyntaxTrees(CreateSyntaxTree(languageName, documentElement.Value)); } foreach (var reference in CreateReferenceList(workspace, referencedSource)) { compilation = compilation.AddReferences(reference); } return compilation; } private static SyntaxTree CreateSyntaxTree(string languageName, string referencedCode) { if (LanguageNames.CSharp == languageName) { return Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(referencedCode); } else { return Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseSyntaxTree(referencedCode); } } private static IList<MetadataReference> CreateReferenceList(TestWorkspace workspace, XElement element) { var references = CreateCommonReferences(workspace, element); foreach (var reference in element.Elements(MetadataReferenceElementName)) { references.Add(MetadataReference.CreateFromFile(reference.Value)); } foreach (var metadataReferenceFromSource in element.Elements(MetadataReferenceFromSourceElementName)) { references.Add(CreateMetadataReferenceFromSource(workspace, metadataReferenceFromSource)); } return references; } private static IList<AnalyzerReference> CreateAnalyzerList(TestWorkspace workspace, XElement projectElement) { var analyzers = new List<AnalyzerReference>(); foreach (var analyzer in projectElement.Elements(AnalyzerElementName)) { analyzers.Add( new AnalyzerImageReference( ImmutableArray<DiagnosticAnalyzer>.Empty, display: (string)analyzer.Attribute(AnalyzerDisplayAttributeName), fullPath: (string)analyzer.Attribute(AnalyzerFullPathAttributeName))); } return analyzers; } private static IList<MetadataReference> CreateCommonReferences(TestWorkspace workspace, XElement element) { var references = new List<MetadataReference>(); var net45 = element.Attribute(CommonReferencesNet45AttributeName); if (net45 != null && ((bool?)net45).HasValue && ((bool?)net45).Value) { references = new List<MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 }; if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var commonReferencesAttribute = element.Attribute(CommonReferencesAttributeName); if (commonReferencesAttribute != null && ((bool?)commonReferencesAttribute).HasValue && ((bool?)commonReferencesAttribute).Value) { references = new List<MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 }; if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef_v4_0_30319_17929); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var winRT = element.Attribute(CommonReferencesWinRTAttributeName); if (winRT != null && ((bool?)winRT).HasValue && ((bool?)winRT).Value) { references = new List<MetadataReference>(TestBase.WinRtRefs.Length); references.AddRange(TestBase.WinRtRefs); if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef_v4_0_30319_17929); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var portable = element.Attribute(CommonReferencesPortableAttributeName); if (portable != null && ((bool?)portable).HasValue && ((bool?)portable).Value) { references = new List<MetadataReference>(TestBase.PortableRefsMinimal.Length); references.AddRange(TestBase.PortableRefsMinimal); } var systemRuntimeFacade = element.Attribute(CommonReferenceFacadeSystemRuntimeAttributeName); if (systemRuntimeFacade != null && ((bool?)systemRuntimeFacade).HasValue && ((bool?)systemRuntimeFacade).Value) { references.Add(TestBase.SystemRuntimeFacadeRef); } return references; } } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (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/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // #pragma warning disable 1587 #region Header /// /// JsonMapper.cs /// JSON to .Net object and object to JSON conversions. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using Amazon.Util; using Amazon.Util.Internal; namespace ThirdParty.Json.LitJson { internal struct PropertyMetadata { public MemberInfo Info; public bool IsField; public Type Type; } internal struct ArrayMetadata { private Type element_type; private bool is_array; private bool is_list; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsArray { get { return is_array; } set { is_array = value; } } public bool IsList { get { return is_list; } set { is_list = value; } } } internal struct ObjectMetadata { private Type element_type; private bool is_dictionary; private IDictionary<string, PropertyMetadata> properties; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsDictionary { get { return is_dictionary; } set { is_dictionary = value; } } public IDictionary<string, PropertyMetadata> Properties { get { return properties; } set { properties = value; } } } internal delegate void ExporterFunc (object obj, JsonWriter writer); public delegate void ExporterFunc<T> (T obj, JsonWriter writer); internal delegate object ImporterFunc (object input); public delegate TValue ImporterFunc<TJson, TValue> (TJson input); public delegate IJsonWrapper WrapperFactory (); public class JsonMapper { #region Fields private static int max_nesting_depth; private static IFormatProvider datetime_format; private static IDictionary<Type, ExporterFunc> base_exporters_table; private static IDictionary<Type, ExporterFunc> custom_exporters_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> base_importers_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> custom_importers_table; private static IDictionary<Type, ArrayMetadata> array_metadata; private static readonly object array_metadata_lock = new Object (); private static IDictionary<Type, IDictionary<Type, MethodInfo>> conv_ops; private static readonly object conv_ops_lock = new Object (); private static IDictionary<Type, ObjectMetadata> object_metadata; private static readonly object object_metadata_lock = new Object (); private static IDictionary<Type, IList<PropertyMetadata>> type_properties; private static readonly object type_properties_lock = new Object (); private static JsonWriter static_writer; private static readonly object static_writer_lock = new Object (); #endregion #region Constructors static JsonMapper () { max_nesting_depth = 100; array_metadata = new Dictionary<Type, ArrayMetadata> (); conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> (); object_metadata = new Dictionary<Type, ObjectMetadata> (); type_properties = new Dictionary<Type, IList<PropertyMetadata>> (); static_writer = new JsonWriter (); datetime_format = DateTimeFormatInfo.InvariantInfo; base_exporters_table = new Dictionary<Type, ExporterFunc> (); custom_exporters_table = new Dictionary<Type, ExporterFunc> (); base_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); custom_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); RegisterBaseExporters (); RegisterBaseImporters (); } #endregion #region Private Methods private static void AddArrayMetadata (Type type) { if (array_metadata.ContainsKey (type)) return; ArrayMetadata data = new ArrayMetadata (); data.IsArray = type.IsArray; var typeInfo = TypeFactory.GetTypeInfo(type); if (typeInfo.GetInterface("System.Collections.IList") != null) data.IsList = true; foreach (PropertyInfo p_info in typeInfo.GetProperties()) { if (p_info.Name != "Item") continue; ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (int)) data.ElementType = p_info.PropertyType; } lock (array_metadata_lock) { try { array_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddObjectMetadata (Type type) { if (object_metadata.ContainsKey (type)) return; ObjectMetadata data = new ObjectMetadata (); var typeInfo = TypeFactory.GetTypeInfo(type); if (typeInfo.GetInterface("System.Collections.IDictionary") != null) data.IsDictionary = true; data.Properties = new Dictionary<string, PropertyMetadata> (); foreach (PropertyInfo p_info in typeInfo.GetProperties()) { if (p_info.Name == "Item") { ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (string)) data.ElementType = p_info.PropertyType; continue; } PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.Type = p_info.PropertyType; data.Properties.Add (p_info.Name, p_data); } foreach (FieldInfo f_info in typeInfo.GetFields()) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; p_data.Type = f_info.FieldType; data.Properties.Add (f_info.Name, p_data); } lock (object_metadata_lock) { try { object_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddTypeProperties (Type type) { if (type_properties.ContainsKey (type)) return; var typeInfo = TypeFactory.GetTypeInfo(type); IList<PropertyMetadata> props = new List<PropertyMetadata> (); foreach (PropertyInfo p_info in typeInfo.GetProperties()) { if (p_info.Name == "Item") continue; PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.IsField = false; props.Add (p_data); } foreach (FieldInfo f_info in typeInfo.GetFields()) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; props.Add (p_data); } lock (type_properties_lock) { try { type_properties.Add (type, props); } catch (ArgumentException) { return; } } } private static MethodInfo GetConvOp (Type t1, Type t2) { lock (conv_ops_lock) { if (! conv_ops.ContainsKey (t1)) conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ()); } var typeInfoT1 = TypeFactory.GetTypeInfo(t1); var typeInfoT2 = TypeFactory.GetTypeInfo(t2); if (conv_ops[t1].ContainsKey (t2)) return conv_ops[t1][t2]; MethodInfo op = typeInfoT1.GetMethod( "op_Implicit", new ITypeInfo[] { typeInfoT2 }); lock (conv_ops_lock) { try { conv_ops[t1].Add (t2, op); } catch (ArgumentException) { return conv_ops[t1][t2]; } } return op; } private static object ReadValue (Type inst_type, JsonReader reader) { reader.Read (); var inst_typeInfo = TypeFactory.GetTypeInfo(inst_type); if (reader.Token == JsonToken.ArrayEnd) return null; //support for nullable types Type underlying_type = Nullable.GetUnderlyingType(inst_type); Type value_type = underlying_type ?? inst_type; if (reader.Token == JsonToken.Null) { if (inst_type.IsClass || underlying_type != null) { return null; } throw new JsonException (String.Format ( "Can't assign null to an instance of type {0}", inst_type)); } if (reader.Token == JsonToken.Double || reader.Token == JsonToken.Int || reader.Token == JsonToken.Long || reader.Token == JsonToken.String || reader.Token == JsonToken.Boolean) { Type json_type = reader.Value.GetType (); var json_typeInfo = TypeFactory.GetTypeInfo(json_type); if (inst_typeInfo.IsAssignableFrom(json_typeInfo)) return reader.Value; // If there's a custom importer that fits, use it if (custom_importers_table.ContainsKey (json_type) && custom_importers_table[json_type].ContainsKey ( value_type)) { ImporterFunc importer = custom_importers_table[json_type][value_type]; return importer (reader.Value); } // Maybe there's a base importer that works if (base_importers_table.ContainsKey (json_type) && base_importers_table[json_type].ContainsKey ( value_type)) { ImporterFunc importer = base_importers_table[json_type][value_type]; return importer (reader.Value); } // Maybe it's an enum if (inst_typeInfo.IsEnum) return Enum.ToObject (value_type, reader.Value); // Try using an implicit conversion operator MethodInfo conv_op = GetConvOp (value_type, json_type); if (conv_op != null) return conv_op.Invoke (null, new object[] { reader.Value }); // No luck throw new JsonException (String.Format ( "Can't assign value '{0}' (type {1}) to type {2}", reader.Value, json_type, inst_type)); } object instance = null; if (reader.Token == JsonToken.ArrayStart) { AddArrayMetadata (inst_type); ArrayMetadata t_data = array_metadata[inst_type]; if (! t_data.IsArray && ! t_data.IsList) throw new JsonException (String.Format ( "Type {0} can't act as an array", inst_type)); IList list; Type elem_type; if (! t_data.IsArray) { list = (IList) Activator.CreateInstance (inst_type); elem_type = t_data.ElementType; } else { list = new List<object> (); elem_type = inst_type.GetElementType (); } while (true) { object item = ReadValue (elem_type, reader); if (reader.Token == JsonToken.ArrayEnd) break; list.Add (item); } if (t_data.IsArray) { int n = list.Count; instance = Array.CreateInstance (elem_type, n); for (int i = 0; i < n; i++) ((Array) instance).SetValue (list[i], i); } else instance = list; } else if (reader.Token == JsonToken.ObjectStart) { AddObjectMetadata (value_type); ObjectMetadata t_data = object_metadata[value_type]; instance = Activator.CreateInstance (value_type); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; if (t_data.Properties.ContainsKey (property)) { PropertyMetadata prop_data = t_data.Properties[property]; if (prop_data.IsField) { ((FieldInfo) prop_data.Info).SetValue ( instance, ReadValue (prop_data.Type, reader)); } else { PropertyInfo p_info = (PropertyInfo) prop_data.Info; if (p_info.CanWrite) p_info.SetValue ( instance, ReadValue (prop_data.Type, reader), null); else ReadValue (prop_data.Type, reader); } } else { if (! t_data.IsDictionary) throw new JsonException (String.Format ( "The type {0} doesn't have the " + "property '{1}'", inst_type, property)); ((IDictionary) instance).Add ( property, ReadValue ( t_data.ElementType, reader)); } } } return instance; } private static IJsonWrapper ReadValue (WrapperFactory factory, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd || reader.Token == JsonToken.Null) return null; IJsonWrapper instance = factory (); if (reader.Token == JsonToken.String) { instance.SetString ((string) reader.Value); return instance; } if (reader.Token == JsonToken.Double) { instance.SetDouble ((double) reader.Value); return instance; } if (reader.Token == JsonToken.Int) { instance.SetInt ((int) reader.Value); return instance; } if (reader.Token == JsonToken.Long) { instance.SetLong ((long) reader.Value); return instance; } if (reader.Token == JsonToken.Boolean) { instance.SetBoolean ((bool) reader.Value); return instance; } if (reader.Token == JsonToken.ArrayStart) { instance.SetJsonType (JsonType.Array); while (true) { IJsonWrapper item = ReadValue (factory, reader); // nij - added check to see if the item is not null. This is to handle arrays within arrays. // In those cases when the outer array read the inner array an item was returned back the current // reader.Token is at the ArrayEnd for the inner array. if (item == null && reader.Token == JsonToken.ArrayEnd) break; ((IList) instance).Add (item); } } else if (reader.Token == JsonToken.ObjectStart) { instance.SetJsonType (JsonType.Object); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; ((IDictionary) instance)[property] = ReadValue ( factory, reader); } } return instance; } private static void RegisterBaseExporters () { base_exporters_table[typeof (byte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((byte) obj)); }; base_exporters_table[typeof (char)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((char) obj)); }; base_exporters_table[typeof (DateTime)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((DateTime) obj, datetime_format)); }; base_exporters_table[typeof (decimal)] = delegate (object obj, JsonWriter writer) { writer.Write ((decimal) obj); }; base_exporters_table[typeof (sbyte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((sbyte) obj)); }; base_exporters_table[typeof (short)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((short) obj)); }; base_exporters_table[typeof (ushort)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((ushort) obj)); }; base_exporters_table[typeof (uint)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToUInt64 ((uint) obj)); }; base_exporters_table[typeof (ulong)] = delegate (object obj, JsonWriter writer) { writer.Write ((ulong) obj); }; base_exporters_table[typeof(float)] = delegate (object obj,JsonWriter writer){ writer.Write(Convert.ToDouble((float) obj)); }; base_exporters_table[typeof(Int64)] = delegate (object obj,JsonWriter writer){ writer.Write(Convert.ToDouble((Int64) obj)); }; } private static void RegisterBaseImporters () { ImporterFunc importer; importer = delegate (object input) { return Convert.ToByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (byte), importer); importer = delegate (object input) { return Convert.ToUInt64 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ulong), importer); importer = delegate (object input) { return Convert.ToSByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (sbyte), importer); importer = delegate (object input) { return Convert.ToInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (short), importer); importer = delegate (object input) { return Convert.ToUInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ushort), importer); importer = delegate (object input) { return Convert.ToUInt32 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (uint), importer); importer = delegate (object input) { return Convert.ToSingle ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (float), importer); importer = delegate (object input) { return Convert.ToDouble ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (double), importer); importer = delegate (object input) { return Convert.ToDecimal ((double) input); }; RegisterImporter (base_importers_table, typeof (double), typeof (decimal), importer); importer = delegate(object input) { return Convert.ToSingle((float)(double)input); }; RegisterImporter(base_importers_table,typeof(double), typeof(float),importer); importer = delegate (object input) { return Convert.ToUInt32 ((long) input); }; RegisterImporter (base_importers_table, typeof (long), typeof (uint), importer); importer = delegate (object input) { return Convert.ToChar ((string) input); }; RegisterImporter (base_importers_table, typeof (string), typeof (char), importer); importer = delegate (object input) { return Convert.ToDateTime ((string) input, datetime_format); }; RegisterImporter (base_importers_table, typeof (string), typeof (DateTime), importer); importer = delegate(object input) { return Convert.ToInt64 ((Int32)input); }; RegisterImporter (base_importers_table, typeof (Int32), typeof(Int64), importer); } private static void RegisterImporter ( IDictionary<Type, IDictionary<Type, ImporterFunc>> table, Type json_type, Type value_type, ImporterFunc importer) { if (! table.ContainsKey (json_type)) table.Add (json_type, new Dictionary<Type, ImporterFunc> ()); table[json_type][value_type] = importer; } private static void WriteValue (object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) throw new JsonException ( String.Format ("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType ())); if (obj == null) { writer.Write (null); return; } if (obj is IJsonWrapper) { if (writer_is_private) writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ()); else ((IJsonWrapper) obj).ToJson (writer); return; } if (obj is String) { writer.Write ((string) obj); return; } if (obj is Double) { writer.Write ((double) obj); return; } if (obj is Int32) { writer.Write ((int) obj); return; } if (obj is Boolean) { writer.Write ((bool) obj); return; } if (obj is Int64) { writer.Write ((long) obj); return; } if (obj is Array) { writer.WriteArrayStart (); foreach (object elem in (Array) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IList) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IDictionary) { writer.WriteObjectStart (); foreach (DictionaryEntry entry in (IDictionary) obj) { writer.WritePropertyName ((string) entry.Key); WriteValue (entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd (); return; } Type obj_type = obj.GetType (); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter (obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter (obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType (obj_type); if (e_type == typeof (long) || e_type == typeof (uint) || e_type == typeof (ulong)) writer.Write ((ulong) obj); else writer.Write ((int) obj); return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties (obj_type); IList<PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart (); foreach (PropertyMetadata p_data in props) { if (p_data.IsField) { writer.WritePropertyName (p_data.Info.Name); WriteValue (((FieldInfo) p_data.Info).GetValue (obj), writer, writer_is_private, depth + 1); } else { PropertyInfo p_info = (PropertyInfo) p_data.Info; if (p_info.CanRead) { writer.WritePropertyName (p_data.Info.Name); WriteValue (p_info.GetValue (obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd (); } #endregion public static string ToJson (object obj) { lock (static_writer_lock) { static_writer.Reset (); WriteValue (obj, static_writer, true, 0); return static_writer.ToString (); } } public static void ToJson (object obj, JsonWriter writer) { WriteValue (obj, writer, false, 0); } public static JsonData ToObject (JsonReader reader) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, reader); } public static JsonData ToObject (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json_reader); } public static JsonData ToObject (string json) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json); } public static T ToObject<T> (JsonReader reader) { return (T) ReadValue (typeof (T), reader); } public static T ToObject<T> (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (T) ReadValue (typeof (T), json_reader); } public static T ToObject<T> (string json) { JsonReader reader = new JsonReader (json); return (T) ReadValue (typeof (T), reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, JsonReader reader) { return ReadValue (factory, reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, string json) { JsonReader reader = new JsonReader (json); return ReadValue (factory, reader); } public static void RegisterExporter<T> (ExporterFunc<T> exporter) { ExporterFunc exporter_wrapper = delegate (object obj, JsonWriter writer) { exporter ((T) obj, writer); }; custom_exporters_table[typeof (T)] = exporter_wrapper; } public static void RegisterImporter<TJson, TValue> ( ImporterFunc<TJson, TValue> importer) { ImporterFunc importer_wrapper = delegate (object input) { return importer ((TJson) input); }; RegisterImporter (custom_importers_table, typeof (TJson), typeof (TValue), importer_wrapper); } public static void UnregisterExporters () { custom_exporters_table.Clear (); } public static void UnregisterImporters () { custom_importers_table.Clear (); } } }
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 ProcessImageDemo.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using Android.Content; using Android.Gms.Maps.Model; using Android.Graphics; using Android.Net; using AppShell.NativeMaps.Mobile; using AppShell.NativeMaps.Mobile.Android; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Globalization; using System.Linq; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using GMaps = Android.Gms.Maps; using Graphics = Android.Graphics; [assembly: ExportRenderer(typeof(MapView), typeof(MapViewRenderer))] namespace AppShell.NativeMaps.Mobile.Android { public class MapViewRenderer : ViewRenderer<MapView, GMaps.MapView>, GMaps.IOnMapReadyCallback { private IImageResolver imageResolver; private GMaps.GoogleMap googleMap; private TwoWayDictionary<Marker, GMaps.Model.Marker> markers; private TwoWayDictionary<TileOverlay, GMaps.Model.TileOverlay> tileOverlays; public MapViewRenderer() { markers = new TwoWayDictionary<Marker, GMaps.Model.Marker>(new LambdaEqualityComparer<GMaps.Model.Marker>((m1, m2) => m1.Id == m2.Id)); tileOverlays = new TwoWayDictionary<TileOverlay, GMaps.Model.TileOverlay>(new LambdaEqualityComparer<GMaps.Model.TileOverlay>((m1, m2) => m1.Id == m2.Id)); imageResolver = AppShell.ShellCore.Container.GetInstance<IImageResolver>(); } protected override void OnElementChanged(ElementChangedEventArgs<MapView> e) { base.OnElementChanged(e); if (Control == null) { GMaps.MapView nativeMapView = new GMaps.MapView(Context); nativeMapView.OnCreate(null); nativeMapView.OnResume(); nativeMapView.GetMapAsync(this); SetNativeControl(nativeMapView); } if (e.OldElement != null) { if (e.OldElement.Markers != null) { foreach (Marker marker in e.OldElement.Markers) RemoveMarker(marker); if (e.OldElement.Markers is ObservableCollection<Marker>) (e.OldElement.Markers as ObservableCollection<Marker>).CollectionChanged -= Markers_CollectionChanged; } if (e.OldElement.TileOverlays != null) { foreach (TileOverlay tileOverlay in e.OldElement.TileOverlays) RemoveTileOverlay(tileOverlay); if (e.OldElement.TileOverlays is ObservableCollection<TileOverlay>) (e.OldElement.TileOverlays as ObservableCollection<TileOverlay>).CollectionChanged -= TileOverlays_CollectionChanged; } } if (e.NewElement != null && googleMap != null) { InitializeElement(); } } public void OnMapReady(GMaps.GoogleMap googleMap) { this.googleMap = googleMap; InitializeElement(); } private void InitializeElement() { SetMapType(); SetCenter(); if (Element.Markers != null) { if (Element.Markers is ObservableCollection<Marker>) (Element.Markers as ObservableCollection<Marker>).CollectionChanged += Markers_CollectionChanged; foreach (Marker marker in Element.Markers) AddMarker(marker); } if (Element.TileOverlays != null) { if (Element.TileOverlays is ObservableCollection<TileOverlay>) (Element.TileOverlays as ObservableCollection<TileOverlay>).CollectionChanged += TileOverlays_CollectionChanged; foreach (TileOverlay tileOverlay in Element.TileOverlays) AddTileOverlay(tileOverlay); } googleMap.UiSettings.MapToolbarEnabled = false; googleMap.CameraChange += GoogleMap_CameraChange; googleMap.MarkerClick += GoogleMap_MarkerClick; googleMap.MarkerDrag += GoogleMap_MarkerDrag; googleMap.MarkerDragEnd += GoogleMap_MarkerDragEnd; } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == MapView.CenterProperty.PropertyName) SetCenter(); else if (e.PropertyName == MapView.ZoomLevelProperty.PropertyName) SetCenter(); else if (e.PropertyName == MapView.MapTypeProperty.PropertyName) SetMapType(); else if (e.PropertyName == MapView.NavigationDestinationProperty.PropertyName) NavigateTo(); } private void GoogleMap_CameraChange(object sender, GMaps.GoogleMap.CameraChangeEventArgs e) { if (Element != null) Element.MapZoomLevel = e.Position.Zoom; } private void GoogleMap_MarkerClick(object sender, GMaps.GoogleMap.MarkerClickEventArgs e) { e.Handled = false; Element.SelectedMarker = markers[e.Marker]; } private void GoogleMap_MarkerDrag(object sender, GMaps.GoogleMap.MarkerDragEventArgs e) { markers[e.Marker].Center = new Location(e.Marker.Position.Latitude, e.Marker.Position.Longitude); } private void GoogleMap_MarkerDragEnd(object sender, GMaps.GoogleMap.MarkerDragEndEventArgs e) { markers[e.Marker].Center = new Location(e.Marker.Position.Latitude, e.Marker.Position.Longitude); } private void Markers_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Reset) { foreach (Marker marker in markers.Select(m => m.Key).ToList()) RemoveMarker(marker); } else if (e.Action == NotifyCollectionChangedAction.Add) { foreach (Marker marker in e.NewItems) AddMarker(marker); } else if (e.Action == NotifyCollectionChangedAction.Remove) { foreach (Marker marker in e.OldItems) RemoveMarker(marker); } } private void TileOverlays_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Reset) { foreach (TileOverlay tileOverlay in tileOverlays.Select(m => m.Key).ToList()) RemoveTileOverlay(tileOverlay); } else if (e.Action == NotifyCollectionChangedAction.Add) { foreach (TileOverlay tileOverlay in e.NewItems) AddTileOverlay(tileOverlay); } else if (e.Action == NotifyCollectionChangedAction.Remove) { foreach (TileOverlay tileOverlay in e.OldItems) RemoveTileOverlay(tileOverlay); } } private void AddMarker(Marker marker) { if (marker is Polyline) { AddPolyline(marker as Polyline); return; } MarkerOptions options = new MarkerOptions(); if (marker.ZIndex.HasValue) options.InvokeZIndex(marker.ZIndex.Value); options.SetPosition(new LatLng(marker.Center.Latitude, marker.Center.Longitude)); if (!string.IsNullOrEmpty(marker.Icon)) { if (imageResolver != null) { System.IO.Stream stream = imageResolver.Resolve(marker.Layer, marker.Icon); if (stream ==null) stream = imageResolver.Resolve(marker); if (stream != null) options.SetIcon(BitmapDescriptorFactory.FromBitmap(BitmapFactory.DecodeStream(stream))); } else options.SetIcon(BitmapDescriptorFactory.FromResource(ResourceManager.GetDrawableByName(marker.Icon))); if (marker.Label != null) CreateLabel(marker); } options.SetTitle(marker.Title); options.SetSnippet(marker.Content); options.Draggable(marker.Draggable); markers.Add(marker, googleMap.AddMarker(options)); marker.PropertyChanged += Marker_PropertyChanged; } private void AddPolyline(Polyline polyline) { PolylineOptions options = new PolylineOptions(); options.Add(polyline.Points.Select(p => new LatLng(p.Latitude, p.Longitude)).ToArray()); if (polyline.ZIndex.HasValue) options.InvokeZIndex(polyline.ZIndex.Value); if (polyline.StrokeColor != null) options.InvokeColor(Graphics.Color.ParseColor(polyline.StrokeColor)); if (polyline.StrokeWidth.HasValue) options.InvokeWidth(polyline.StrokeWidth.Value); googleMap.AddPolyline(options); } private void RemoveMarker(Marker marker) { marker.PropertyChanged -= Marker_PropertyChanged; if (marker.Label != null) RemoveLabel(marker); if (markers.ContainsKey(marker)) { markers[marker].Remove(); markers.Remove(marker); } } private void AddTileOverlay(TileOverlay tileOverlay) { TileOverlayOptions options = new TileOverlayOptions(); if (tileOverlay is UrlTileOverlay) options.InvokeTileProvider(new UrlTileOverlayProvider(tileOverlay as UrlTileOverlay)); tileOverlays.Add(tileOverlay, googleMap.AddTileOverlay(options)); } private void RemoveTileOverlay(TileOverlay tileOverlay) { tileOverlays[tileOverlay].Remove(); tileOverlays.Remove(tileOverlay); } private void Marker_PropertyChanged(object sender, PropertyChangedEventArgs e) { Marker marker = sender as Marker; switch (e.PropertyName) { case "Center": markers[marker].Position = new LatLng(marker.Center.Latitude, marker.Center.Longitude); break; case "Icon": { if (!string.IsNullOrEmpty(marker.Icon)) markers[marker].SetIcon(BitmapDescriptorFactory.FromResource(ResourceManager.GetDrawableByName(marker.Icon))); break; } case "Title": markers[marker].Title = marker.Title; break; case "Content": markers[marker].Snippet = marker.Icon; break; case "Draggable": markers[marker].Draggable = marker.Draggable; break; } if (e.PropertyName == "Center" && marker.Id != null && marker.Label != null && markers.Any(m => m.Key.Id == marker.Id + "-Label")) { var labelMarker = markers.FirstOrDefault(m => m.Key.Id == marker.Id + "-Label"); if (labelMarker.Key != null) markers[labelMarker.Key].Position = new LatLng(marker.Center.Latitude, marker.Center.Longitude); } } private void SetCenter() { if (Element != null && Element.Center != null) googleMap.MoveCamera(GMaps.CameraUpdateFactory.NewLatLngZoom(new LatLng(Element.Center.Latitude, Element.Center.Longitude), (float)Element.ZoomLevel)); } private void SetMapType() { googleMap.MapType = Element.MapType.ToNativeMapType(); } private void CreateLabel(Marker marker) { if (marker.Label.Text == null) return; Paint labelTextPaint = new Paint(); labelTextPaint.Flags = PaintFlags.AntiAlias; labelTextPaint.TextSize = marker.Label.TextSize != 0 ? marker.Label.TextSize : 25.0f; labelTextPaint.SetStyle(Paint.Style.Stroke); labelTextPaint.Color = Xamarin.Forms.Color.White.ToAndroid(); labelTextPaint.StrokeWidth = 8.0f; Rect boundsText = new Rect(); labelTextPaint.GetTextBounds(marker.Label.Text, 0, marker.Label.Text.Length, boundsText); MarkerOptions options = new MarkerOptions(); if (marker.ZIndex.HasValue) options.InvokeZIndex(marker.ZIndex.Value - 0.1f); options.SetPosition(new LatLng(marker.Center.Latitude, marker.Center.Longitude)); options.Anchor(marker.Label.AnchorPointX, marker.Label.AnchorPointY); Bitmap labelBitmap = Bitmap.CreateBitmap(boundsText.Width(), boundsText.Height() * 2, Bitmap.Config.Argb8888); Canvas canvas = new Canvas(labelBitmap); canvas.DrawText(marker.Label.Text, 0, boundsText.Height() * 2, labelTextPaint); labelTextPaint.SetStyle(Paint.Style.Fill); labelTextPaint.Color = global::Android.Graphics.Color.DarkGray; canvas.DrawText(marker.Label.Text, 0, boundsText.Height() * 2, labelTextPaint); options.SetIcon(BitmapDescriptorFactory.FromBitmap(labelBitmap)); markers.Add(new Marker() { Id = marker.Id + "-Label", Center = marker.Center }, googleMap.AddMarker(options)); } private void RemoveLabel(Marker marker) { if (marker.Id != null && markers.Any(m => m.Key.Id == marker.Id + "-Label")) { var labelMarker = markers.FirstOrDefault(m => m.Key.Id == marker.Id + "-Label"); if (labelMarker.Key != null) { markers[labelMarker.Key].Remove(); markers.Remove(labelMarker.Key); } } } private void NavigateTo() { if (Element.NavigationDestination != null) { Uri uri = Uri.Parse(string.Format(CultureInfo.InvariantCulture, "google.navigation:q={0},{1}", Element.NavigationDestination.Latitude, Element.NavigationDestination.Longitude)); Intent navigationIntent = new Intent(Intent.ActionView, uri); navigationIntent.SetPackage("com.google.android.apps.maps"); Forms.Context.StartActivity(navigationIntent); } } public override SizeRequest GetDesiredSize(int widthConstraint, int heightConstraint) { return new SizeRequest(new Size(ContextExtensions.ToPixels(Context, 40.0), ContextExtensions.ToPixels(Context, 40.0))); } } }
using System; using System.Globalization; using System.Xml; using Orchard.Comments.Models; using Orchard.ContentManagement; using Orchard.ContentManagement.Drivers; using Orchard.ContentManagement.Aspects; using Orchard.Services; using Orchard.Localization; using Orchard.Comments.Services; using Orchard.UI.Notify; namespace Orchard.Comments.Drivers { public class CommentPartDriver : ContentPartDriver<CommentPart> { private readonly IContentManager _contentManager; private readonly IWorkContextAccessor _workContextAccessor; private readonly IClock _clock; private readonly ICommentService _commentService; private readonly IOrchardServices _orchardServices; protected override string Prefix { get { return "Comments"; } } public Localizer T { get; set; } public CommentPartDriver( IContentManager contentManager, IWorkContextAccessor workContextAccessor, IClock clock, ICommentService commentService, IOrchardServices orchardServices) { _contentManager = contentManager; _workContextAccessor = workContextAccessor; _clock = clock; _commentService = commentService; _orchardServices = orchardServices; T = NullLocalizer.Instance; } protected override DriverResult Display(CommentPart part, string displayType, dynamic shapeHelper) { return Combined( ContentShape("Parts_Comment", () => shapeHelper.Parts_Comment()), ContentShape("Parts_Comment_SummaryAdmin", () => shapeHelper.Parts_Comment_SummaryAdmin()) ); } // GET protected override DriverResult Editor(CommentPart part, dynamic shapeHelper) { if (UI.Admin.AdminFilter.IsApplied(_workContextAccessor.GetContext().HttpContext.Request.RequestContext)) { return ContentShape("Parts_Comment_AdminEdit", () => shapeHelper.EditorTemplate(TemplateName: "Parts.Comment.AdminEdit", Model: part, Prefix: Prefix)); } else { return ContentShape("Parts_Comment_Edit", () => shapeHelper.EditorTemplate(TemplateName: "Parts.Comment", Model: part, Prefix: Prefix)); } } // POST protected override DriverResult Editor(CommentPart part, IUpdateModel updater, dynamic shapeHelper) { updater.TryUpdateModel(part, Prefix, null, null); var workContext = _workContextAccessor.GetContext(); // applying moderate/approve actions var httpContext = workContext.HttpContext; var name = httpContext.Request.Form["submit.Save"]; if (!string.IsNullOrEmpty(name) && String.Equals(name, "moderate", StringComparison.OrdinalIgnoreCase)) { if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) { _commentService.UnapproveComment(part.Id); _orchardServices.Notifier.Success(T("Comment successfully moderated.")); return Editor(part, shapeHelper); } } if (!string.IsNullOrEmpty(name) && String.Equals(name, "approve", StringComparison.OrdinalIgnoreCase)) { if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't approve comment"))) { _commentService.ApproveComment(part.Id); _orchardServices.Notifier.Success(T("Comment approved.")); return Editor(part, shapeHelper); } } if (!string.IsNullOrEmpty(name) && String.Equals(name, "delete", StringComparison.OrdinalIgnoreCase)) { if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment"))) { _commentService.DeleteComment(part.Id); _orchardServices.Notifier.Success(T("Comment successfully deleted.")); return Editor(part, shapeHelper); } } // if editing from the admin, don't update the owner or the status if (!string.IsNullOrEmpty(name) && String.Equals(name, "save", StringComparison.OrdinalIgnoreCase)) { _orchardServices.Notifier.Success(T("Comment saved.")); return Editor(part, shapeHelper); } part.CommentDateUtc = _clock.UtcNow; if (!String.IsNullOrEmpty(part.SiteName) && !part.SiteName.StartsWith("http://") && !part.SiteName.StartsWith("https://")) { part.SiteName = "http://" + part.SiteName; } var currentUser = workContext.CurrentUser; part.UserName = (currentUser != null ? currentUser.UserName : null); if (currentUser != null) part.Author = currentUser.UserName; else if (string.IsNullOrWhiteSpace(part.Author)) { updater.AddModelError("Comments.Author", T("Name is mandatory")); } var moderateComments = workContext.CurrentSite.As<CommentSettingsPart>().ModerateComments; part.Status = moderateComments ? CommentStatus.Pending : CommentStatus.Approved; var commentedOn = _contentManager.Get<ICommonPart>(part.CommentedOn); // prevent users from commenting on a closed thread by hijacking the commentedOn property var commentsPart = commentedOn.As<CommentsPart>(); if (commentsPart == null || !commentsPart.CommentsActive) { _orchardServices.TransactionManager.Cancel(); return Editor(part, shapeHelper); } if (commentedOn != null && commentedOn.Container != null) { part.CommentedOnContainer = commentedOn.Container.ContentItem.Id; } commentsPart.Record.CommentPartRecords.Add(part.Record); return Editor(part, shapeHelper); } protected override void Importing(CommentPart part, ContentManagement.Handlers.ImportContentContext context) { // Don't do anything if the tag is not specified. if (context.Data.Element(part.PartDefinition.Name) == null) { return; } context.ImportAttribute(part.PartDefinition.Name, "Author", author => part.Record.Author = author ); context.ImportAttribute(part.PartDefinition.Name, "SiteName", siteName => part.Record.SiteName = siteName ); context.ImportAttribute(part.PartDefinition.Name, "UserName", userName => part.Record.UserName = userName ); context.ImportAttribute(part.PartDefinition.Name, "Email", email => part.Record.Email = email ); context.ImportAttribute(part.PartDefinition.Name, "Position", position => part.Record.Position = decimal.Parse(position, CultureInfo.InvariantCulture) ); context.ImportAttribute(part.PartDefinition.Name, "Status", status => part.Record.Status = (CommentStatus)Enum.Parse(typeof(CommentStatus), status) ); context.ImportAttribute(part.PartDefinition.Name, "CommentDateUtc", commentDate => part.Record.CommentDateUtc = XmlConvert.ToDateTime(commentDate, XmlDateTimeSerializationMode.Utc) ); context.ImportAttribute(part.PartDefinition.Name, "CommentText", text => part.Record.CommentText = text ); context.ImportAttribute(part.PartDefinition.Name, "CommentedOn", commentedOn => { var contentItem = context.GetItemFromSession(commentedOn); if (contentItem != null) { part.Record.CommentedOn = contentItem.Id; } contentItem.As<CommentsPart>().Record.CommentPartRecords.Add(part.Record); }); context.ImportAttribute(part.PartDefinition.Name, "RepliedOn", repliedOn => { var contentItem = context.GetItemFromSession(repliedOn); if (contentItem != null) { part.Record.RepliedOn = contentItem.Id; } }); context.ImportAttribute(part.PartDefinition.Name, "CommentedOnContainer", commentedOnContainer => { var container = context.GetItemFromSession(commentedOnContainer); if (container != null) { part.Record.CommentedOnContainer = container.Id; } }); } protected override void Exporting(CommentPart part, ContentManagement.Handlers.ExportContentContext context) { context.Element(part.PartDefinition.Name).SetAttributeValue("Author", part.Record.Author); context.Element(part.PartDefinition.Name).SetAttributeValue("SiteName", part.Record.SiteName); context.Element(part.PartDefinition.Name).SetAttributeValue("UserName", part.Record.UserName); context.Element(part.PartDefinition.Name).SetAttributeValue("Email", part.Record.Email); context.Element(part.PartDefinition.Name).SetAttributeValue("Position", part.Record.Position.ToString(CultureInfo.InvariantCulture)); context.Element(part.PartDefinition.Name).SetAttributeValue("Status", part.Record.Status.ToString()); if (part.Record.CommentDateUtc != null) { context.Element(part.PartDefinition.Name) .SetAttributeValue("CommentDateUtc", XmlConvert.ToString(part.Record.CommentDateUtc.Value, XmlDateTimeSerializationMode.Utc)); } context.Element(part.PartDefinition.Name).SetAttributeValue("CommentText", part.Record.CommentText); var commentedOn = _contentManager.Get(part.Record.CommentedOn); if (commentedOn != null) { var commentedOnIdentity = _contentManager.GetItemMetadata(commentedOn).Identity; context.Element(part.PartDefinition.Name).SetAttributeValue("CommentedOn", commentedOnIdentity.ToString()); } var commentedOnContainer = _contentManager.Get(part.Record.CommentedOnContainer); if (commentedOnContainer != null) { var commentedOnContainerIdentity = _contentManager.GetItemMetadata(commentedOnContainer).Identity; context.Element(part.PartDefinition.Name).SetAttributeValue("CommentedOnContainer", commentedOnContainerIdentity.ToString()); } if (part.Record.RepliedOn.HasValue) { var repliedOn = _contentManager.Get(part.Record.RepliedOn.Value); if (repliedOn != null) { var repliedOnIdentity = _contentManager.GetItemMetadata(repliedOn).Identity; context.Element(part.PartDefinition.Name).SetAttributeValue("RepliedOn", repliedOnIdentity.ToString()); } } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Threading; namespace TuringMachineProject { public class TuringMachineVisualizer { private Graphics graphics; private Dictionary<string, GUIState> stateGUITable; private Dictionary<KeyValuePair<State, char>, GUITransition> edgeGUITable; private string startState; private List<string> steps; private int stepIndex; //private string[] stepAttribute = new string[] { "from", "to", "read", "tape", "pinter" }; private string lastTape; private int lastPointerIndex; private int DUPLICATION_SHIFT = 20; private int SLEEP_AMOUNT = 200; public int SleepAmount { get { return SLEEP_AMOUNT; } set { SLEEP_AMOUNT = value; } } #region Drawing Attributes private const int CIRCLE_RADIUS = 25; private const int CIRCLE_RADIUS_SPECIAL = 20; private const float WIDTH_HIGHLIGHTED = 5; private const float WIDTH_NORMAL = 3; private int TAPE_HEIGHT; #region Fonts private Font FONT_HIGHLIGHTED; private Font FONT_NORMAL; private Font TAPE_FONT; #endregion #region Colors private Color CIRCLE_COLOR_HIGHLIGHTED = Color.LightGreen; private Color CIRCLE_COLOR_NORMAL = Color.Orange; private Color CIRCLE_COLOR_SPECIAL = Color.Red; private Color CIRCLE_STRING_COLOR = Color.Black; private Color LINE_COLOR_HIGHLIGHTED = Color.LightGreen; private Color LINE_COLOR_NORMAL = Color.Gray; private Color LINE_STRING_COLOR_HIGHLIGHTED = Color.Tomato; private Color LINE_STRING_COLOR_NORMAL = Color.DarkCyan; private Color TAPE_COLOR = Color.LightBlue; private Color TAPE_POINTER_COLOR = Color.Blue; private Color TAPE_CHAR_COLOR = Color.DarkGray; private Color TAPE_CHAR_POINTER_COLOR = Color.Red; public Color CLEAR_COLOR = Color.White; #endregion #endregion public TuringMachineVisualizer(Graphics graphics) { this.graphics = graphics; this.FONT_HIGHLIGHTED = new Font (new Font("Comic Sans MS",10), FontStyle.Bold); this.FONT_NORMAL = new Font(new Font("Comic Sans MS", 10), FontStyle.Regular); this.TAPE_FONT = new Font(new Font("Comic Sans MS", 15), FontStyle.Bold); this.TAPE_HEIGHT = (int)(this.graphics.VisibleClipBounds.Height - this.graphics.MeasureString("#",this.TAPE_FONT).Height); } public void setStateTable(Dictionary<string, GUIState> stateTable) { this.stateGUITable = stateTable; } public void setEdgeTable(Dictionary<KeyValuePair<State, char>, GUITransition> transitions) { this.edgeGUITable = transitions; } public void setSteps(List<string> steps) { this.steps = steps; this.stepIndex = 1; } public void drawStep() { string[] tokens = this.steps[this.stepIndex].Split(new char[] { ' ' }); string fromState = tokens[0]; string toState = tokens[1]; char readChar = tokens[2][0]; string tape = tokens[3]; int pointerIndex = int.Parse(tokens[4]); //light start, can be deleted but delete this.initialDrawing() too and change implementation of drawLastStep() this.initialDrawing(); this.clearState(fromState, false); this.drawState(fromState, true, this.stateGUITable[fromState].getState().IsFinal); Thread.Sleep(SLEEP_AMOUNT); //light edge and draw tape this.clearState(fromState, true); this.clearEdge(fromState, readChar, false); this.clearEdge(fromState, readChar, true); // for more accurate erase this.clearTape(this.lastTape, this.lastPointerIndex); this.drawState(fromState, false, this.stateGUITable[fromState].getState().IsFinal); this.drawEdge(fromState, readChar, true); this.drawTape(tape, pointerIndex); Thread.Sleep(SLEEP_AMOUNT); //light end //this.initialDrawing(); this.clearEdge(fromState, readChar,true); this.clearEdge(fromState, readChar, false); // for more accurate erase this.clearState(toState, false); this.drawState(toState, true, this.stateGUITable[toState].getState().IsFinal); this.drawEdge(fromState, readChar, false); this.lastTape = tape; this.lastPointerIndex = pointerIndex; this.stepIndex++; } public bool isLastStep() { return this.stepIndex == this.steps.Count; } public void drawLastStep() { if (this.steps.Count <= 1) return; this.stepIndex = this.steps.Count - 1; string[] tokens = this.steps[this.stepIndex].Split(new char[] { ' ' }); string fromState = tokens[0]; string toState = tokens[1]; char readChar = tokens[2][0]; string tape = tokens[3]; int pointerIndex = int.Parse(tokens[4]); this.graphics.Clear(CLEAR_COLOR); this.initialDrawing(); this.drawState(toState, true, this.stateGUITable[toState].getState().IsFinal); this.drawTape(tape, pointerIndex); this.lastTape = tape; this.lastPointerIndex = pointerIndex; this.stepIndex++; } public void drawTuringMachine() { string[] tokens = this.steps[0].Split(new char[] { ' ' }); this.startState = tokens[0]; string initialTape = tokens[1]; int pointerIndex = int.Parse(tokens[2]); this.graphics.Clear(CLEAR_COLOR); this.initialDrawing(); bool isFinal = this.stateGUITable[this.startState].getState().IsFinal; this.drawState(this.startState, true, isFinal); this.drawTape(initialTape, pointerIndex); this.lastTape = initialTape; this.lastPointerIndex = pointerIndex; } public void reDraw() { if (this.stepIndex == 1) this.drawTuringMachine(); else if (this.stepIndex > 1) { this.stepIndex--; string[] tokens = this.steps[this.stepIndex].Split(new char[] { ' ' }); string fromState = tokens[0]; string toState = tokens[1]; char readChar = tokens[2][0]; string tape = tokens[3]; int pointerIndex = int.Parse(tokens[4]); this.initialDrawing(); this.drawState(toState, true, this.stateGUITable[toState].getState().IsFinal); this.drawTape(tape, pointerIndex); this.stepIndex++; } } private void initialDrawing() { // this.graphics.Clear(Color.White); this.drawEnterArrow(); List<string> IDs = new List<string>(this.stateGUITable.Keys); for (int i = 0; i < IDs.Count; ++i) { bool isFinal = this.stateGUITable[IDs[i]].getState().IsFinal; this.drawState(IDs[i], false, isFinal); } List<KeyValuePair<State, char>> edgeKeys = new List<KeyValuePair<State, char>>(this.edgeGUITable.Keys); foreach (KeyValuePair<State, char> edge in edgeKeys) { this.drawEdge(edge.Key.StateID, edge.Value, false); } } private void drawState(string name, bool highlight, bool final) { //getState GUIState guiState = this.stateGUITable [name]; //draw SolidBrush brush; Pen pen; if (highlight) { pen = new Pen (CIRCLE_COLOR_HIGHLIGHTED, WIDTH_HIGHLIGHTED); brush = new SolidBrush (CIRCLE_COLOR_HIGHLIGHTED); } else { pen = new Pen(CIRCLE_COLOR_NORMAL, WIDTH_NORMAL); brush = new SolidBrush (CIRCLE_COLOR_NORMAL); } //Circle Point cornerPoint = new Point (guiState.Position.X - CIRCLE_RADIUS, guiState.Position.Y - CIRCLE_RADIUS); Rectangle boundedRect = new Rectangle (cornerPoint, new Size (2 * CIRCLE_RADIUS, 2 * CIRCLE_RADIUS)); this.graphics.FillEllipse (brush, boundedRect); if (final) { Point corner = new Point(guiState.Position.X - CIRCLE_RADIUS_SPECIAL, guiState.Position.Y - CIRCLE_RADIUS_SPECIAL); Rectangle smallBoundRect = new Rectangle(corner, new Size(2 * CIRCLE_RADIUS_SPECIAL, 2 * CIRCLE_RADIUS_SPECIAL)); Pen innerPen = new Pen(CIRCLE_COLOR_SPECIAL,WIDTH_NORMAL); this.graphics.DrawEllipse(innerPen, smallBoundRect); innerPen.Dispose(); } //String brush.Color = CIRCLE_STRING_COLOR; cornerPoint = new Point(guiState.Position.X - CIRCLE_RADIUS / 2, guiState.Position.Y - CIRCLE_RADIUS / 2); Font font; if (highlight) font = FONT_HIGHLIGHTED; else font = FONT_NORMAL; this.graphics.DrawString(guiState.getState().StateID, font, brush, cornerPoint); //End brush.Dispose (); pen.Dispose(); //this.graphics.Dispose (); } #region Edge Drawing private void drawEdge(string fromID, char read, bool highlight) { KeyValuePair<State, char> key = new KeyValuePair<State, char> (this.stateGUITable [fromID].getState (), read); Transition transition = this.edgeGUITable [key].getTransition (); //draw SolidBrush brush; Pen pen; Font font; if (highlight) { pen = new Pen (LINE_COLOR_HIGHLIGHTED, WIDTH_HIGHLIGHTED); brush = new SolidBrush(LINE_STRING_COLOR_HIGHLIGHTED); font = FONT_HIGHLIGHTED; } else { pen = new Pen (LINE_COLOR_NORMAL, WIDTH_NORMAL); brush = new SolidBrush(LINE_STRING_COLOR_NORMAL); font = FONT_NORMAL; } pen.StartCap = LineCap.Round; pen.EndCap = LineCap.ArrowAnchor; if (this.edgeGUITable [key].IsSelfLoop) { Point stringPoint = new Point(); List<Point> curvePoint = this.getSelfCurvePointsAndStringPoint(this.stateGUITable[transition.From.StateID].Position, this.edgeGUITable[key].Angle, ref stringPoint); //Draw Curve this.graphics.DrawBeziers(pen, curvePoint.ToArray()); //Draw String this.graphics.DrawString(this.getTransitionString(transition), font, brush, stringPoint); } else { Point startPoint = new Point(this.stateGUITable[transition.From.StateID].Position.X, this.stateGUITable[transition.From.StateID].Position.Y); Point endPoint = new Point(this.stateGUITable[transition.To.StateID].Position.X, this.stateGUITable[transition.To.StateID].Position.Y); bool isUpOrLEFT = true; // example: q0 -> q1 if (transition.From.StateID.CompareTo(transition.To.StateID) < 0) { isUpOrLEFT = true; } else if (transition.From.StateID.CompareTo(transition.To.StateID) < 0){ isUpOrLEFT = false; } Point stringPoint = new Point(); List<Point> curvePoints = this.getCurvePointsAndStringPoint(startPoint, endPoint, isUpOrLEFT, ref stringPoint); //Draw Curve this.graphics.DrawCurve(pen, curvePoints.ToArray()); //Draw String if (this.searchForDublication(transition.From, transition.To, transition.Read)) stringPoint.Y -= DUPLICATION_SHIFT; this.graphics.DrawString(this.getTransitionString(transition), font, brush, stringPoint); } pen.Dispose(); brush.Dispose(); } private List<Point> getCurvePointsAndStringPoint(Point start, Point end, bool isUpOrLEFT, ref Point stringPoint) { int LINE_SHIFT_AMOUNT = 15; double ANGLE_SHIFT_AMOUNT = 0.34; // radius double angleBetweenCenters = Math.Atan2((end.Y - start.Y), (end.X - start.X)); // winFrom coordinate - | - // + | + // Swaping between lines if (end.X <= start.X) LINE_SHIFT_AMOUNT *= -1; if (isUpOrLEFT){ LINE_SHIFT_AMOUNT *= -1; ANGLE_SHIFT_AMOUNT *= -1; } start.X += (int)(CIRCLE_RADIUS * Math.Cos(angleBetweenCenters + ANGLE_SHIFT_AMOUNT)); start.Y += (int)(CIRCLE_RADIUS * Math.Sin(angleBetweenCenters + ANGLE_SHIFT_AMOUNT)); end.X += (int)(CIRCLE_RADIUS * Math.Cos(angleBetweenCenters - ANGLE_SHIFT_AMOUNT + Math.PI)); end.Y += (int)(CIRCLE_RADIUS * Math.Sin(angleBetweenCenters - ANGLE_SHIFT_AMOUNT + Math.PI)); double deltaX = end.X - start.X; double deltaY = end.Y - start.Y; int numOfPoints = 4; List<Point> curvePoints = new List<Point>(); for (int i = 0; i < numOfPoints; ++i) { if (i == 0) curvePoints.Add(start); else if (i == numOfPoints - 1) curvePoints.Add(end); else { double segmentXLength = deltaX / (numOfPoints - 1); double segmentYLength = deltaY / (numOfPoints - 1); int X = (int)(start.X + i * segmentXLength + LINE_SHIFT_AMOUNT); int Y = (int)(start.Y + i * segmentYLength + LINE_SHIFT_AMOUNT); curvePoints.Add(new Point(X, Y)); } } int X_SHIFT = 30; int Y_SHIFT = 20; stringPoint = new Point((int)(start.X + (deltaX / 2) + LINE_SHIFT_AMOUNT - X_SHIFT), (int)(start.Y + (deltaY / 2) + LINE_SHIFT_AMOUNT - Y_SHIFT)); return curvePoints; } private List<Point> getSelfCurvePointsAndStringPoint(Point center, double angle, ref Point stringPoint) { angle *= -1; // convert to winForm coordinates angle = (float)((angle / 180) * Math.PI); // convert to radius double ANGLE_SHIFT_AMOUNT = Math.PI/6; // radius float CURVE_HEIGHT = 3; Point start = new Point(center.X + (int)(CIRCLE_RADIUS * Math.Cos(angle - ANGLE_SHIFT_AMOUNT)), center.Y + (int)(CIRCLE_RADIUS * Math.Sin(angle - ANGLE_SHIFT_AMOUNT))); Point end = new Point(center.X + (int)(CIRCLE_RADIUS * Math.Cos(angle + ANGLE_SHIFT_AMOUNT)), center.Y + (int)(CIRCLE_RADIUS * Math.Sin(angle + ANGLE_SHIFT_AMOUNT))); Point middle1 = new Point(center.X + (int)(CURVE_HEIGHT * CIRCLE_RADIUS * Math.Cos(angle - ANGLE_SHIFT_AMOUNT)), center.Y + (int)(CURVE_HEIGHT * CIRCLE_RADIUS * Math.Sin(angle - ANGLE_SHIFT_AMOUNT))); Point middle2 = new Point(center.X + (int)(CURVE_HEIGHT * CIRCLE_RADIUS * Math.Cos(angle + ANGLE_SHIFT_AMOUNT)), center.Y + (int)(CURVE_HEIGHT * CIRCLE_RADIUS * Math.Sin(angle + ANGLE_SHIFT_AMOUNT))); List<Point> curvePoints = new List<Point>(); curvePoints.Add(start); curvePoints.Add(middle1); curvePoints.Add(middle2); curvePoints.Add(end); if (Math.PI >= angle && angle >= -Math.PI / 2) CURVE_HEIGHT = 2.4F; stringPoint = new Point(center.X + (int)(CURVE_HEIGHT * CIRCLE_RADIUS * Math.Cos(angle)), center.Y + (int)(CURVE_HEIGHT * CIRCLE_RADIUS * Math.Sin(angle))); return curvePoints; } private string getTransitionString(Transition transition) { string transString; switch (transition.Movement) { case TapeMoves.Left: transString = string.Format("{0}|{1},{2}", transition.Read, transition.Write, "L"); break; case TapeMoves.Right: transString = string.Format("{0}|{1},{2}", transition.Read, transition.Write, "R"); break; case TapeMoves.Stable: transString = string.Format("{0}|{1},{2}", transition.Read, transition.Write, "S"); break; default: throw new Exception("Not Implemented Yet"); } return transString; } #endregion private bool searchForDublication(State from, State to, char read) { List<GUITransition> value = new List<GUITransition>(this.edgeGUITable.Values); foreach (GUITransition guiT in value) { Transition t = guiT.getTransition(); if (t.From == from && t.To == to && t.Read != read) return true; else if (t.From == from && t.To == to && t.Read == read) return false; } return false; } private void drawTape(string currentTape, int pointerIndex) { Pen pen = new Pen(TAPE_COLOR, WIDTH_NORMAL); SolidBrush brush = new SolidBrush(TAPE_CHAR_COLOR); SizeF rectangleSize = graphics.MeasureString("#", TAPE_FONT); if (rectangleSize.Width * (pointerIndex + 1) > this.graphics.VisibleClipBounds.Width) { int diff = (int)(rectangleSize.Width * currentTape.Length - this.graphics.VisibleClipBounds.Width); int numOfCharToCut = diff / (int)rectangleSize.Width; currentTape = currentTape.Substring(numOfCharToCut); pointerIndex -= numOfCharToCut; } int xPosition = 0; Point pointerPoint = new Point(); for (int i = 0; i < currentTape.Length; ++i) { Point corner = new Point(xPosition, TAPE_HEIGHT); if (i == pointerIndex) { pointerPoint = corner; brush.Color = TAPE_CHAR_POINTER_COLOR; graphics.DrawString(currentTape[i].ToString(), TAPE_FONT, brush, corner); } else { brush.Color = TAPE_CHAR_COLOR; graphics.DrawString(currentTape[i].ToString(), TAPE_FONT, brush, corner); graphics.DrawRectangle(pen, new Rectangle(corner, new Size((int)rectangleSize.Width, (int)rectangleSize.Height))); } xPosition += (int)rectangleSize.Width; } pen.Width = WIDTH_HIGHLIGHTED; pen.Color = TAPE_POINTER_COLOR; graphics.DrawRectangle(pen, new Rectangle(pointerPoint, new Size((int)rectangleSize.Width, (int)rectangleSize.Height))); brush.Dispose(); pen.Dispose(); } private void drawEnterArrow() { Point center = this.stateGUITable[this.startState].Position; float angle = (float)Math.PI; int arrowLength = 20; Point endPoint = new Point((int)(center.X + CIRCLE_RADIUS * Math.Cos(angle)), (int)(center.Y + CIRCLE_RADIUS * Math.Sin(angle))); Point startPoint = new Point(endPoint.X - arrowLength, endPoint.Y); Pen pen = new Pen(LINE_COLOR_NORMAL, WIDTH_HIGHLIGHTED); pen.StartCap = LineCap.Round; pen.EndCap = LineCap.ArrowAnchor; this.graphics.DrawLine(pen, startPoint, endPoint); pen.Dispose(); } private void clearEdge(string fromID, char read, bool highlight) { Color backupLine,backupString; if (highlight) { backupLine = this.LINE_COLOR_HIGHLIGHTED; backupString = this.LINE_STRING_COLOR_HIGHLIGHTED; this.LINE_COLOR_HIGHLIGHTED = CLEAR_COLOR; this.LINE_STRING_COLOR_HIGHLIGHTED = CLEAR_COLOR; } else { backupLine = this.LINE_COLOR_NORMAL; backupString = this.LINE_STRING_COLOR_NORMAL; this.LINE_COLOR_NORMAL = CLEAR_COLOR; this.LINE_STRING_COLOR_NORMAL = CLEAR_COLOR; } this.drawEdge(fromID, read, highlight); if (highlight) { this.LINE_COLOR_HIGHLIGHTED = backupLine; this.LINE_STRING_COLOR_HIGHLIGHTED = backupString; } else { this.LINE_COLOR_NORMAL = backupLine; this.LINE_STRING_COLOR_NORMAL = backupString; } } private void clearState(string name, bool highlight) { Color backup; if (highlight) { backup = this.CIRCLE_COLOR_HIGHLIGHTED; this.CIRCLE_COLOR_HIGHLIGHTED = CLEAR_COLOR; } else { backup = this.CIRCLE_COLOR_NORMAL; this.CIRCLE_COLOR_NORMAL = CLEAR_COLOR; } this.drawState(name, highlight, false); if (highlight) { this.CIRCLE_COLOR_HIGHLIGHTED = backup; } else { this.CIRCLE_COLOR_NORMAL = backup; } } private void clearTape(string currentTape, int pointerIndex) { Color backupTapePointer, backupCharPointer; backupTapePointer = this.TAPE_POINTER_COLOR; backupCharPointer = this.TAPE_CHAR_POINTER_COLOR; this.TAPE_POINTER_COLOR = CLEAR_COLOR; this.TAPE_CHAR_POINTER_COLOR = CLEAR_COLOR; this.drawTape(currentTape, pointerIndex); this.TAPE_POINTER_COLOR = backupTapePointer; this.TAPE_CHAR_POINTER_COLOR = backupCharPointer; } public Bitmap screenShot() { return new Bitmap((int)this.graphics.VisibleClipBounds.Width, (int)this.graphics.VisibleClipBounds.Height, this.graphics); } } }
// 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 MinScalarSingle() { var test = new SimpleBinaryOpTest__MinScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MinScalarSingle { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int Op2ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static SimpleBinaryOpTest__MinScalarSingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__MinScalarSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.MinScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse.MinScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse.MinScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse).GetMethod(nameof(Sse.MinScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse).GetMethod(nameof(Sse.MinScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse).GetMethod(nameof(Sse.MinScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse.MinScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.MinScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.MinScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.MinScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__MinScalarSingle(); var result = Sse.MinScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse.MinScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(Math.Min(left[0], right[0])) != BitConverter.SingleToInt32Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.MinScalar)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// // This file is part of the game Voxalia, created by FreneticXYZ. // This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license. // See README.md or LICENSE.txt for contents of the MIT license. // If these are not available, see https://opensource.org/licenses/MIT // namespace Voxalia.Shared // mcmonkey - namespace change { // mcmonkey - NOTE TO READERS: This class was found elsewhere. Can't locate a link to it. // mcmonkey - Original header is below, though I removed some unicode from the name to avoid file errors. // mcmonkey - ORIGINAL HEADER BEGIN // SimplexNoise for C# // Author: Heikki Tormala //This is free and unencumbered software released into the public domain. //Anyone is free to copy, modify, publish, use, compile, sell, or //distribute this software, either in source code form or as a compiled //binary, for any purpose, commercial or non-commercial, and by any //means. //In jurisdictions that recognize copyright laws, the author or authors //of this software dedicate any and all copyright interest in the //software to the public domain. We make this dedication for the benefit //of the public at large and to the detriment of our heirs and //successors. We intend this dedication to be an overt act of //relinquishment in perpetuity of all present and future rights to this //software under copyright law. //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 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. //For more information, please refer to http://unlicense.org/ // mcmonkey - ORIGINAL HEADER END // This class all mcmonkey public class SimplexNoise { public static double Generate(double x, double y) { x = System.Math.Abs(x); y = System.Math.Abs(y); return (SimplexNoiseInternal.Generate(x, y) + 1f) * 0.5f; } public static double Generate(double x, double y, double z) { x = System.Math.Abs(x); y = System.Math.Abs(y); z = System.Math.Abs(z); return (SimplexNoiseInternal.Generate(x, y, z) + 1f) * 0.5f; } } // mcmonkey - Below code changed from float to double. /// <summary> /// Implementation of the Perlin simplex noise, an improved Perlin noise algorithm. /// Based loosely on SimplexNoise1234 by Stefan Gustavson http://staffwww.itn.liu.se/~stegu/aqsis/aqsis-newnoise/ /// </summary> public class SimplexNoiseInternal // mcmonkey - class rename { /// <summary> /// 1D simplex noise /// </summary> /// <param name="x">.</param> /// <returns>.</returns> public static double Generate(double x) { long i0 = FastFloor(x); long i1 = i0 + 1; double x0 = x - i0; double x1 = x0 - 1.0f; double n0, n1; double t0 = 1.0f - x0 * x0; t0 *= t0; n0 = t0 * t0 * grad(perm[i0 & 0xff], x0); double t1 = 1.0f - x1 * x1; t1 *= t1; n1 = t1 * t1 * grad(perm[i1 & 0xff], x1); // The maximum value of this noise is 8*(3/4)^4 = 2.53125 // A factor of 0.395 scales to fit exactly within [-1,1] return 0.395f * (n0 + n1); } /// <summary> /// 2D simplex noise /// </summary> /// <param name="x">.</param> /// <param name="y">.</param> /// <returns>.</returns> public static double Generate(double x, double y) { const double F2 = 0.366025403f; // F2 = 0.5*(sqrt(3.0)-1.0) const double G2 = 0.211324865f; // G2 = (3.0-Math.sqrt(3.0))/6.0 double n0, n1, n2; // Noise contributions from the three corners // Skew the input space to determine which simplex cell we're in double s = (x + y) * F2; // Hairy factor for 2D double xs = x + s; double ys = y + s; long i = FastFloor(xs); long j = FastFloor(ys); double t = (double)(i + j) * G2; double X0 = i - t; // Unskew the cell origin back to (x,y) space double Y0 = j - t; double x0 = x - X0; // The x,y distances from the cell origin double y0 = y - Y0; // For the 2D case, the simplex shape is an equilateral triangle. // Determine which simplex we are in. int i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords if (x0 > y0) { i1 = 1; j1 = 0; } // lower triangle, XY order: (0,0)->(1,0)->(1,1) else { i1 = 0; j1 = 1; } // upper triangle, YX order: (0,0)->(0,1)->(1,1) // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where // c = (3-sqrt(3))/6 double x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords double y1 = y0 - j1 + G2; double x2 = x0 - 1.0f + 2.0f * G2; // Offsets for last corner in (x,y) unskewed coords double y2 = y0 - 1.0f + 2.0f * G2; // Wrap the integer indices at 256, to avoid indexing perm[] out of bounds long ii = i % 256; long jj = j % 256; // Calculate the contribution from the three corners double t0 = 0.5f - x0 * x0 - y0 * y0; if (t0 < 0.0f) n0 = 0.0f; else { t0 *= t0; n0 = t0 * t0 * grad(perm[ii + perm[jj]], x0, y0); } double t1 = 0.5f - x1 * x1 - y1 * y1; if (t1 < 0.0f) n1 = 0.0f; else { t1 *= t1; n1 = t1 * t1 * grad(perm[ii + i1 + perm[jj + j1]], x1, y1); } double t2 = 0.5f - x2 * x2 - y2 * y2; if (t2 < 0.0f) n2 = 0.0f; else { t2 *= t2; n2 = t2 * t2 * grad(perm[ii + 1 + perm[jj + 1]], x2, y2); } // Add contributions from each corner to get the final noise value. // The result is scaled to return values in the interval [-1,1]. return 40.0f * (n0 + n1 + n2); // TODO: The scale factor is preliminary! } public static double Generate(double x, double y, double z) { // Simple skewing factors for the 3D case const double F3 = 0.333333333f; const double G3 = 0.166666667f; double n0, n1, n2, n3; // Noise contributions from the four corners // Skew the input space to determine which simplex cell we're in double s = (x + y + z) * F3; // Very nice and simple skew factor for 3D double xs = x + s; double ys = y + s; double zs = z + s; long i = FastFloor(xs); long j = FastFloor(ys); long k = FastFloor(zs); double t = (double)(i + j + k) * G3; double X0 = i - t; // Unskew the cell origin back to (x,y,z) space double Y0 = j - t; double Z0 = k - t; double x0 = x - X0; // The x,y,z distances from the cell origin double y0 = y - Y0; double z0 = z - Z0; // For the 3D case, the simplex shape is a slightly irregular tetrahedron. // Determine which simplex we are in. long i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords long i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords /* This code would benefit from a backport from the GLSL version! */ if (x0 >= y0) { if (y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } // X Y Z order else if (x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; } // X Z Y order else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; } // Z X Y order } else { // x0<y0 if (y0 < z0) { i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1; } // Z Y X order else if (x0 < z0) { i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1; } // Y Z X order else { i1 = 0; j1 = 1; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } // Y X Z order } // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z), // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where // c = 1/6. double x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords double y1 = y0 - j1 + G3; double z1 = z0 - k1 + G3; double x2 = x0 - i2 + 2.0f * G3; // Offsets for third corner in (x,y,z) coords double y2 = y0 - j2 + 2.0f * G3; double z2 = z0 - k2 + 2.0f * G3; double x3 = x0 - 1.0f + 3.0f * G3; // Offsets for last corner in (x,y,z) coords double y3 = y0 - 1.0f + 3.0f * G3; double z3 = z0 - 1.0f + 3.0f * G3; // Wrap the integer indices at 256, to avoid indexing perm[] out of bounds long ii = Mod(i, 256); long jj = Mod(j, 256); long kk = Mod(k, 256); // Calculate the contribution from the four corners double t0 = 0.6f - x0 * x0 - y0 * y0 - z0 * z0; if (t0 < 0.0f) n0 = 0.0f; else { t0 *= t0; n0 = t0 * t0 * grad(perm[ii + perm[jj + perm[kk]]], x0, y0, z0); } double t1 = 0.6f - x1 * x1 - y1 * y1 - z1 * z1; if (t1 < 0.0f) n1 = 0.0f; else { t1 *= t1; n1 = t1 * t1 * grad(perm[ii + i1 + perm[jj + j1 + perm[kk + k1]]], x1, y1, z1); } double t2 = 0.6f - x2 * x2 - y2 * y2 - z2 * z2; if (t2 < 0.0f) n2 = 0.0f; else { t2 *= t2; n2 = t2 * t2 * grad(perm[ii + i2 + perm[jj + j2 + perm[kk + k2]]], x2, y2, z2); } double t3 = 0.6f - x3 * x3 - y3 * y3 - z3 * z3; if (t3 < 0.0f) n3 = 0.0f; else { t3 *= t3; n3 = t3 * t3 * grad(perm[ii + 1 + perm[jj + 1 + perm[kk + 1]]], x3, y3, z3); } // Add contributions from each corner to get the final noise value. // The result is scaled to stay just inside [-1,1] return 32.4f * (n0 + n1 + n2 + n3); // TODO: The scale factor is preliminary! // mcmonkey - improve scaling factor from 32.0 } public static byte[] perm = new byte[512] { 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180, 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 }; private static long FastFloor(double x) { return (x > 0) ? ((long)x) : (((long)x) - 1); } private static long Mod(long x, long m) { long a = x % m; return a < 0 ? a + m : a; } private static double grad(long hash, double x) { long h = hash & 15; double grad = 1.0f + (h & 7); // Gradient value 1.0, 2.0, ..., 8.0 if ((h & 8) != 0) grad = -grad; // Set a random sign for the gradient return (grad * x); // Multiply the gradient with the distance } private static double grad(long hash, double x, double y) { long h = hash & 7; // Convert low 3 bits of hash code double u = h < 4 ? x : y; // into 8 simple gradient directions, double v = h < 4 ? y : x; // and compute the dot product with (x,y). return ((h & 1) != 0 ? -u : u) + ((h & 2) != 0 ? -2.0f * v : 2.0f * v); } private static double grad(long hash, double x, double y, double z) { long h = hash & 15; // Convert low 4 bits of hash code into 12 simple double u = h < 8 ? x : y; // gradient directions, and compute dot product. double v = h < 4 ? y : h == 12 || h == 14 ? x : z; // Fix repeats at h = 12 to 15 return ((h & 1) != 0 ? -u : u) + ((h & 2) != 0 ? -v : v); } private static double grad(long hash, double x, double y, double z, double t) { long h = hash & 31; // Convert low 5 bits of hash code into 32 simple double u = h < 24 ? x : y; // gradient directions, and compute dot product. double v = h < 16 ? y : z; double w = h < 8 ? z : t; return ((h & 1) != 0 ? -u : u) + ((h & 2) != 0 ? -v : v) + ((h & 4) != 0 ? -w : w); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Infrastructure { using System.Data.Common; using System.Data.Entity.Core.EntityClient; using System.Data.Entity.Infrastructure.Interception; using System.Data.Entity.Resources; using System.Data.Entity.TestDoubles; using System.Linq; using System.Threading; using System.Threading.Tasks; using Moq; using Moq.Protected; using Xunit; using MockHelper = System.Data.Entity.Core.Objects.MockHelper; public class CommitFailureHandlerTests { public class Initialize : TestBase { [Fact] public void Initializes_with_ObjectContext() { var context = MockHelper.CreateMockObjectContext<object>(); using (var handler = new CommitFailureHandler()) { handler.Initialize(context); Assert.Same(context, handler.ObjectContext); Assert.Same(context.InterceptionContext.DbContexts.FirstOrDefault(), handler.DbContext); Assert.Same(((EntityConnection)context.Connection).StoreConnection, handler.Connection); Assert.Same(((EntityConnection)context.Connection).StoreConnection, handler.Connection); Assert.IsType<TransactionContext>(handler.TransactionContext); } } [Fact] public void Initializes_with_DbContext() { var context = new DbContext("c"); using (var handler = new CommitFailureHandler()) { handler.Initialize(context, context.Database.Connection); Assert.Null(handler.ObjectContext); Assert.Same(context, handler.DbContext); Assert.Same(context.Database.Connection, handler.Connection); Assert.IsType<TransactionContext>(handler.TransactionContext); } } [Fact] public void Throws_for_null_parameters() { using (var handler = new CommitFailureHandler()) { Assert.Equal( "connection", Assert.Throws<ArgumentNullException>(() => handler.Initialize(new DbContext("c"), null)).ParamName); Assert.Equal( "context", Assert.Throws<ArgumentNullException>(() => handler.Initialize(null, new Mock<DbConnection>().Object)).ParamName); Assert.Equal( "context", Assert.Throws<ArgumentNullException>(() => handler.Initialize(null)).ParamName); } } [Fact] public void Throws_if_already_initialized_with_ObjectContext() { var context = MockHelper.CreateMockObjectContext<object>(); using (var handler = new CommitFailureHandler()) { handler.Initialize(context); Assert.Equal( Strings.TransactionHandler_AlreadyInitialized, Assert.Throws<InvalidOperationException>(() => handler.Initialize(context)).Message); var dbContext = new DbContext("c"); Assert.Equal( Strings.TransactionHandler_AlreadyInitialized, Assert.Throws<InvalidOperationException>(() => handler.Initialize(dbContext, dbContext.Database.Connection)).Message); } } [Fact] public void Throws_if_already_initialized_with_DbContext() { var dbContext = new DbContext("c"); using (var handler = new CommitFailureHandler()) { handler.Initialize(dbContext, dbContext.Database.Connection); var context = MockHelper.CreateMockObjectContext<object>(); Assert.Equal( Strings.TransactionHandler_AlreadyInitialized, Assert.Throws<InvalidOperationException>(() => handler.Initialize(context)).Message); Assert.Equal( Strings.TransactionHandler_AlreadyInitialized, Assert.Throws<InvalidOperationException>(() => handler.Initialize(dbContext, dbContext.Database.Connection)).Message); } } } public class Dispose : TestBase { [Fact] public void Removes_interceptor() { var mockConnection = new Mock<DbConnection>().Object; var handlerMock = new Mock<CommitFailureHandler> { CallBase = true }; using (handlerMock.Object) { DbInterception.Dispatch.Connection.Close(mockConnection, new DbInterceptionContext()); handlerMock.Verify(m => m.Closed(It.IsAny<DbConnection>(), It.IsAny<DbConnectionInterceptionContext>()), Times.Once()); handlerMock.Object.Dispose(); DbInterception.Dispatch.Connection.Close(mockConnection, new DbInterceptionContext()); handlerMock.Verify(m => m.Closed(It.IsAny<DbConnection>(), It.IsAny<DbConnectionInterceptionContext>()), Times.Once()); } } [Fact] public void Delegates_to_protected_method() { var context = MockHelper.CreateMockObjectContext<int>(); var commitFailureHandlerMock = CreateCommitFailureHandlerMock(); commitFailureHandlerMock.Object.Initialize(context); using (var handler = commitFailureHandlerMock.Object) { handler.Dispose(); commitFailureHandlerMock.Protected().Verify("Dispose", Times.Once(), true); } } [Fact] public void Can_be_invoked_twice_without_throwing() { var handler = new CommitFailureHandler(); handler.Dispose(); handler.Dispose(); } } public class MatchesParentContext : TestBase { [Fact] public void Throws_for_null_parameters() { using (var handler = new CommitFailureHandler()) { Assert.Equal( "connection", Assert.Throws<ArgumentNullException>(() => handler.MatchesParentContext(null, new DbInterceptionContext())) .ParamName); Assert.Equal( "interceptionContext", Assert.Throws<ArgumentNullException>(() => handler.MatchesParentContext(new Mock<DbConnection>().Object, null)) .ParamName); } } [Fact] public void Returns_false_with_DbContext_if_nothing_matches() { using (var handler = new CommitFailureHandler()) { handler.Initialize(new DbContext("c"), CreateMockConnection()); Assert.False( handler.MatchesParentContext( new Mock<DbConnection>().Object, new DbInterceptionContext().WithObjectContext(MockHelper.CreateMockObjectContext<object>()) .WithDbContext(new DbContext("c")))); } } [Fact] public void Returns_false_with_DbContext_if_different_context_same_connection() { var connection = CreateMockConnection(); using (var handler = new CommitFailureHandler()) { handler.Initialize(new DbContext("c"), connection); Assert.False( handler.MatchesParentContext( connection, new DbInterceptionContext().WithObjectContext(MockHelper.CreateMockObjectContext<object>()) .WithDbContext(new DbContext("c")))); } } [Fact] public void Returns_true_with_DbContext_if_same_context() { var context = new DbContext("c"); using (var handler = new CommitFailureHandler()) { handler.Initialize(context, CreateMockConnection()); Assert.True( handler.MatchesParentContext( new Mock<DbConnection>().Object, new DbInterceptionContext().WithObjectContext(MockHelper.CreateMockObjectContext<object>()) .WithDbContext(context))); } } [Fact] public void Returns_true_with_DbContext_if_no_context_same_connection() { var connection = CreateMockConnection(); using (var handler = new CommitFailureHandler()) { handler.Initialize(new DbContext("c"), connection); Assert.True( handler.MatchesParentContext( connection, new DbInterceptionContext())); } } [Fact] public void Returns_false_with_ObjectContext_if_nothing_matches() { using (var handler = new CommitFailureHandler()) { handler.Initialize(MockHelper.CreateMockObjectContext<object>()); Assert.False( handler.MatchesParentContext( new Mock<DbConnection>().Object, new DbInterceptionContext().WithObjectContext(MockHelper.CreateMockObjectContext<object>()) .WithDbContext(new DbContext("c")))); } } [Fact] public void Returns_false_with_ObjectContext_if_different_context_same_connection() { var context = MockHelper.CreateMockObjectContext<object>(); using (var handler = new CommitFailureHandler()) { handler.Initialize(context); Assert.False( handler.MatchesParentContext( ((EntityConnection)context.Connection).StoreConnection, new DbInterceptionContext().WithObjectContext(MockHelper.CreateMockObjectContext<object>()) .WithDbContext(new DbContext("c")))); } } [Fact] public void Returns_true_with_ObjectContext_if_same_ObjectContext() { var context = MockHelper.CreateMockObjectContext<object>(); using (var handler = new CommitFailureHandler()) { handler.Initialize(context); Assert.True( handler.MatchesParentContext( new Mock<DbConnection>().Object, new DbInterceptionContext().WithObjectContext(context) .WithDbContext(new DbContext("c")))); } } [Fact] public void Returns_true_with_ObjectContext_if_no_context_same_connection() { var context = MockHelper.CreateMockObjectContext<object>(); using (var handler = new CommitFailureHandler()) { handler.Initialize(context); Assert.True( handler.MatchesParentContext( ((EntityConnection)context.Connection).StoreConnection, new DbInterceptionContext())); } } } public class PruneTransactionHistory : TestBase { [Fact] public void Delegates_to_protected_method() { var handlerMock = new Mock<CommitFailureHandler> { CallBase = true }; handlerMock.Protected().Setup("PruneTransactionHistory", ItExpr.IsAny<bool>(), ItExpr.IsAny<bool>()).Callback(() => { }); using (var handler = handlerMock.Object) { handler.PruneTransactionHistory(); handlerMock.Protected().Verify("PruneTransactionHistory", Times.Once(), true, true); } } } #if !NET40 public class PruneTransactionHistoryAsync : TestBase { [Fact] public void Delegates_to_protected_method() { var handlerMock = new Mock<CommitFailureHandler> { CallBase = true }; handlerMock.Protected().Setup<Task>("PruneTransactionHistoryAsync", ItExpr.IsAny<bool>(), ItExpr.IsAny<bool>(), ItExpr.IsAny<CancellationToken>()) .Returns(() => Task.FromResult(true)); using (var handler = handlerMock.Object) { handler.PruneTransactionHistoryAsync().Wait(); handlerMock.Protected().Verify<Task>("PruneTransactionHistoryAsync", Times.Once(), true, true, CancellationToken.None); } } [Fact] public void Delegates_to_protected_method_with_CancelationToken() { var handlerMock = new Mock<CommitFailureHandler> { CallBase = true }; handlerMock.Protected().Setup<Task>("PruneTransactionHistoryAsync", ItExpr.IsAny<bool>(), ItExpr.IsAny<bool>(), ItExpr.IsAny<CancellationToken>()) .Returns(() => Task.FromResult(true)); using (var handler = handlerMock.Object) { var token = new CancellationToken(); handler.PruneTransactionHistoryAsync(token).Wait(); handlerMock.Protected().Verify<Task>("PruneTransactionHistoryAsync", Times.Once(), true, true, token); } } } #endif public class ClearTransactionHistory : TestBase { [Fact] public void Delegates_to_protected_method() { var context = MockHelper.CreateMockObjectContext<int>(); var commitFailureHandlerMock = CreateCommitFailureHandlerMock(); commitFailureHandlerMock.Object.Initialize(context); using (var handler = commitFailureHandlerMock.Object) { handler.ClearTransactionHistory(); commitFailureHandlerMock.Protected().Verify("PruneTransactionHistory", Times.Once(), true, true); } } } #if !NET40 public class ClearTransactionHistoryAsync : TestBase { [Fact] public void Delegates_to_protected_method() { var context = MockHelper.CreateMockObjectContext<int>(); var commitFailureHandlerMock = CreateCommitFailureHandlerMock(); commitFailureHandlerMock.Object.Initialize(context); using (var handler = commitFailureHandlerMock.Object) { handler.ClearTransactionHistoryAsync().Wait(); commitFailureHandlerMock.Protected() .Verify<Task>("PruneTransactionHistoryAsync", Times.Once(), true, true, CancellationToken.None); } } [Fact] public void Delegates_to_protected_method_with_CancelationToken() { var context = MockHelper.CreateMockObjectContext<int>(); var commitFailureHandlerMock = CreateCommitFailureHandlerMock(); commitFailureHandlerMock.Object.Initialize(context); using (var handler = commitFailureHandlerMock.Object) { var token = new CancellationToken(); handler.ClearTransactionHistoryAsync(token).Wait(); commitFailureHandlerMock.Protected().Verify<Task>("PruneTransactionHistoryAsync", Times.Once(), true, true, token); } } } #endif public class BeganTransaction { [Fact] public void BeganTransaction_does_not_fail_if_exception_thrown_such_that_there_is_no_transaction() { var context = MockHelper.CreateMockObjectContext<object>(); var handler = new CommitFailureHandler(); handler.Initialize(context); var interceptionContext = new BeginTransactionInterceptionContext().WithObjectContext(context); Assert.DoesNotThrow(() => handler.BeganTransaction(new Mock<DbConnection>().Object, interceptionContext)); } } private static DbConnection CreateMockConnection() { var connectionMock = new Mock<DbConnection>(); connectionMock.Protected() .Setup<DbProviderFactory>("DbProviderFactory") .Returns(GenericProviderFactory<DbProviderFactory>.Instance); return connectionMock.Object; } private static Mock<CommitFailureHandler> CreateCommitFailureHandlerMock() { Func<DbConnection, TransactionContext> transactionContextFactory = c => { var transactionContextMock = new Mock<TransactionContext>(c) { CallBase = true }; var transactionRowSet = new InMemoryDbSet<TransactionRow>(); transactionContextMock.Setup(m => m.Transactions).Returns(transactionRowSet); return transactionContextMock.Object; }; var handlerMock = new Mock<CommitFailureHandler>(transactionContextFactory) { CallBase = true }; handlerMock.Protected().Setup("PruneTransactionHistory", ItExpr.IsAny<bool>(), ItExpr.IsAny<bool>()).Callback(() => { }); #if !NET40 handlerMock.Protected() .Setup<Task>("PruneTransactionHistoryAsync", ItExpr.IsAny<bool>(), ItExpr.IsAny<bool>(), ItExpr.IsAny<CancellationToken>()) .Returns(() => Task.FromResult(true)); #endif return handlerMock; } } }
/* * Vericred API * * Vericred's API allows you to search for Health Plans that a specific doctor accepts. ## Getting Started Visit our [Developer Portal](https://developers.vericred.com) to create an account. Once you have created an account, you can create one Application for Production and another for our Sandbox (select the appropriate Plan when you create the Application). ## SDKs Our API follows standard REST conventions, so you can use any HTTP client to integrate with us. You will likely find it easier to use one of our [autogenerated SDKs](https://github.com/vericred/?query=vericred-), which we make available for several common programming languages. ## Authentication To authenticate, pass the API Key you created in the Developer Portal as a `Vericred-Api-Key` header. `curl -H 'Vericred-Api-Key: YOUR_KEY' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Versioning Vericred's API default to the latest version. However, if you need a specific version, you can request it with an `Accept-Version` header. The current version is `v3`. Previous versions are `v1` and `v2`. `curl -H 'Vericred-Api-Key: YOUR_KEY' -H 'Accept-Version: v2' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Pagination Endpoints that accept `page` and `per_page` parameters are paginated. They expose four additional fields that contain data about your position in the response, namely `Total`, `Per-Page`, `Link`, and `Page` as described in [RFC-5988](https://tools.ietf.org/html/rfc5988). For example, to display 5 results per page and view the second page of a `GET` to `/networks`, your final request would be `GET /networks?....page=2&per_page=5`. ## Sideloading When we return multiple levels of an object graph (e.g. `Provider`s and their `State`s we sideload the associated data. In this example, we would provide an Array of `State`s and a `state_id` for each provider. This is done primarily to reduce the payload size since many of the `Provider`s will share a `State` ``` { providers: [{ id: 1, state_id: 1}, { id: 2, state_id: 1 }], states: [{ id: 1, code: 'NY' }] } ``` If you need the second level of the object graph, you can just match the corresponding id. ## Selecting specific data All endpoints allow you to specify which fields you would like to return. This allows you to limit the response to contain only the data you need. For example, let's take a request that returns the following JSON by default ``` { provider: { id: 1, name: 'John', phone: '1234567890', field_we_dont_care_about: 'value_we_dont_care_about' }, states: [{ id: 1, name: 'New York', code: 'NY', field_we_dont_care_about: 'value_we_dont_care_about' }] } ``` To limit our results to only return the fields we care about, we specify the `select` query string parameter for the corresponding fields in the JSON document. In this case, we want to select `name` and `phone` from the `provider` key, so we would add the parameters `select=provider.name,provider.phone`. We also want the `name` and `code` from the `states` key, so we would add the parameters `select=states.name,staes.code`. The id field of each document is always returned whether or not it is requested. Our final request would be `GET /providers/12345?select=provider.name,provider.phone,states.name,states.code` The response would be ``` { provider: { id: 1, name: 'John', phone: '1234567890' }, states: [{ id: 1, name: 'New York', code: 'NY' }] } ``` ## Benefits summary format Benefit cost-share strings are formatted to capture: * Network tiers * Compound or conditional cost-share * Limits on the cost-share * Benefit-specific maximum out-of-pocket costs **Example #1** As an example, we would represent [this Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/33602TX0780032.pdf) as: * **Hospital stay facility fees**: - Network Provider: `$400 copay/admit plus 20% coinsurance` - Out-of-Network Provider: `$1,500 copay/admit plus 50% coinsurance` - Vericred's format for this benefit: `In-Network: $400 before deductible then 20% after deductible / Out-of-Network: $1,500 before deductible then 50% after deductible` * **Rehabilitation services:** - Network Provider: `20% coinsurance` - Out-of-Network Provider: `50% coinsurance` - Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.` - Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Period` **Example #2** In [this other Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/40733CA0110568.pdf), the **specialty_drugs** cost-share has a maximum out-of-pocket for in-network pharmacies. * **Specialty drugs:** - Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply` - Out-of-Network Provider `Not covered` - Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Network: 100%` **BNF** Here's a description of the benefits summary string, represented as a context-free grammar: ``` <cost-share> ::= <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> <tier-limit> "/" <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> "|" <benefit-limit> <tier> ::= "In-Network:" | "In-Network-Tier-2:" | "Out-of-Network:" <opt-num-prefix> ::= "first" <num> <unit> | "" <unit> ::= "day(s)" | "visit(s)" | "exam(s)" | "item(s)" <value> ::= <ddct_moop> | <copay> | <coinsurance> | <compound> | "unknown" | "Not Applicable" <compound> ::= <copay> <deductible> "then" <coinsurance> <deductible> | <copay> <deductible> "then" <copay> <deductible> | <coinsurance> <deductible> "then" <coinsurance> <deductible> <copay> ::= "$" <num> <coinsurace> ::= <num> "%" <ddct_moop> ::= <copay> | "Included in Medical" | "Unlimited" <opt-per-unit> ::= "per day" | "per visit" | "per stay" | "" <deductible> ::= "before deductible" | "after deductible" | "" <tier-limit> ::= ", " <limit> | "" <benefit-limit> ::= <limit> | "" ``` * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Collections.ObjectModel; using System.Linq; using RestSharp; using IO.Vericred.Client; using IO.Vericred.Model; namespace IO.Vericred.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface INetworkSizesApi : IApiAccessor { #region Synchronous Operations /// <summary> /// State Network Sizes /// </summary> /// <remarks> /// The number of in-network Providers for each network in a given state. This data is recalculated nightly. The endpoint is paginated. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="stateId">State code</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>StateNetworkSizeResponse</returns> StateNetworkSizeResponse ListStateNetworkSizes (string stateId, int? page = null, int? perPage = null); /// <summary> /// State Network Sizes /// </summary> /// <remarks> /// The number of in-network Providers for each network in a given state. This data is recalculated nightly. The endpoint is paginated. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="stateId">State code</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>ApiResponse of StateNetworkSizeResponse</returns> ApiResponse<StateNetworkSizeResponse> ListStateNetworkSizesWithHttpInfo (string stateId, int? page = null, int? perPage = null); /// <summary> /// Network Sizes /// </summary> /// <remarks> /// The number of in-network Providers for each network/state combination provided. This data is recalculated nightly. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>StateNetworkSizeResponse</returns> StateNetworkSizeResponse SearchNetworkSizes (StateNetworkSizeRequest body); /// <summary> /// Network Sizes /// </summary> /// <remarks> /// The number of in-network Providers for each network/state combination provided. This data is recalculated nightly. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>ApiResponse of StateNetworkSizeResponse</returns> ApiResponse<StateNetworkSizeResponse> SearchNetworkSizesWithHttpInfo (StateNetworkSizeRequest body); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// State Network Sizes /// </summary> /// <remarks> /// The number of in-network Providers for each network in a given state. This data is recalculated nightly. The endpoint is paginated. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="stateId">State code</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>Task of StateNetworkSizeResponse</returns> System.Threading.Tasks.Task<StateNetworkSizeResponse> ListStateNetworkSizesAsync (string stateId, int? page = null, int? perPage = null); /// <summary> /// State Network Sizes /// </summary> /// <remarks> /// The number of in-network Providers for each network in a given state. This data is recalculated nightly. The endpoint is paginated. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="stateId">State code</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>Task of ApiResponse (StateNetworkSizeResponse)</returns> System.Threading.Tasks.Task<ApiResponse<StateNetworkSizeResponse>> ListStateNetworkSizesAsyncWithHttpInfo (string stateId, int? page = null, int? perPage = null); /// <summary> /// Network Sizes /// </summary> /// <remarks> /// The number of in-network Providers for each network/state combination provided. This data is recalculated nightly. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of StateNetworkSizeResponse</returns> System.Threading.Tasks.Task<StateNetworkSizeResponse> SearchNetworkSizesAsync (StateNetworkSizeRequest body); /// <summary> /// Network Sizes /// </summary> /// <remarks> /// The number of in-network Providers for each network/state combination provided. This data is recalculated nightly. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of ApiResponse (StateNetworkSizeResponse)</returns> System.Threading.Tasks.Task<ApiResponse<StateNetworkSizeResponse>> SearchNetworkSizesAsyncWithHttpInfo (StateNetworkSizeRequest body); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class NetworkSizesApi : INetworkSizesApi { private IO.Vericred.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="NetworkSizesApi"/> class. /// </summary> /// <returns></returns> public NetworkSizesApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = IO.Vericred.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="NetworkSizesApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public NetworkSizesApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = IO.Vericred.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public IO.Vericred.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// State Network Sizes The number of in-network Providers for each network in a given state. This data is recalculated nightly. The endpoint is paginated. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="stateId">State code</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>StateNetworkSizeResponse</returns> public StateNetworkSizeResponse ListStateNetworkSizes (string stateId, int? page = null, int? perPage = null) { ApiResponse<StateNetworkSizeResponse> localVarResponse = ListStateNetworkSizesWithHttpInfo(stateId, page, perPage); return localVarResponse.Data; } /// <summary> /// State Network Sizes The number of in-network Providers for each network in a given state. This data is recalculated nightly. The endpoint is paginated. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="stateId">State code</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>ApiResponse of StateNetworkSizeResponse</returns> public ApiResponse< StateNetworkSizeResponse > ListStateNetworkSizesWithHttpInfo (string stateId, int? page = null, int? perPage = null) { // verify the required parameter 'stateId' is set if (stateId == null) throw new ApiException(400, "Missing required parameter 'stateId' when calling NetworkSizesApi->ListStateNetworkSizes"); var localVarPath = "/states/{state_id}/network_sizes"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (stateId != null) localVarPathParams.Add("state_id", Configuration.ApiClient.ParameterToString(stateId)); // path parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (perPage != null) localVarQueryParams.Add("per_page", Configuration.ApiClient.ParameterToString(perPage)); // query parameter // authentication (Vericred-Api-Key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"))) { localVarHeaderParams["Vericred-Api-Key"] = Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ListStateNetworkSizes", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<StateNetworkSizeResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (StateNetworkSizeResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(StateNetworkSizeResponse))); } /// <summary> /// State Network Sizes The number of in-network Providers for each network in a given state. This data is recalculated nightly. The endpoint is paginated. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="stateId">State code</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>Task of StateNetworkSizeResponse</returns> public async System.Threading.Tasks.Task<StateNetworkSizeResponse> ListStateNetworkSizesAsync (string stateId, int? page = null, int? perPage = null) { ApiResponse<StateNetworkSizeResponse> localVarResponse = await ListStateNetworkSizesAsyncWithHttpInfo(stateId, page, perPage); return localVarResponse.Data; } /// <summary> /// State Network Sizes The number of in-network Providers for each network in a given state. This data is recalculated nightly. The endpoint is paginated. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="stateId">State code</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>Task of ApiResponse (StateNetworkSizeResponse)</returns> public async System.Threading.Tasks.Task<ApiResponse<StateNetworkSizeResponse>> ListStateNetworkSizesAsyncWithHttpInfo (string stateId, int? page = null, int? perPage = null) { // verify the required parameter 'stateId' is set if (stateId == null) throw new ApiException(400, "Missing required parameter 'stateId' when calling NetworkSizesApi->ListStateNetworkSizes"); var localVarPath = "/states/{state_id}/network_sizes"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (stateId != null) localVarPathParams.Add("state_id", Configuration.ApiClient.ParameterToString(stateId)); // path parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (perPage != null) localVarQueryParams.Add("per_page", Configuration.ApiClient.ParameterToString(perPage)); // query parameter // authentication (Vericred-Api-Key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"))) { localVarHeaderParams["Vericred-Api-Key"] = Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ListStateNetworkSizes", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<StateNetworkSizeResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (StateNetworkSizeResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(StateNetworkSizeResponse))); } /// <summary> /// Network Sizes The number of in-network Providers for each network/state combination provided. This data is recalculated nightly. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>StateNetworkSizeResponse</returns> public StateNetworkSizeResponse SearchNetworkSizes (StateNetworkSizeRequest body) { ApiResponse<StateNetworkSizeResponse> localVarResponse = SearchNetworkSizesWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Network Sizes The number of in-network Providers for each network/state combination provided. This data is recalculated nightly. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>ApiResponse of StateNetworkSizeResponse</returns> public ApiResponse< StateNetworkSizeResponse > SearchNetworkSizesWithHttpInfo (StateNetworkSizeRequest body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling NetworkSizesApi->SearchNetworkSizes"); var localVarPath = "/network_sizes/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (Vericred-Api-Key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"))) { localVarHeaderParams["Vericred-Api-Key"] = Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("SearchNetworkSizes", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<StateNetworkSizeResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (StateNetworkSizeResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(StateNetworkSizeResponse))); } /// <summary> /// Network Sizes The number of in-network Providers for each network/state combination provided. This data is recalculated nightly. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of StateNetworkSizeResponse</returns> public async System.Threading.Tasks.Task<StateNetworkSizeResponse> SearchNetworkSizesAsync (StateNetworkSizeRequest body) { ApiResponse<StateNetworkSizeResponse> localVarResponse = await SearchNetworkSizesAsyncWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Network Sizes The number of in-network Providers for each network/state combination provided. This data is recalculated nightly. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of ApiResponse (StateNetworkSizeResponse)</returns> public async System.Threading.Tasks.Task<ApiResponse<StateNetworkSizeResponse>> SearchNetworkSizesAsyncWithHttpInfo (StateNetworkSizeRequest body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling NetworkSizesApi->SearchNetworkSizes"); var localVarPath = "/network_sizes/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (Vericred-Api-Key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"))) { localVarHeaderParams["Vericred-Api-Key"] = Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("SearchNetworkSizes", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<StateNetworkSizeResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (StateNetworkSizeResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(StateNetworkSizeResponse))); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.WindowsAzure.Storage.Queue; using Microsoft.WindowsAzure.Storage.RetryPolicies; using Orleans.Runtime; using Orleans.AzureUtils.Utilities; using System.Linq; using Orleans.Streaming.AzureStorage; namespace Orleans.AzureUtils { /// <summary> /// How to use the Queue Storage Service: http://www.windowsazure.com/en-us/develop/net/how-to-guides/queue-service/ /// Windows Azure Storage Abstractions and their Scalability Targets: http://blogs.msdn.com/b/windowsazurestorage/archive/2010/05/10/windows-azure-storage-abstractions-and-their-scalability-targets.aspx /// Naming Queues and Metadata: http://msdn.microsoft.com/en-us/library/windowsazure/dd179349.aspx /// Windows Azure Queues and Windows Azure Service Bus Queues - Compared and Contrasted: http://msdn.microsoft.com/en-us/library/hh767287(VS.103).aspx /// Status and Error Codes: http://msdn.microsoft.com/en-us/library/dd179382.aspx /// /// http://blogs.msdn.com/b/windowsazurestorage/archive/tags/scalability/ /// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/12/30/windows-azure-storage-architecture-overview.aspx /// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/11/06/how-to-get-most-out-of-windows-azure-tables.aspx /// /// </summary> internal static class AzureQueueDefaultPolicies { public static int MaxQueueOperationRetries; public static TimeSpan PauseBetweenQueueOperationRetries; public static TimeSpan QueueOperationTimeout; public static IRetryPolicy QueueOperationRetryPolicy; static AzureQueueDefaultPolicies() { MaxQueueOperationRetries = 5; PauseBetweenQueueOperationRetries = TimeSpan.FromMilliseconds(100); QueueOperationRetryPolicy = new LinearRetry(PauseBetweenQueueOperationRetries, MaxQueueOperationRetries); // 5 x 100ms QueueOperationTimeout = PauseBetweenQueueOperationRetries.Multiply(MaxQueueOperationRetries).Multiply(6); // 3 sec } } /// <summary> /// Utility class to encapsulate access to Azure queue storage. /// </summary> /// <remarks> /// Used by Azure queue streaming provider. /// </remarks> public class AzureQueueDataManager { /// <summary> Name of the table queue instance is managing. </summary> public string QueueName { get; private set; } private string connectionString { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] private readonly ILogger logger; private readonly TimeSpan? messageVisibilityTimeout; private readonly CloudQueueClient queueOperationsClient; private CloudQueue queue; /// <summary> /// Constructor. /// </summary> /// <param name="loggerFactory">logger factory to use</param> /// <param name="queueName">Name of the queue to be connected to.</param> /// <param name="storageConnectionString">Connection string for the Azure storage account used to host this table.</param> /// <param name="visibilityTimeout">A TimeSpan specifying the visibility timeout interval</param> public AzureQueueDataManager(ILoggerFactory loggerFactory, string queueName, string storageConnectionString, TimeSpan? visibilityTimeout = null) { queueName = SanitizeQueueName(queueName); ValidateQueueName(queueName); logger = loggerFactory.CreateLogger<AzureQueueDataManager>(); QueueName = queueName; connectionString = storageConnectionString; messageVisibilityTimeout = visibilityTimeout; queueOperationsClient = GetCloudQueueClient( connectionString, AzureQueueDefaultPolicies.QueueOperationRetryPolicy, AzureQueueDefaultPolicies.QueueOperationTimeout, logger); } /// <summary> /// Constructor. /// </summary> /// <param name="queueName">Name of the queue to be connected to.</param> /// <param name="serviceId">The service id of the silo. It will be concatenated to the queueName.</param> /// <param name="storageConnectionString">Connection string for the Azure storage account used to host this table.</param> /// <param name="visibilityTimeout">A TimeSpan specifying the visibility timeout interval</param> /// <param name="loggerFactory">logger factory used to create loggers</param> public AzureQueueDataManager(ILoggerFactory loggerFactory, string queueName, string serviceId, string storageConnectionString, TimeSpan? visibilityTimeout = null) { logger = loggerFactory.CreateLogger<AzureQueueDataManager>(); QueueName = serviceId + "-" + queueName; QueueName = SanitizeQueueName(QueueName); ValidateQueueName(QueueName); connectionString = storageConnectionString; messageVisibilityTimeout = visibilityTimeout; queueOperationsClient = GetCloudQueueClient( connectionString, AzureQueueDefaultPolicies.QueueOperationRetryPolicy, AzureQueueDefaultPolicies.QueueOperationTimeout, logger); } /// <summary> /// Initializes the connection to the queue. /// </summary> public async Task InitQueueAsync() { var startTime = DateTime.UtcNow; try { // Retrieve a reference to a queue. // Not sure if this is a blocking call or not. Did not find an alternative async API. Should probably use BeginListQueuesSegmented. var myQueue = queueOperationsClient.GetQueueReference(QueueName); // Create the queue if it doesn't already exist. bool didCreate = await myQueue.CreateIfNotExistsAsync(); queue = myQueue; logger.Info((int)AzureQueueErrorCode.AzureQueue_01, "{0} Azure storage queue {1}", (didCreate ? "Created" : "Attached to"), QueueName); } catch (Exception exc) { ReportErrorAndRethrow(exc, "CreateIfNotExist", AzureQueueErrorCode.AzureQueue_02); } finally { CheckAlertSlowAccess(startTime, "InitQueue_Async"); } } /// <summary> /// Deletes the queue. /// </summary> public async Task DeleteQueue() { var startTime = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Deleting queue: {0}", QueueName); try { // that way we don't have first to create the queue to be able later to delete it. CloudQueue queueRef = queue ?? queueOperationsClient.GetQueueReference(QueueName); if (await queueRef.DeleteIfExistsAsync()) { logger.Info((int)AzureQueueErrorCode.AzureQueue_03, "Deleted Azure Queue {0}", QueueName); } } catch (Exception exc) { ReportErrorAndRethrow(exc, "DeleteQueue", AzureQueueErrorCode.AzureQueue_04); } finally { CheckAlertSlowAccess(startTime, "DeleteQueue"); } } /// <summary> /// Clears the queue. /// </summary> public async Task ClearQueue() { var startTime = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Clearing a queue: {0}", QueueName); try { // that way we don't have first to create the queue to be able later to delete it. CloudQueue queueRef = queue ?? queueOperationsClient.GetQueueReference(QueueName); await queueRef.ClearAsync(); logger.Info((int)AzureQueueErrorCode.AzureQueue_05, "Cleared Azure Queue {0}", QueueName); } catch (Exception exc) { ReportErrorAndRethrow(exc, "ClearQueue", AzureQueueErrorCode.AzureQueue_06); } finally { CheckAlertSlowAccess(startTime, "ClearQueue"); } } /// <summary> /// Adds a new message to the queue. /// </summary> /// <param name="message">Message to be added to the queue.</param> public async Task AddQueueMessage(CloudQueueMessage message) { var startTime = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Adding message {0} to queue: {1}", message, QueueName); try { await queue.AddMessageAsync(message); } catch (Exception exc) { ReportErrorAndRethrow(exc, "AddQueueMessage", AzureQueueErrorCode.AzureQueue_07); } finally { CheckAlertSlowAccess(startTime, "AddQueueMessage"); } } /// <summary> /// Peeks in the queue for latest message, without dequeueing it. /// </summary> public async Task<CloudQueueMessage> PeekQueueMessage() { var startTime = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Peeking a message from queue: {0}", QueueName); try { return await queue.PeekMessageAsync(); } catch (Exception exc) { ReportErrorAndRethrow(exc, "PeekQueueMessage", AzureQueueErrorCode.AzureQueue_08); return null; // Dummy statement to keep compiler happy } finally { CheckAlertSlowAccess(startTime, "PeekQueueMessage"); } } /// <summary> /// Gets a new message from the queue. /// </summary> public async Task<CloudQueueMessage> GetQueueMessage() { var startTime = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Getting a message from queue: {0}", QueueName); try { //BeginGetMessage and EndGetMessage is not supported in netstandard, may be use GetMessageAsync // http://msdn.microsoft.com/en-us/library/ee758456.aspx // If no messages are visible in the queue, GetMessage returns null. return await queue.GetMessageAsync(messageVisibilityTimeout, options: null, operationContext: null); } catch (Exception exc) { ReportErrorAndRethrow(exc, "GetQueueMessage", AzureQueueErrorCode.AzureQueue_09); return null; // Dummy statement to keep compiler happy } finally { CheckAlertSlowAccess(startTime, "GetQueueMessage"); } } /// <summary> /// Gets a number of new messages from the queue. /// </summary> /// <param name="count">Number of messages to get from the queue.</param> public async Task<IEnumerable<CloudQueueMessage>> GetQueueMessages(int count = -1) { var startTime = DateTime.UtcNow; if (count == -1) { count = CloudQueueMessage.MaxNumberOfMessagesToPeek; } if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Getting up to {0} messages from queue: {1}", count, QueueName); try { return await queue.GetMessagesAsync(count, messageVisibilityTimeout, options: null, operationContext: null); } catch (Exception exc) { ReportErrorAndRethrow(exc, "GetQueueMessages", AzureQueueErrorCode.AzureQueue_10); return null; // Dummy statement to keep compiler happy } finally { CheckAlertSlowAccess(startTime, "GetQueueMessages"); } } /// <summary> /// Deletes a messages from the queue. /// </summary> /// <param name="message">A message to be deleted from the queue.</param> public async Task DeleteQueueMessage(CloudQueueMessage message) { var startTime = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Deleting a message from queue: {0}", QueueName); try { await queue.DeleteMessageAsync(message.Id, message.PopReceipt); } catch (Exception exc) { ReportErrorAndRethrow(exc, "DeleteMessage", AzureQueueErrorCode.AzureQueue_11); } finally { CheckAlertSlowAccess(startTime, "DeleteQueueMessage"); } } internal async Task GetAndDeleteQueueMessage() { CloudQueueMessage message = await GetQueueMessage(); await DeleteQueueMessage(message); } /// <summary> /// Returns an approximate number of messages in the queue. /// </summary> public async Task<int> GetApproximateMessageCount() { var startTime = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("GetApproximateMessageCount a message from queue: {0}", QueueName); try { await queue.FetchAttributesAsync(); return queue.ApproximateMessageCount.HasValue ? queue.ApproximateMessageCount.Value : 0; } catch (Exception exc) { ReportErrorAndRethrow(exc, "FetchAttributes", AzureQueueErrorCode.AzureQueue_12); return 0; // Dummy statement to keep compiler happy } finally { CheckAlertSlowAccess(startTime, "GetApproximateMessageCount"); } } private void CheckAlertSlowAccess(DateTime startOperation, string operation) { var timeSpan = DateTime.UtcNow - startOperation; if (timeSpan > AzureQueueDefaultPolicies.QueueOperationTimeout) { logger.Warn((int)AzureQueueErrorCode.AzureQueue_13, "Slow access to Azure queue {0} for {1}, which took {2}.", QueueName, operation, timeSpan); } } private void ReportErrorAndRethrow(Exception exc, string operation, AzureQueueErrorCode errorCode) { var errMsg = String.Format( "Error doing {0} for Azure storage queue {1} " + Environment.NewLine + "Exception = {2}", operation, QueueName, exc); logger.Error((int)errorCode, errMsg, exc); throw new AggregateException(errMsg, exc); } private CloudQueueClient GetCloudQueueClient( string storageConnectionString, IRetryPolicy retryPolicy, TimeSpan timeout, ILogger logger) { try { var storageAccount = AzureStorageUtils.GetCloudStorageAccount(storageConnectionString); CloudQueueClient operationsClient = storageAccount.CreateCloudQueueClient(); operationsClient.DefaultRequestOptions.RetryPolicy = retryPolicy; operationsClient.DefaultRequestOptions.ServerTimeout = timeout; return operationsClient; } catch (Exception exc) { logger.Error((int)AzureQueueErrorCode.AzureQueue_14, String.Format("Error creating GetCloudQueueOperationsClient."), exc); throw; } } private string SanitizeQueueName(string queueName) { var tmp = queueName; //Azure queue naming rules : https://docs.microsoft.com/en-us/rest/api/storageservices/Naming-Queues-and-Metadata?redirectedfrom=MSDN tmp = tmp.ToLowerInvariant(); tmp = tmp .Replace('/', '-') // Forward slash .Replace('\\', '-') // Backslash .Replace('#', '-') // Pound sign .Replace('?', '-') // Question mark .Replace('&', '-') .Replace('+', '-') .Replace(':', '-') .Replace('%', '-'); return tmp; } private void ValidateQueueName(string queueName) { // Naming Queues and Metadata: http://msdn.microsoft.com/en-us/library/windowsazure/dd179349.aspx if (!(queueName.Length >= 3 && queueName.Length <= 63)) { // A queue name must be from 3 through 63 characters long. throw new ArgumentException(String.Format("A queue name must be from 3 through 63 characters long, while your queueName length is {0}, queueName is {1}.", queueName.Length, queueName), queueName); } if (!Char.IsLetterOrDigit(queueName.First())) { // A queue name must start with a letter or number throw new ArgumentException(String.Format("A queue name must start with a letter or number, while your queueName is {0}.", queueName), queueName); } if (!Char.IsLetterOrDigit(queueName.Last())) { // The first and last letters in the queue name must be alphanumeric. The dash (-) character cannot be the first or last character. throw new ArgumentException(String.Format("The last letter in the queue name must be alphanumeric, while your queueName is {0}.", queueName), queueName); } if (!queueName.All(c => Char.IsLetterOrDigit(c) || c.Equals('-'))) { // A queue name can only contain letters, numbers, and the dash (-) character. throw new ArgumentException(String.Format("A queue name can only contain letters, numbers, and the dash (-) character, while your queueName is {0}.", queueName), queueName); } if (queueName.Contains("--")) { // Consecutive dash characters are not permitted in the queue name. throw new ArgumentException(String.Format("Consecutive dash characters are not permitted in the queue name, while your queueName is {0}.", queueName), queueName); } if (queueName.Where(Char.IsLetter).Any(c => !Char.IsLower(c))) { // All letters in a queue name must be lowercase. throw new ArgumentException(String.Format("All letters in a queue name must be lowercase, while your queueName is {0}.", queueName), queueName); } } } }
using System; using System.Collections.Generic; namespace Wc3o { public class BuildingInfo : EntityInfo { #region " Get " static SortedDictionary<BuildingType, BuildingInfo> infos; public static BuildingInfo Get(BuildingType t) { if (infos == null) infos = new SortedDictionary<BuildingType, BuildingInfo>(); if (!infos.ContainsKey(t)) Create(t); return infos[t]; } #endregion #region " Create " static void Create(BuildingType t) { BuildingInfo i = new BuildingInfo(); i.type = t; i.bonusAuraArmor = 1; i.malusAuraArmor = 1; i.bonusAuraRange = 1; i.malusAuraRange = 1; i.bonusAuraHitpoints = 1; i.malusAuraHitpoints = 1; i.bonusAuraAttackGround = 1; i.malusAuraAttackGround = 1; i.bonusAuraAttackAir = 1; i.malusAuraAttackAir = 1; i.bonusAuraCooldown = 1; i.malusAuraCooldown = 1; i.buildable = true; switch (t) { case BuildingType.GreatHall: i.fraction = Fraction.Orcs; i.name = "Great Hall"; i.image = "/Orcs/GreatHall.gif"; i.createImage = "/Orcs/GreatHall.gif"; i.gold = 385; i.lumber = 185; i.hitpoints = 1500; i.minutes = 450; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[1]; i.upgradesTo[0] = BuildingType.Stronghold; i.requirements = new BuildingType[0]; i.score = 3; i.number = 3; i.numberPerSector = 1; i.food = 10; break; case BuildingType.Stronghold: i.fraction = Fraction.Orcs; i.name = "Stronghold"; i.image = "/Orcs/Stronghold.gif"; i.createImage = "/Orcs/Stronghold.gif"; i.gold = 315; i.lumber = 190; i.hitpoints = 1600; i.minutes = 610; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[1]; i.upgradesTo[0] = BuildingType.Fortress; i.requirements = new BuildingType[0]; i.score = 7; i.number = 2; i.numberPerSector = 1; i.food = 10; i.buildable = false; break; case BuildingType.Fortress: i.fraction = Fraction.Orcs; i.name = "Fortress"; i.image = "/Orcs/Fortress.gif"; i.createImage = "/Orcs/Fortress.gif"; i.gold = 325; i.lumber = 190; i.hitpoints = 1800; i.minutes = 610; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.AltarOfStorms; i.score = 10; i.number = 1; i.numberPerSector = 1; i.food = 10; i.buildable = false; break; case BuildingType.OrcBarracks: i.fraction = Fraction.Orcs; i.name = "Barracks"; i.image = "/Orcs/Barracks.gif"; i.createImage = "/Orcs/Barracks.gif"; i.gold = 180; i.lumber = 50; i.hitpoints = 1200; i.minutes = 180; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 4; i.number = 2; i.numberPerSector = 1; break; case BuildingType.AltarOfStorms: i.fraction = Fraction.Orcs; i.name = "Altar Of Storms"; i.image = "/Orcs/AltarOfStorms.gif"; i.createImage = "/Orcs/AltarOfStorms.gif"; i.gold = 180; i.lumber = 50; i.hitpoints = 900; i.minutes = 270; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 5; i.number = 2; i.numberPerSector = 1; break; case BuildingType.WarMill: i.fraction = Fraction.Orcs; i.name = "War Mill"; i.image = "/Orcs/WarMill.gif"; i.createImage = "/Orcs/WarMill.gif"; i.gold = 205; i.lumber = 0; i.hitpoints = 1000; i.minutes = 315; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 4; i.number = 2; i.numberPerSector = 1; break; case BuildingType.Beastiary: i.fraction = Fraction.Orcs; i.name = "Beastiary"; i.image = "/Orcs/Beastiary.gif"; i.createImage = "/Orcs/Beastiary.gif"; i.gold = 145; i.lumber = 140; i.hitpoints = 1100; i.minutes = 270; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.Stronghold; i.score = 6; i.number = 2; i.numberPerSector = 1; break; case BuildingType.SpiritLodge: i.fraction = Fraction.Orcs; i.name = "Spirit Lodge"; i.image = "/Orcs/SpiritLodge.gif"; i.createImage = "/Orcs/SpiritLodge.gif"; i.gold = 150; i.lumber = 150; i.hitpoints = 800; i.minutes = 315; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.Stronghold; i.score = 6; i.number = 2; i.numberPerSector = 1; break; case BuildingType.TaurenTotem: i.fraction = Fraction.Orcs; i.name = "Tauren Totem"; i.image = "/Orcs/TaurenTotem.gif"; i.createImage = "/Orcs/TaurenTotem.gif"; i.gold = 135; i.lumber = 155; i.hitpoints = 1200; i.minutes = 315; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[2]; i.requirements[0] = BuildingType.Fortress; i.requirements[1] = BuildingType.WarMill; i.score = 10; i.number = 1; i.numberPerSector = 1; break; case BuildingType.VoodooLounge: i.fraction = Fraction.Orcs; i.name = "Voodoo Lounge"; i.image = "/Orcs/VoodooLounge.gif"; i.createImage = "/Orcs/VoodooLounge.gif"; i.gold = 130; i.lumber = 30; i.hitpoints = 500; i.minutes = 270; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 4; i.number = 2; i.numberPerSector = 1; break; case BuildingType.HauntedGoldMine: i.fraction = Fraction.Undead; i.name = "Haunted Gold Mine"; i.image = "/Undead/HauntedGoldMine.gif"; i.createImage = "/Undead/HauntedGoldMine.gif"; i.gold = 255; i.lumber = 220; i.hitpoints = 800; i.minutes = 300; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 2; i.number = 6; i.numberPerSector = 1; break; case BuildingType.Necropolis: i.fraction = Fraction.Undead; i.name = "Necropolis"; i.image = "/Undead/Necropolis.gif"; i.createImage = "/Undead/Necropolis.gif"; i.gold = 255; i.lumber = 0; i.hitpoints = 1500; i.minutes = 360; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[1]; i.upgradesTo[0] = BuildingType.HallsOfTheDead; i.requirements = new BuildingType[0]; i.score = 3; i.number = 3; i.numberPerSector = 1; i.food = 10; break; case BuildingType.Crypt: i.fraction = Fraction.Undead; i.name = "Crypt"; i.image = "/Undead/Crypt.gif"; i.createImage = "/Undead/Crypt.gif"; i.gold = 200; i.lumber = 50; i.hitpoints = 1300; i.minutes = 180; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 4; i.number = 2; i.numberPerSector = 1; break; case BuildingType.Ziggurat: i.fraction = Fraction.Undead; i.name = "Ziggurat"; i.image = "/Undead/Ziggurat.gif"; i.createImage = "/Undead/Ziggurat.gif"; i.gold = 150; i.lumber = 50; i.hitpoints = 550; i.minutes = 150; i.armor = 1; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[2]; i.upgradesTo[0] = BuildingType.NerubianTower; i.upgradesTo[1] = BuildingType.SpiritTower; i.requirements = new BuildingType[0]; i.score = 2; i.number = 20; i.numberPerSector = 20; i.food = 10; break; case BuildingType.AltarOfDarkness: i.fraction = Fraction.Undead; i.name = "Altar Of Darkness"; i.image = "/Undead/AltarOfDarkness.gif"; i.createImage = "/Undead/AltarOfDarkness.gif"; i.gold = 180; i.lumber = 50; i.hitpoints = 900; i.minutes = 270; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 5; i.number = 2; i.numberPerSector = 1; break; case BuildingType.Graveyard: i.fraction = Fraction.Undead; i.name = "Graveyard"; i.image = "/Undead/Graveyard.gif"; i.createImage = "/Undead/Graveyard.gif"; i.gold = 215; i.lumber = 0; i.hitpoints = 900; i.minutes = 360; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 5; i.number = 2; i.numberPerSector = 1; break; case BuildingType.Slaughterhouse: i.fraction = Fraction.Undead; i.name = "Slaughterhouse"; i.image = "/Undead/Slaughterhouse.gif"; i.createImage = "/Undead/Slaughterhouse.gif"; i.gold = 140; i.lumber = 135; i.hitpoints = 1200; i.minutes = 270; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[2]; i.requirements[0] = BuildingType.Graveyard; i.requirements[1] = BuildingType.HallsOfTheDead; i.score = 6; i.number = 2; i.numberPerSector = 1; break; case BuildingType.TempleOfTheDamned: i.fraction = Fraction.Undead; i.name = "Temple Of The Damned"; i.image = "/Undead/TempleOfTheDamned.gif"; i.createImage = "/Undead/TempleOfTheDamned.gif"; i.gold = 155; i.lumber = 140; i.hitpoints = 1100; i.minutes = 270; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[2]; i.requirements[0] = BuildingType.Graveyard; i.requirements[1] = BuildingType.HallsOfTheDead; i.score = 6; i.number = 2; i.numberPerSector = 1; break; case BuildingType.SacrificialPit: i.fraction = Fraction.Undead; i.name = "Sacrificial Pit"; i.image = "/Undead/SacrificialPit.gif"; i.createImage = "/Undead/SacrificialPit.gif"; i.gold = 75; i.lumber = 150; i.hitpoints = 900; i.minutes = 205; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.HallsOfTheDead; i.score = 3; i.number = 2; i.numberPerSector = 1; break; case BuildingType.Boneyard: i.fraction = Fraction.Undead; i.name = "Boneyard"; i.image = "/Undead/Boneyard.gif"; i.createImage = "/Undead/Boneyard.gif"; i.gold = 175; i.lumber = 200; i.hitpoints = 1500; i.minutes = 315; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[2]; i.requirements[0] = BuildingType.SacrificialPit; i.requirements[1] = BuildingType.BlackCitadel; i.score = 10; i.number = 1; i.numberPerSector = 1; break; case BuildingType.TombOfRelics: i.fraction = Fraction.Undead; i.name = "Tomb Of Relics"; i.image = "/Undead/TombOfRelics.gif"; i.createImage = "/Undead/TombOfRelics.gif"; i.gold = 130; i.lumber = 30; i.hitpoints = 475; i.minutes = 270; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 4; i.number = 2; i.numberPerSector = 1; break; case BuildingType.TownHall: i.fraction = Fraction.Humans; i.name = "Town Hall"; i.image = "/Humans/TownHall.jpg"; i.createImage = "/Humans/TownHall.jpg"; i.gold = 385; i.lumber = 205; i.hitpoints = 1500; i.minutes = 540; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[1]; i.upgradesTo[0] = BuildingType.Keep; i.requirements = new BuildingType[0]; i.score = 3; i.number = 3; i.numberPerSector = 1; i.food = 10; break; case BuildingType.Keep: i.fraction = Fraction.Humans; i.name = "Keep"; i.image = "/Humans/Keep.jpg"; i.createImage = "/Humans/Keep.jpg"; i.gold = 320; i.lumber = 210; i.hitpoints = 2000; i.minutes = 630; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[1]; i.upgradesTo[0] = BuildingType.Castle; i.requirements = new BuildingType[0]; i.score = 7; i.number = 2; i.numberPerSector = 1; i.food = 10; i.buildable = false; break; case BuildingType.Castle: i.fraction = Fraction.Humans; i.name = "Castle"; i.image = "/Humans/Castle.jpg"; i.createImage = "/Humans/Castle.jpg"; i.gold = 360; i.lumber = 210; i.hitpoints = 2500; i.minutes = 630; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.AltarOfKings; i.score = 10; i.number = 2; i.numberPerSector = 1; i.food = 10; i.buildable = false; break; case BuildingType.HumanBarracks: i.fraction = Fraction.Humans; i.name = "Barracks"; i.image = "/Humans/Barracks.jpg"; i.createImage = "/Humans/Barracks.jpg"; i.gold = 160; i.lumber = 60; i.hitpoints = 1500; i.minutes = 180; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 4; i.number = 2; i.numberPerSector = 1; break; case BuildingType.Farm: i.fraction = Fraction.Humans; i.name = "Farm"; i.image = "/Humans/Farm.jpg"; i.createImage = "/Humans/Farm.jpg"; i.gold = 80; i.lumber = 20; i.hitpoints = 500; i.minutes = 105; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 1; i.number = 40; i.numberPerSector = 40; i.food = 6; break; case BuildingType.AltarOfKings: i.fraction = Fraction.Humans; i.name = "Altar Of Kings"; i.image = "/Humans/AltarOfKings.jpg"; i.createImage = "/Humans/AltarOfKings.jpg"; i.gold = 180; i.lumber = 50; i.hitpoints = 900; i.minutes = 270; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 4; i.number = 2; i.numberPerSector = 1; break; case BuildingType.LumberMill: i.fraction = Fraction.Humans; i.name = "Lumber Mill"; i.image = "/Humans/LumberMill.jpg"; i.createImage = "/Humans/LumberMill.jpg"; i.gold = 120; i.lumber = 0; i.hitpoints = 900; i.minutes = 270; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 5; i.number = 2; i.numberPerSector = 1; break; case BuildingType.ScoutTower: i.fraction = Fraction.Humans; i.name = "Scout Tower"; i.image = "/Humans/ScoutTower.jpg"; i.createImage = "/Humans/ScoutTower.jpg"; i.gold = 30; i.lumber = 20; i.hitpoints = 300; i.minutes = 105; i.armor = 0; i.armorType = ArmorType.Light; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[3]; i.upgradesTo[0] = BuildingType.GuardTower; i.upgradesTo[1] = BuildingType.CannonTower; i.upgradesTo[2] = BuildingType.ArcaneTower; i.requirements = new BuildingType[0]; i.score = 1; i.number = 5; i.numberPerSector = 5; break; case BuildingType.Blacksmith: i.fraction = Fraction.Humans; i.name = "Blacksmith"; i.image = "/Humans/Blacksmith.jpg"; i.createImage = "/Humans/Blacksmith.jpg"; i.gold = 140; i.lumber = 60; i.hitpoints = 1200; i.minutes = 315; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.TownHall; i.score = 5; i.number = 2; i.numberPerSector = 1; break; case BuildingType.Workshop: i.fraction = Fraction.Humans; i.name = "Workshop"; i.image = "/Humans/Workshop.jpg"; i.createImage = "/Humans/Workshop.jpg"; i.gold = 140; i.lumber = 140; i.hitpoints = 1200; i.minutes = 270; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[2]; i.requirements[0] = BuildingType.Keep; i.requirements[1] = BuildingType.Blacksmith; i.score = 6; i.number = 2; i.numberPerSector = 1; break; case BuildingType.ArcaneSanctum: i.fraction = Fraction.Humans; i.name = "Arcane Sanctum"; i.image = "/Humans/ArcaneSanctum.jpg"; i.createImage = "/Humans/ArcaneSanctum.jpg"; i.gold = 150; i.lumber = 140; i.hitpoints = 1050; i.minutes = 315; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.Keep; i.score = 6; i.number = 2; i.numberPerSector = 1; break; case BuildingType.GryphonAviary: i.fraction = Fraction.Humans; i.name = "Gryphon Aviary"; i.image = "/Humans/GryphonAviary.jpg"; i.createImage = "/Humans/GryphonAviary.jpg"; i.gold = 140; i.lumber = 150; i.hitpoints = 1200; i.minutes = 335; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.requirements = new BuildingType[2]; i.requirements[0] = BuildingType.LumberMill; i.requirements[1] = BuildingType.Castle; i.score = 10; i.number = 1; i.numberPerSector = 1; break; case BuildingType.ArcaneVault: i.fraction = Fraction.Humans; i.name = "Arcane Vault"; i.image = "/Humans/ArcaneVault.jpg"; i.createImage = "/Humans/ArcaneVault.jpg"; i.gold = 130; i.lumber = 30; i.hitpoints = 485; i.minutes = 270; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 4; i.number = 2; i.numberPerSector = 1; break; case BuildingType.Burrow: i.fraction = Fraction.Orcs; i.name = "Burrow"; i.image = "/Orcs/Burrow.gif"; i.createImage = "/Orcs/Burrow.gif"; i.gold = 160; i.lumber = 40; i.hitpoints = 600; i.minutes = 150; i.armor = 5; i.armorType = ArmorType.Heavy; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 25; i.attackGround = 25; i.cooldown = 2; i.range = 70; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 2; i.number = 20; i.numberPerSector = 10; i.food = 10; break; case BuildingType.WatchTower: i.fraction = Fraction.Orcs; i.name = "Watch Tower"; i.image = "/Orcs/WatchTower.gif"; i.createImage = "/Orcs/WatchTower.gif"; i.gold = 110; i.lumber = 80; i.hitpoints = 500; i.minutes = 250; i.armor = 3; i.armorType = ArmorType.Heavy; i.attackTypeAir = AttackType.Pierce; i.attackTypeGround = AttackType.Pierce; i.attackAir = 17; i.attackGround = 17; i.cooldown = 0.6; i.range = 80; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.WarMill; i.score = 3; i.number = 7; i.numberPerSector = 3; break; case BuildingType.GuardTower: i.fraction = Fraction.Humans; i.name = "Guard Tower"; i.image = "/Humans/GuardTower.jpg"; i.createImage = "/Humans/GuardTower.jpg"; i.gold = 70; i.lumber = 50; i.hitpoints = 500; i.minutes = 225; i.armor = 5; i.armorType = ArmorType.Heavy; i.attackTypeAir = AttackType.Pierce; i.attackTypeGround = AttackType.Pierce; i.attackAir = 25; i.attackGround = 25; i.cooldown = 0.9; i.range = 70; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.LumberMill; i.score = 3; i.number = 3; i.numberPerSector = 2; i.buildable = false; break; case BuildingType.CannonTower: i.fraction = Fraction.Humans; i.name = "Cannon Tower"; i.image = "/Humans/CannonTower.jpg"; i.createImage = "/Humans/CannonTower.jpg"; i.gold = 170; i.lumber = 100; i.hitpoints = 600; i.minutes = 335; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.Siege; i.attackAir = 0; i.attackGround = 100; i.cooldown = 2.5; i.range = 80; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.Workshop; i.score = 6; i.number = 3; i.numberPerSector = 2; i.buildable = false; break; case BuildingType.ArcaneTower: i.fraction = Fraction.Humans; i.name = "Arcane Tower"; i.image = "/Humans/ArcaneTower.jpg"; i.createImage = "/Humans/ArcaneTower.jpg"; i.gold = 70; i.lumber = 50; i.hitpoints = 500; i.minutes = 225; i.armor = 5; i.armorType = ArmorType.Heavy; i.attackTypeAir = AttackType.Pierce; i.attackTypeGround = AttackType.Pierce; i.attackAir = 9; i.attackGround = 9; i.cooldown = 1; i.range = 80; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 2; i.number = 3; i.numberPerSector = 2; i.bonusAuraRange = 1.1; i.bonusAuraAttackGround = 1.1; i.malusAuraArmor = 1.1; i.buildable = false; break; case BuildingType.NerubianTower: i.fraction = Fraction.Undead; i.name = "Nerubian Tower"; i.image = "/Undead/NerubianTower.gif"; i.createImage = "/Undead/NerubianTower.gif"; i.gold = 100; i.lumber = 20; i.hitpoints = 550; i.minutes = 135; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.Normal; i.attackTypeGround = AttackType.Normal; i.attackAir = 9; i.attackGround = 9; i.cooldown = 1; i.range = 70; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 4; i.number = 4; i.numberPerSector = 3; i.bonusAuraAttackGround = 1.1; i.bonusAuraAttackAir = 1.1; i.food = 10; i.buildable = false; break; case BuildingType.SpiritTower: i.fraction = Fraction.Undead; i.name = "Spirit Tower"; i.image = "/Undead/SpiritTower.gif"; i.createImage = "/Undead/SpiritTower.gif"; i.gold = 145; i.lumber = 40; i.hitpoints = 550; i.minutes = 160; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.Pierce; i.attackTypeGround = AttackType.Pierce; i.attackAir = 29; i.attackGround = 29; i.cooldown = 1; i.range = 70; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.Graveyard; i.score = 2; i.number = 4; i.numberPerSector = 3; i.food = 10; i.buildable = false; break; case BuildingType.HallsOfTheDead: i.fraction = Fraction.Undead; i.name = "Halls Of The Dead"; i.image = "/Undead/HallsOfTheDead.gif"; i.createImage = "/Undead/HallsOfTheDead.gif"; i.gold = 320; i.lumber = 210; i.hitpoints = 1750; i.minutes = 630; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.Pierce; i.attackTypeGround = AttackType.Pierce; i.attackAir = 11; i.attackGround = 11; i.cooldown = 1; i.range = 80; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[1]; i.upgradesTo[0] = BuildingType.BlackCitadel; i.requirements = new BuildingType[0]; i.score = 7; i.number = 2; i.numberPerSector = 1; i.food = 10; i.buildable = false; break; case BuildingType.BlackCitadel: i.fraction = Fraction.Undead; i.name = "Black Citadel"; i.image = "/Undead/BlackCitadel.gif"; i.createImage = "/Undead/BlackCitadel.gif"; i.gold = 325; i.lumber = 230; i.hitpoints = 2000; i.minutes = 630; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.Pierce; i.attackTypeGround = AttackType.Pierce; i.attackAir = 14; i.attackGround = 14; i.cooldown = 1; i.range = 80; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.AltarOfDarkness; i.score = 10; i.number = 1; i.numberPerSector = 1; i.food = 10; i.buildable = false; break; case BuildingType.TreeOfLife: i.fraction = Fraction.NightElves; i.name = "Tree Of Life"; i.image = "/NightElves/TreeOfLife.gif"; i.createImage = "/NightElves/TreeOfLife.gif"; i.gold = 340; i.lumber = 185; i.hitpoints = 1300; i.minutes = 330; i.armor = 2; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.Normal; i.attackAir = 0; i.attackGround = 45; i.cooldown = 2.5; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[1]; i.upgradesTo[0] = BuildingType.TreeOfAges; i.requirements = new BuildingType[0]; i.score = 3; i.number = 3; i.numberPerSector = 1; i.food = 10; break; case BuildingType.TreeOfAges: i.fraction = Fraction.NightElves; i.name = "Tree Of Ages"; i.image = "/NightElves/TreeOfAges.gif"; i.createImage = "/NightElves/TreeOfAges.gif"; i.gold = 320; i.lumber = 180; i.hitpoints = 1700; i.minutes = 630; i.armor = 2; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.Normal; i.attackAir = 0; i.attackGround = 54; i.cooldown = 2.5; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[1]; i.upgradesTo[0] = BuildingType.TreeOfEternity; i.requirements = new BuildingType[0]; i.score = 7; i.number = 2; i.numberPerSector = 1; i.food = 10; i.buildable = false; break; case BuildingType.TreeOfEternity: i.fraction = Fraction.NightElves; i.name = "Tree Of Eternity"; i.image = "/NightElves/TreeOfEternity.gif"; i.createImage = "/NightElves/TreeOfEternity.gif"; i.gold = 330; i.lumber = 200; i.hitpoints = 2000; i.minutes = 630; i.armor = 2; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.Normal; i.attackAir = 0; i.attackGround = 67; i.cooldown = 2.5; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.AltarOfElders; i.score = 10; i.number = 1; i.numberPerSector = 1; i.food = 10; i.buildable = false; break; case BuildingType.AncientOfWar: i.fraction = Fraction.NightElves; i.name = "Ancient Of War"; i.image = "/NightElves/AncientOfWar.gif"; i.createImage = "/NightElves/AncientOfWar.gif"; i.gold = 150; i.lumber = 60; i.hitpoints = 1000; i.minutes = 270; i.armor = 2; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.Normal; i.attackAir = 0; i.attackGround = 50; i.cooldown = 2.5; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 4; i.number = 2; i.numberPerSector = 1; break; case BuildingType.AncientOfLore: i.fraction = Fraction.NightElves; i.name = "Ancient Of Lore"; i.image = "/NightElves/AncientOfLore.gif"; i.createImage = "/NightElves/AncientOfLore.gif"; i.gold = 155; i.lumber = 145; i.hitpoints = 900; i.minutes = 315; i.armor = 2; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.Normal; i.attackAir = 0; i.attackGround = 45; i.cooldown = 2.5; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[2]; i.requirements[0] = BuildingType.TreeOfAges; i.requirements[1] = BuildingType.HuntersHall; i.score = 6; i.number = 2; i.numberPerSector = 1; break; case BuildingType.AncientOfWind: i.fraction = Fraction.NightElves; i.name = "Ancient Of Wind"; i.image = "/NightElves/AncientOfWind.gif"; i.createImage = "/NightElves/AncientOfWind.gif"; i.gold = 150; i.lumber = 140; i.hitpoints = 900; i.minutes = 270; i.armor = 2; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.Normal; i.attackAir = 0; i.attackGround = 42; i.cooldown = 2.5; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.TreeOfAges; i.score = 6; i.number = 2; i.numberPerSector = 1; break; case BuildingType.AncientProtector: i.fraction = Fraction.NightElves; i.name = "Ancient Protector"; i.image = "/NightElves/AncientProtector.gif"; i.createImage = "/NightElves/AncientProtector.gif"; i.gold = 135; i.lumber = 80; i.hitpoints = 600; i.minutes = 270; i.armor = 1; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.Pierce; i.attackTypeGround = AttackType.Pierce; i.attackAir = 49; i.attackGround = 49; i.cooldown = 2; i.range = 70; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.HuntersHall; i.score = 5; i.number = 6; i.numberPerSector = 4; break; case BuildingType.AncientOfWonders: i.fraction = Fraction.NightElves; i.name = "Ancient Of Wonders"; i.image = "/NightElves/AncientOfWonders.gif"; i.createImage = "/NightElves/AncientOfWonders.gif"; i.gold = 90; i.lumber = 30; i.hitpoints = 450; i.minutes = 270; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.Normal; i.attackAir = 0; i.attackGround = 23; i.cooldown = 2.5; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 4; i.number = 2; i.numberPerSector = 1; break; case BuildingType.MoonWell: i.fraction = Fraction.NightElves; i.name = "Moon Well"; i.image = "/NightElves/MoonWell.gif"; i.createImage = "/NightElves/MoonWell.gif"; i.gold = 180; i.lumber = 40; i.hitpoints = 600; i.minutes = 150; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 2; i.number = 20; i.numberPerSector = 20; i.food = 10; break; case BuildingType.AltarOfElders: i.fraction = Fraction.NightElves; i.name = "Altar Of Elders"; i.image = "/NightElves/AltarOfElders.gif"; i.createImage = "/NightElves/AltarOfElders.gif"; i.gold = 180; i.lumber = 50; i.hitpoints = 900; i.minutes = 270; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[0]; i.score = 5; i.number = 2; i.numberPerSector = 1; break; case BuildingType.HuntersHall: i.fraction = Fraction.NightElves; i.name = "Hunters Hall"; i.image = "/NightElves/HuntersHall.gif"; i.createImage = "/NightElves/HuntersHall.gif"; i.gold = 210; i.lumber = 100; i.hitpoints = 1100; i.minutes = 270; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[1]; i.requirements[0] = BuildingType.TreeOfLife; i.score = 4; i.number = 2; i.numberPerSector = 1; break; case BuildingType.ChimaeraRoost: i.fraction = Fraction.NightElves; i.name = "Chimaera Roost"; i.image = "/NightElves/ChimaeraRoost.gif"; i.createImage = "/NightElves/ChimaeraRoost.gif"; i.gold = 140; i.lumber = 190; i.hitpoints = 1200; i.minutes = 360; i.armor = 5; i.armorType = ArmorType.Fort; i.attackTypeAir = AttackType.None; i.attackTypeGround = AttackType.None; i.attackAir = 0; i.attackGround = 0; i.cooldown = 0; i.range = 0; i.visibility = Visibility.Always; i.upgradesTo = new BuildingType[0]; i.requirements = new BuildingType[2]; i.requirements[0] = BuildingType.AncientOfWind; i.requirements[1] = BuildingType.TreeOfEternity; i.score = 10; i.number = 1; i.numberPerSector = 1; break; } infos[t] = i; } #endregion #region " Properties " BuildingType type; public BuildingType Type { get { return type; } } int number; public int Number { get { return number; } } int numberPerSector; public int NumberPerSector { get { return numberPerSector; } } BuildingType[] upgradesTo; public BuildingType[] UpgradesTo { get { return upgradesTo; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using XmlCoreTest.Common; namespace System.Xml.Tests { //////////////////////////////////////////////////////////////// // TestFiles // //////////////////////////////////////////////////////////////// public class NameTable_TestFiles { //Data private static string s_allNodeTypeDTD = "AllNodeTypes.dtd"; private static string s_allNodeTypeENT = "AllNodeTypes.ent"; private static string s_genericXml = "Generic.xml"; private static string s_bigFileXml = "Big.xml"; public static void RemoveDataReader(EREADER_TYPE eReaderType) { switch (eReaderType) { case EREADER_TYPE.GENERIC: DeleteTestFile(s_allNodeTypeDTD); DeleteTestFile(s_allNodeTypeENT); DeleteTestFile(s_genericXml); break; case EREADER_TYPE.BIG_ELEMENT_SIZE: DeleteTestFile(s_bigFileXml); break; default: throw new Exception(); } } private static Dictionary<EREADER_TYPE, string> s_fileNameMap = null; public static string GetTestFileName(EREADER_TYPE eReaderType) { if (s_fileNameMap == null) InitFileNameMap(); return s_fileNameMap[eReaderType]; } private static void InitFileNameMap() { if (s_fileNameMap == null) { s_fileNameMap = new Dictionary<EREADER_TYPE, string>(); } s_fileNameMap.Add(EREADER_TYPE.GENERIC, s_genericXml); s_fileNameMap.Add(EREADER_TYPE.BIG_ELEMENT_SIZE, s_bigFileXml); } public static void CreateTestFile(ref string strFileName, EREADER_TYPE eReaderType) { strFileName = GetTestFileName(eReaderType); switch (eReaderType) { case EREADER_TYPE.GENERIC: CreateGenericTestFile(strFileName); break; case EREADER_TYPE.BIG_ELEMENT_SIZE: CreateBigElementTestFile(strFileName); break; default: throw new Exception(); } } protected static void DeleteTestFile(string strFileName) { } public static void CreateGenericTestFile(string strFileName) { MemoryStream ms = new MemoryStream(); TextWriter tw = new StreamWriter(ms); tw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"); tw.WriteLine("<!-- comment1 -->"); tw.WriteLine("<?PI1_First processing instruction?>"); tw.WriteLine("<?PI1a?>"); tw.WriteLine("<?PI1b?>"); tw.WriteLine("<?PI1c?>"); tw.WriteLine("<!DOCTYPE root SYSTEM \"AllNodeTypes.dtd\" ["); tw.WriteLine("<!NOTATION gif SYSTEM \"foo.exe\">"); tw.WriteLine("<!ELEMENT root ANY>"); tw.WriteLine("<!ELEMENT elem1 ANY>"); tw.WriteLine("<!ELEMENT ISDEFAULT ANY>"); tw.WriteLine("<!ENTITY % e SYSTEM \"AllNodeTypes.ent\">"); tw.WriteLine("%e;"); tw.WriteLine("<!ENTITY e1 \"e1foo\">"); tw.WriteLine("<!ENTITY e2 \"&ext3; e2bar\">"); tw.WriteLine("<!ENTITY e3 \"&e1; e3bzee \">"); tw.WriteLine("<!ENTITY e4 \"&e3; e4gee\">"); tw.WriteLine("<!ATTLIST elem1 child1 CDATA #IMPLIED child2 CDATA \"&e2;\" child3 CDATA #REQUIRED>"); tw.WriteLine("<!ATTLIST root xmlns:something CDATA #FIXED \"something\" xmlns:my CDATA #FIXED \"my\" xmlns:dt CDATA #FIXED \"urn:uuid:C2F41010-65B3-11d1-A29F-00AA00C14882/\">"); tw.WriteLine("<!ATTLIST ISDEFAULT d1 CDATA #FIXED \"d1value\">"); tw.WriteLine("<!ATTLIST MULTISPACES att IDREFS #IMPLIED>"); tw.WriteLine("<!ELEMENT CATMIXED (#PCDATA)>"); tw.WriteLine("]>"); tw.WriteLine("<PLAY>"); tw.WriteLine("<root xmlns:something=\"something\" xmlns:my=\"my\" xmlns:dt=\"urn:uuid:C2F41010-65B3-11d1-A29F-00AA00C14882/\">"); tw.WriteLine("<elem1 child1=\"\" child2=\"e1foo e3bzee e2bar\" child3=\"something\">"); tw.WriteLine("text node two e1foo text node three"); tw.WriteLine("</elem1>"); tw.WriteLine("e1foo e3bzee e2bar"); tw.WriteLine("<![CDATA[ This section contains characters that should not be interpreted as markup. For example, characters ', \","); tw.WriteLine("<, >, and & are all fine here.]]>"); tw.WriteLine("<elem2 att1=\"id1\" att2=\"up\" att3=\"attribute3\"> "); tw.WriteLine("<a />"); tw.WriteLine("</elem2>"); tw.WriteLine("<elem2> "); tw.WriteLine("elem2-text1"); tw.WriteLine("<a refs=\"id2\"> "); tw.WriteLine("this-is-a "); tw.WriteLine("</a> "); tw.WriteLine("elem2-text2"); tw.WriteLine("e1foo e3bzee "); tw.WriteLine("e1foo e3bzee e4gee"); tw.WriteLine("<!-- elem2-comment1-->"); tw.WriteLine("elem2-text3"); tw.WriteLine("<b> "); tw.WriteLine("this-is-b"); tw.WriteLine("</b>"); tw.WriteLine("elem2-text4"); tw.WriteLine("<?elem2_PI elem2-PI?>"); tw.WriteLine("elem2-text5"); tw.WriteLine("</elem2>"); tw.WriteLine("<elem2 att1=\"id2\"></elem2>"); tw.WriteLine("</root>"); tw.Write("<ENTITY1 att1='xxx&lt;xxx&#65;xxx&#x43;xxxe1fooxxx'>xxx&gt;xxx&#66;xxx&#x44;xxxe1fooxxx</ENTITY1>"); tw.WriteLine("<ENTITY2 att1='xxx&lt;xxx&#65;xxx&#x43;xxxe1fooxxx'>xxx&gt;xxx&#66;xxx&#x44;xxxe1fooxxx</ENTITY2>"); tw.WriteLine("<ENTITY3 att1='xxx&lt;xxx&#65;xxx&#x43;xxxe1fooxxx'>xxx&gt;xxx&#66;xxx&#x44;xxxe1fooxxx</ENTITY3>"); tw.WriteLine("<ENTITY4 att1='xxx&lt;xxx&#65;xxx&#x43;xxxe1fooxxx'>xxx&gt;xxx&#66;xxx&#x44;xxxe1fooxxx</ENTITY4>"); tw.WriteLine("<ENTITY5>e1foo e3bzee </ENTITY5>"); tw.WriteLine("<ATTRIBUTE1 />"); tw.WriteLine("<ATTRIBUTE2 a1='a1value' />"); tw.WriteLine("<ATTRIBUTE3 a1='a1value' a2='a2value' a3='a3value' />"); tw.WriteLine("<ATTRIBUTE4 a1='' />"); tw.WriteLine("<ATTRIBUTE5 CRLF='x\r\nx' CR='x\rx' LF='x\nx' MS='x x' TAB='x\tx' />"); tw.WriteLine("<ENDOFLINE1>x\r\nx</ENDOFLINE1>"); tw.WriteLine("<ENDOFLINE2>x\rx</ENDOFLINE2>"); tw.WriteLine("<ENDOFLINE3>x\nx</ENDOFLINE3>"); tw.WriteLine("<WHITESPACE1>\r\n<ELEM />\r\n</WHITESPACE1>"); tw.WriteLine("<WHITESPACE2> <ELEM /> </WHITESPACE2>"); tw.WriteLine("<WHITESPACE3>\t<ELEM />\t</WHITESPACE3>"); tw.WriteLine("<SKIP1 /><AFTERSKIP1 />"); tw.WriteLine("<SKIP2></SKIP2><AFTERSKIP2 />"); tw.WriteLine("<SKIP3><ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 /></SKIP3><AFTERSKIP3></AFTERSKIP3>"); tw.WriteLine("<SKIP4><ELEM1 /><ELEM2>xxx<ELEM3 /></ELEM2></SKIP4>"); tw.WriteLine("<CHARS1>0123456789</CHARS1>"); tw.WriteLine("<CHARS2>xxx<MARKUP />yyy</CHARS2>"); tw.WriteLine("<CHARS_ELEM1>xxx<MARKUP />yyy</CHARS_ELEM1>"); tw.WriteLine("<CHARS_ELEM2><MARKUP />yyy</CHARS_ELEM2>"); tw.WriteLine("<CHARS_ELEM3>xxx<MARKUP /></CHARS_ELEM3>"); tw.WriteLine("<CHARS_CDATA1>xxx<![CDATA[yyy]]>zzz</CHARS_CDATA1>"); tw.WriteLine("<CHARS_CDATA2><![CDATA[yyy]]>zzz</CHARS_CDATA2>"); tw.WriteLine("<CHARS_CDATA3>xxx<![CDATA[yyy]]></CHARS_CDATA3>"); tw.WriteLine("<CHARS_PI1>xxx<?PI_CHAR1 yyy?>zzz</CHARS_PI1>"); tw.WriteLine("<CHARS_PI2><?PI_CHAR2?>zzz</CHARS_PI2>"); tw.WriteLine("<CHARS_PI3>xxx<?PI_CHAR3 yyy?></CHARS_PI3>"); tw.WriteLine("<CHARS_COMMENT1>xxx<!-- comment1-->zzz</CHARS_COMMENT1>"); tw.WriteLine("<CHARS_COMMENT2><!-- comment1-->zzz</CHARS_COMMENT2>"); tw.WriteLine("<CHARS_COMMENT3>xxx<!-- comment1--></CHARS_COMMENT3>"); tw.Flush(); tw.WriteLine("<ISDEFAULT />"); tw.WriteLine("<ISDEFAULT a1='a1value' />"); tw.WriteLine("<BOOLEAN1>true</BOOLEAN1>"); tw.WriteLine("<BOOLEAN2>false</BOOLEAN2>"); tw.WriteLine("<BOOLEAN3>1</BOOLEAN3>"); tw.WriteLine("<BOOLEAN4>tRue</BOOLEAN4>"); tw.WriteLine("<DATETIME>1999-02-22T11:11:11</DATETIME>"); tw.WriteLine("<DATE>1999-02-22</DATE>"); tw.WriteLine("<TIME>11:11:11</TIME>"); tw.WriteLine("<INTEGER>9999</INTEGER>"); tw.WriteLine("<FLOAT>99.99</FLOAT>"); tw.WriteLine("<DECIMAL>.09</DECIMAL>"); tw.WriteLine("<CONTENT><e1 a1='a1value' a2='a2value'><e2 a1='a1value' a2='a2value'><e3 a1='a1value' a2='a2value'>leave</e3></e2></e1></CONTENT>"); tw.WriteLine("<TITLE><!-- this is a comment--></TITLE>"); tw.WriteLine("<PGROUP>"); tw.WriteLine("<ACT0 xmlns:foo=\"http://www.foo.com\" foo:Attr0=\"0\" foo:Attr1=\"1111111101\" foo:Attr2=\"222222202\" foo:Attr3=\"333333303\" foo:Attr4=\"444444404\" foo:Attr5=\"555555505\" foo:Attr6=\"666666606\" foo:Attr7=\"777777707\" foo:Attr8=\"888888808\" foo:Attr9=\"999999909\" />"); tw.WriteLine("<ACT1 Attr0=\'0\' Attr1=\'1111111101\' Attr2=\'222222202\' Attr3=\'333333303\' Attr4=\'444444404\' Attr5=\'555555505\' Attr6=\'666666606\' Attr7=\'777777707\' Attr8=\'888888808\' Attr9=\'999999909\' />"); tw.WriteLine("<QUOTE1 Attr0=\"0\" Attr1=\'1111111101\' Attr2=\"222222202\" Attr3=\'333333303\' />"); tw.WriteLine("<PERSONA>DROMIO OF EPHESUS</PERSONA>"); tw.WriteLine("<QUOTE2 Attr0=\"0\" Attr1=\"1111111101\" Attr2=\'222222202\' Attr3=\'333333303\' />"); tw.WriteLine("<QUOTE3 Attr0=\'0\' Attr1=\"1111111101\" Attr2=\'222222202\' Attr3=\"333333303\" />"); tw.WriteLine("<EMPTY1 />"); tw.WriteLine("<EMPTY2 val=\"abc\" />"); tw.WriteLine("<EMPTY3></EMPTY3>"); tw.WriteLine("<NONEMPTY0></NONEMPTY0>"); tw.WriteLine("<NONEMPTY1>ABCDE</NONEMPTY1>"); tw.WriteLine("<NONEMPTY2 val=\"abc\">1234</NONEMPTY2>"); tw.WriteLine("<ACT2 Attr0=\"10\" Attr1=\"1111111011\" Attr2=\"222222012\" Attr3=\"333333013\" Attr4=\"444444014\" Attr5=\"555555015\" Attr6=\"666666016\" Attr7=\"777777017\" Attr8=\"888888018\" Attr9=\"999999019\" />"); tw.WriteLine("<GRPDESCR>twin brothers, and sons to Aegeon and Aemilia.</GRPDESCR>"); tw.WriteLine("</PGROUP>"); tw.WriteLine("<PGROUP>"); tw.Flush(); tw.WriteLine("<XMLLANG0 xml:lang=\"en-US\">What color e1foo is it?</XMLLANG0>"); tw.Write("<XMLLANG1 xml:lang=\"en-GB\">What color is it?<a><b><c>Language Test</c><PERSONA>DROMIO OF EPHESUS</PERSONA></b></a></XMLLANG1>"); tw.WriteLine("<NOXMLLANG />"); tw.WriteLine("<EMPTY_XMLLANG Attr0=\"0\" xml:lang=\"en-US\" />"); tw.WriteLine("<XMLLANG2 xml:lang=\"en-US\">What color is it?<TITLE><!-- this is a comment--></TITLE><XMLLANG1 xml:lang=\"en-GB\">Testing language<XMLLANG0 xml:lang=\"en-US\">What color is it?</XMLLANG0>haha </XMLLANG1>hihihi</XMLLANG2>"); tw.WriteLine("<DONEXMLLANG />"); tw.WriteLine("<XMLSPACE1 xml:space=\'default\'>&lt; &gt;</XMLSPACE1>"); tw.Write("<XMLSPACE2 xml:space=\'preserve\'>&lt; &gt;<a><!-- comment--><b><?PI1a?><c>Space Test</c><PERSONA>DROMIO OF SYRACUSE</PERSONA></b></a></XMLSPACE2>"); tw.WriteLine("<NOSPACE />"); tw.WriteLine("<EMPTY_XMLSPACE Attr0=\"0\" xml:space=\'default\' />"); tw.WriteLine("<XMLSPACE2A xml:space=\'default\'>&lt; <XMLSPACE3 xml:space=\'preserve\'> &lt; &gt; <XMLSPACE4 xml:space=\'default\'> &lt; &gt; </XMLSPACE4> test </XMLSPACE3> &gt;</XMLSPACE2A>"); tw.WriteLine("<GRPDESCR>twin brothers, and attendants on the two Antipholuses.</GRPDESCR>"); tw.WriteLine("<DOCNAMESPACE>"); tw.WriteLine("<NAMESPACE0 xmlns:bar=\"1\"><bar:check>Namespace=1</bar:check></NAMESPACE0>"); tw.WriteLine("<NAMESPACE1 xmlns:bar=\"1\"><a><b><c><d><bar:check>Namespace=1</bar:check><bar:check2></bar:check2></d></c></b></a></NAMESPACE1>"); tw.WriteLine("<NONAMESPACE>Namespace=\"\"</NONAMESPACE>"); tw.WriteLine("<EMPTY_NAMESPACE bar:Attr0=\"0\" xmlns:bar=\"1\" />"); tw.WriteLine("<EMPTY_NAMESPACE1 Attr0=\"0\" xmlns=\"14\" />"); tw.WriteLine("<EMPTY_NAMESPACE2 Attr0=\"0\" xmlns=\"14\"></EMPTY_NAMESPACE2>"); tw.WriteLine("<NAMESPACE2 xmlns:bar=\"1\"><a><b><c xmlns:bar=\"2\"><d><bar:check>Namespace=2</bar:check></d></c></b></a></NAMESPACE2>"); tw.WriteLine("<NAMESPACE3 xmlns=\"1\"><a xmlns:a=\"2\" xmlns:b=\"3\" xmlns:c=\"4\"><b xmlns:d=\"5\" xmlns:e=\"6\" xmlns:f='7'><c xmlns:d=\"8\" xmlns:e=\"9\" xmlns:f=\"10\">"); tw.WriteLine("<d xmlns:g=\"11\" xmlns:h=\"12\"><check>Namespace=1</check><testns xmlns=\"100\"><empty100 /><check100>Namespace=100</check100></testns><check1>Namespace=1</check1><d:check8>Namespace=8</d:check8></d></c><d:check5>Namespace=5</d:check5></b></a>"); tw.WriteLine("<a13 a:check=\"Namespace=13\" xmlns:a=\"13\" /><check14 xmlns=\"14\">Namespace=14</check14></NAMESPACE3>"); tw.WriteLine("<NONAMESPACE>Namespace=\"\"</NONAMESPACE>"); tw.WriteLine("<NONAMESPACE1 Attr1=\"one\" xmlns=\"1000\">Namespace=\"\"</NONAMESPACE1>"); tw.WriteLine("</DOCNAMESPACE>"); tw.WriteLine("</PGROUP>"); tw.WriteLine("<GOTOCONTENT>some text<![CDATA[cdata info]]></GOTOCONTENT>"); tw.WriteLine("<SKIPCONTENT att1=\"\"> <!-- comment1--> \n <?PI_SkipContent instruction?></SKIPCONTENT>"); tw.WriteLine("<MIXCONTENT> <!-- comment1-->some text<?PI_SkipContent instruction?><![CDATA[cdata info]]></MIXCONTENT>"); tw.WriteLine("<A att=\"123\">1<B>2<C>3<D>4<E>5<F>6<G>7<H>8<I>9<J>10"); tw.WriteLine("<A1 att=\"456\">11<B1>12<C1>13<D1>14<E1>15<F1>16<G1>17<H1>18<I1>19<J1>20"); tw.WriteLine("<A2 att=\"789\">21<B2>22<C2>23<D2>24<E2>25<F2>26<G2>27<H2>28<I2>29<J2>30"); tw.WriteLine("<A3 att=\"123\">31<B3>32<C3>33<D3>34<E3>35<F3>36<G3>37<H3>38<I3>39<J3>40"); tw.WriteLine("<A4 att=\"456\">41<B4>42<C4>43<D4>44<E4>45<F4>46<G4>47<H4>48<I4>49<J4>50"); tw.WriteLine("<A5 att=\"789\">51<B5>52<C5>53<D5>54<E5>55<F5>56<G5>57<H5>58<I5>59<J5>60"); tw.WriteLine("<A6 att=\"123\">61<B6>62<C6>63<D6>64<E6>65<F6>66<G6>67<H6>68<I6>69<J6>70"); tw.WriteLine("<A7 att=\"456\">71<B7>72<C7>73<D7>74<E7>75<F7>76<G7>77<H7>78<I7>79<J7>80"); tw.WriteLine("<A8 att=\"789\">81<B8>82<C8>83<D8>84<E8>85<F8>86<G8>87<H8>88<I8>89<J8>90"); tw.WriteLine("<A9 att=\"123\">91<B9>92<C9>93<D9>94<E9>95<F9>96<G9>97<H9>98<I9>99<J9>100"); tw.WriteLine("<A10 att=\"123\">101<B10>102<C10>103<D10>104<E10>105<F10>106<G10>107<H10>108<I10>109<J10>110"); tw.WriteLine("</J10>109</I10>108</H10>107</G10>106</F10>105</E10>104</D10>103</C10>102</B10>101</A10>"); tw.WriteLine("</J9>99</I9>98</H9>97</G9>96</F9>95</E9>94</D9>93</C9>92</B9>91</A9>"); tw.WriteLine("</J8>89</I8>88</H8>87</G8>86</F8>85</E8>84</D8>83</C8>82</B8>81</A8>"); tw.WriteLine("</J7>79</I7>78</H7>77</G7>76</F7>75</E7>74</D7>73</C7>72</B7>71</A7>"); tw.WriteLine("</J6>69</I6>68</H6>67</G6>66</F6>65</E6>64</D6>63</C6>62</B6>61</A6>"); tw.WriteLine("</J5>59</I5>58</H5>57</G5>56</F5>55</E5>54</D5>53</C5>52</B5>51</A5>"); tw.WriteLine("</J4>49</I4>48</H4>47</G4>46</F4>45</E4>44</D4>43</C4>42</B4>41</A4>"); tw.WriteLine("</J3>39</I3>38</H3>37</G3>36</F3>35</E3>34</D3>33</C3>32</B3>31</A3>"); tw.WriteLine("</J2>29</I2>28</H2>27</G2>26</F2>25</E2>24</D2>23</C2>22</B2>21</A2>"); tw.WriteLine("</J1>19</I1>18</H1>17</G1>16</F1>15</E1>14</D1>13</C1>12</B1>11</A1>"); tw.Write("</J>9</I>8</H>7</G>6</F>5</E>4</D>3</C>2</B>1</A>"); tw.WriteLine("<EMPTY4 val=\"abc\"></EMPTY4>"); tw.WriteLine("<COMPLEX>Text<!-- comment --><![CDATA[cdata]]></COMPLEX>"); tw.WriteLine("<DUMMY />"); tw.WriteLine("<MULTISPACES att=' \r\n \t \r\r\n n1 \r\n \t \r\r\n n2 \r\n \t \r\r\n ' />"); tw.WriteLine("<CAT>AB<![CDATA[CD]]> </CAT>"); tw.WriteLine("<CATMIXED>AB<![CDATA[CD]]> </CATMIXED>"); tw.WriteLine("<VALIDXMLLANG0 xml:lang=\"a\" />"); tw.WriteLine("<VALIDXMLLANG1 xml:lang=\"\" />"); tw.WriteLine("<VALIDXMLLANG2 xml:lang=\"ab-cd-\" />"); tw.WriteLine("<VALIDXMLLANG3 xml:lang=\"a b-cd\" />"); tw.Write("</PLAY>"); tw.Flush(); FilePathUtil.addStream(strFileName, ms); } public static void CreateBigElementTestFile(string strFileName) { MemoryStream ms = new MemoryStream(); TextWriter tw = new StreamWriter(ms); string str = new String('Z', (1 << 20) - 1); tw.WriteLine("<Root>"); tw.Write("<"); tw.Write(str); tw.WriteLine("X />"); tw.Flush(); tw.Write("<"); tw.Write(str); tw.WriteLine("Y />"); tw.WriteLine("</Root>"); tw.Flush(); FilePathUtil.addStream(strFileName, ms); } } }
using System; using System.Collections.Generic; using UnityEngine; using XposeCraft.Collections; using XposeCraft.Core.Faction; using XposeCraft.Core.Faction.Units; using XposeCraft.Game; using XposeCraft.Game.Actors; using XposeCraft.Game.Actors.Buildings; using XposeCraft.Game.Actors.Resources; using XposeCraft.Game.Actors.Units; using XposeCraft.Game.Control.GameActions; using XposeCraft.Game.Enums; using VisionState = XposeCraft.Core.Fog_Of_War.VisionReceiver.VisionState; namespace XposeCraft.GameInternal { /// <summary> /// Data structures that make up the Model of a Player used within a game. /// It is a good idea not to persist it as a prefab, as the instance will usually hold references to Scene objects. /// </summary> public class Player : MonoBehaviour { /// <summary> /// True if already lost. /// </summary> public bool LostGame { get; set; } /// <summary> /// Reason of losing. /// </summary> public enum LoseReason { ExceptionThrown, AllBuildingsDestroyed, TimeoutStalemate } // Unity hot-swap serialization workarounds. [Serializable] public class EventList : List<GameEvent> { } [Serializable] public class RegisteredEventsDictionary : SerializableDictionary2<GameEventType, EventList> { } /// <summary> /// Curently executing Player to be used as a Model. /// Needs to be replaced before executing any Event. /// </summary> public static Player CurrentPlayer; /// <summary> /// Faction of the Player, allied Players will share it. /// </summary> public Faction Faction; public int FactionIndex; /// <summary> /// This Player's Base. /// </summary> public PlaceType MyBase; /// <summary> /// This Player's Enemy's Base. /// </summary> public PlaceType EnemyBase; /// <summary> /// Actions hooked to Events that can, but don't have to be, run at any time. /// </summary> public RegisteredEventsDictionary RegisteredEvents; // In-game Actors available to the Player. public List<Unit> Units; public List<Building> Buildings; /// <summary> /// Only the first Player's (index 0) Resources are being used! /// </summary> public List<Resource> SharedResources; public List<Unit> EnemyVisibleUnits; public List<Building> EnemyVisibleBuildings; // Run-time configuration of the Player private bool _exceptionOnDeadUnitAction; public bool ExceptionOnDeadUnitAction { get { return _exceptionOnDeadUnitAction; } set { _exceptionOnDeadUnitAction = value; } } public void EnemyOnSight( GameObject enemyActorGameObject, Actor enemyActor, List<GameObject> myActorGameObjectsSaw, List<Actor> myActorsSaw, VisionState previousState, VisionState newState) { if (newState == VisionState.Vision) { EvaluateAttackMove(enemyActor, myActorGameObjectsSaw, myActorsSaw); } // Evaluating visibility event if a change occurred if (previousState != newState) { EnemyVisibilityChanged(enemyActor, myActorsSaw, previousState, newState); } } private static void EvaluateAttackMove( Actor enemyActor, List<GameObject> myActorGameObjectsSaw, List<Actor> myActorsSaw) { // Evaluating Attack Move for (var myActorIndex = 0; myActorIndex < myActorsSaw.Count; myActorIndex++) { var myActorSaw = myActorsSaw[myActorIndex]; // Only Units can respond to seeing an enemy by Attack Move if (!(myActorSaw is IUnit)) { continue; } // TODO: optimize performance by not requesting the component every time var myUnitController = myActorGameObjectsSaw[myActorIndex].GetComponent<UnitController>(); if (!myUnitController.IsAttackMove || myUnitController.AttackMoveTarget != null) { continue; } // A new target causes Attack to be performed before continuing the queue Attack.AttackUnitOrBuilding(enemyActor, myUnitController); myUnitController.AttackMoveTarget = enemyActor; } } private void EnemyVisibilityChanged( Actor enemyActor, List<Actor> myActorsSawChange, VisionState previousState, VisionState newState) { if (previousState == VisionState.Vision && newState != VisionState.Vision) { EnemyHidden(enemyActor, newState); } else if (previousState == VisionState.Undiscovered || previousState == VisionState.Discovered) { EnemyTurnedToVisible(enemyActor, myActorsSawChange); } } private void EnemyTurnedToVisible(Actor enemyActor, List<Actor> myActorsSaw) { // Only the first detection matters, as it is about visibility state "change" var myActor = myActorsSaw.Count == 0 ? null : myActorsSaw[0]; var enemyUnit = enemyActor as IUnit; if (enemyUnit != null) { GameManager.Instance.FiredEvent( this, GameEventType.EnemyUnitsOnSight, new Arguments { MyUnit = myActor as IUnit, MyBuilding = myActor as IBuilding, EnemyUnits = new[] {enemyUnit} }); EnemyVisibleUnits.Add((Unit) enemyUnit); return; } var enemyBuilding = enemyActor as IBuilding; if (enemyBuilding != null) { GameManager.Instance.FiredEvent( this, GameEventType.EnemyBuildingsOnSight, new Arguments { MyUnit = myActor as IUnit, MyBuilding = myActor as IBuilding, EnemyBuildings = new[] {enemyBuilding} }); EnemyVisibleBuildings.Add((Building) enemyBuilding); } } private void EnemyHidden(Actor enemyActor, VisionState newState) { var unit = enemyActor as IUnit; if (unit != null) { EnemyVisibleUnits.Remove((Unit) unit); return; } var building = enemyActor as IBuilding; if (building != null && newState == VisionState.Undiscovered) { EnemyVisibleBuildings.Remove((Building) building); } } public void Win() { if (this == GameManager.Instance.GuiPlayer) { GameTestRunner.Passed = true; } Log.i(string.Format("Player {0} won the game", name)); } public void Lost(LoseReason loseReason) { if (LostGame) { return; } LostGame = true; switch (loseReason) { case LoseReason.ExceptionThrown: Log.e(string.Format("Player {0} lost because an exception was thrown", name)); break; case LoseReason.AllBuildingsDestroyed: Log.e(string.Format("Player {0} lost because all his buildings were destroyed", name)); break; case LoseReason.TimeoutStalemate: Log.e(string.Format("Stalemate. Player {0} lost because of a game timeout", name)); break; default: throw new ArgumentOutOfRangeException("loseReason", loseReason, null); } if (this == GameManager.Instance.GuiPlayer) { GameTestRunner.Failed = true; } // This causes enemies to Win if they don't have any more enemies if (loseReason == LoseReason.TimeoutStalemate) { return; } foreach (var enemyFactionIndex in Faction.EnemyFactionIndexes()) { foreach (var player in GameManager.Instance.Players) { if (this != player && player.FactionIndex == enemyFactionIndex) { player.Win(); } } } } public void Lost(Exception exception) { Log.e(exception); Lost(LoseReason.ExceptionThrown); } } }
//--------------------------------------------------------------------------- // // <copyright file="AxisAngleRotation3D.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Markup; using System.Windows.Media.Media3D.Converters; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using System.Windows.Media.Imaging; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media.Media3D { sealed partial class AxisAngleRotation3D : Rotation3D { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new AxisAngleRotation3D Clone() { return (AxisAngleRotation3D)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new AxisAngleRotation3D CloneCurrentValue() { return (AxisAngleRotation3D)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void AxisPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { AxisAngleRotation3D target = ((AxisAngleRotation3D) d); target.AxisPropertyChangedHook(e); target.PropertyChanged(AxisProperty); } private static void AnglePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { AxisAngleRotation3D target = ((AxisAngleRotation3D) d); target.AnglePropertyChangedHook(e); target.PropertyChanged(AngleProperty); } #region Public Properties /// <summary> /// Axis - Vector3D. Default value is new Vector3D(0,1,0). /// </summary> public Vector3D Axis { get { return (Vector3D) GetValue(AxisProperty); } set { SetValueInternal(AxisProperty, value); } } /// <summary> /// Angle - double. Default value is (double)0.0. /// </summary> public double Angle { get { return (double) GetValue(AngleProperty); } set { SetValueInternal(AngleProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new AxisAngleRotation3D(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <SecurityNote> /// Critical: This code calls into an unsafe code block /// TreatAsSafe: This code does not return any critical data.It is ok to expose /// Channels are safe to call into and do not go cross domain and cross process /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { // If we're told we can skip the channel check, then we must be on channel Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel)); if (skipOnChannelCheck || _duceResource.IsOnChannel(channel)) { base.UpdateResource(channel, skipOnChannelCheck); // Obtain handles for animated properties DUCE.ResourceHandle hAxisAnimations = GetAnimationResourceHandle(AxisProperty, channel); DUCE.ResourceHandle hAngleAnimations = GetAnimationResourceHandle(AngleProperty, channel); // Pack & send command packet DUCE.MILCMD_AXISANGLEROTATION3D data; unsafe { data.Type = MILCMD.MilCmdAxisAngleRotation3D; data.Handle = _duceResource.GetHandle(channel); if (hAxisAnimations.IsNull) { data.axis = CompositionResourceManager.Vector3DToMilPoint3F(Axis); } data.hAxisAnimations = hAxisAnimations; if (hAngleAnimations.IsNull) { data.angle = Angle; } data.hAngleAnimations = hAngleAnimations; // Send packed command structure channel.SendCommand( (byte*)&data, sizeof(DUCE.MILCMD_AXISANGLEROTATION3D)); } } } internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel) { if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_AXISANGLEROTATION3D)) { AddRefOnChannelAnimations(channel); UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ ); } return _duceResource.GetHandle(channel); } internal override void ReleaseOnChannelCore(DUCE.Channel channel) { Debug.Assert(_duceResource.IsOnChannel(channel)); if (_duceResource.ReleaseOnChannel(channel)) { ReleaseOnChannelAnimations(channel); } } internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel) { // Note that we are in a lock here already. return _duceResource.GetHandle(channel); } internal override int GetChannelCountCore() { // must already be in composition lock here return _duceResource.GetChannelCount(); } internal override DUCE.Channel GetChannelCore(int index) { // Note that we are in a lock here already. return _duceResource.GetChannel(index); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the AxisAngleRotation3D.Axis property. /// </summary> public static readonly DependencyProperty AxisProperty; /// <summary> /// The DependencyProperty for the AxisAngleRotation3D.Angle property. /// </summary> public static readonly DependencyProperty AngleProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource(); internal static Vector3D s_Axis = new Vector3D(0,1,0); internal const double c_Angle = (double)0.0; #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static AxisAngleRotation3D() { // We check our static default fields which are of type Freezable // to make sure that they are not mutable, otherwise we will throw // if these get touched by more than one thread in the lifetime // of your app. (Windows OS Bug #947272) // // Initializations Type typeofThis = typeof(AxisAngleRotation3D); AxisProperty = RegisterProperty("Axis", typeof(Vector3D), typeofThis, new Vector3D(0,1,0), new PropertyChangedCallback(AxisPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); AngleProperty = RegisterProperty("Angle", typeof(double), typeofThis, (double)0.0, new PropertyChangedCallback(AnglePropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); } #endregion Constructors } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServiceBus.Fluent { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// NamespacesOperations operations. /// </summary> public partial interface INamespacesOperations { /// <summary> /// Check the give namespace name availability. /// </summary> /// <param name='name'> /// The Name to check the namespce name availability and The namespace /// name can contain only letters, numbers, and hyphens. The namespace /// must start with a letter, and it must end with a letter or number. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<CheckNameAvailabilityResultInner>> CheckNameAvailabilityMethodWithHttpMessagesAsync(string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the available namespaces within the subscription, /// irrespective of the resource groups. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NamespaceModelInner>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the available namespaces within a resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NamespaceModelInner>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a service namespace. Once created, this /// namespace's resource manifest is immutable. This operation is /// idempotent. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639408.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='parameters'> /// Parameters supplied to create a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NamespaceModelInner>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceModelInner parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated resources under the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639389.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a description for the specified namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639379.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NamespaceModelInner>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='parameters'> /// Parameters supplied to update a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NamespaceModelInner>> UpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceUpdateParametersInner parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the authorization rules for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639376.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleInner>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates an authorization rule for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639410.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='rights'> /// The rights associated with the rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedAccessAuthorizationRuleInner>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, IList<AccessRights?> rights, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a namespace authorization rule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639417.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets an authorization rule for a namespace by rule name. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639392.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedAccessAuthorizationRuleInner>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the primary and secondary connection strings for the /// namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639398.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ResourceListKeysInner>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the primary or secondary connection strings for the /// namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt718977.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='policykey'> /// Key that needs to be regenerated. Possible values include: /// 'PrimaryKey', 'SecondaryKey' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ResourceListKeysInner>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Policykey? policykey = default(Policykey?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a service namespace. Once created, this /// namespace's resource manifest is immutable. This operation is /// idempotent. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639408.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='parameters'> /// Parameters supplied to create a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NamespaceModelInner>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceModelInner parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated resources under the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639389.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the available namespaces within the subscription, /// irrespective of the resource groups. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NamespaceModelInner>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the available namespaces within a resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NamespaceModelInner>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the authorization rules for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639376.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleInner>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// // 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.Collections.Generic; using System.Text; using Encog.MathUtil.Randomize.Generate; using Encog.ML.Data; using Encog.ML.Data.Cross; using Encog.ML.Data.Versatile; using Encog.ML.Data.Versatile.Columns; using Encog.ML.Data.Versatile.Division; using Encog.ML.Factory; using Encog.ML.Model.Config; using Encog.ML.Train; using Encog.ML.Train.Strategy.End; using Encog.Util; using Encog.Util.Simple; namespace Encog.ML.Model { /// <summary> /// Encog model is designed to allow you to easily swap between different model /// types and automatically normalize data. It is designed to work with a /// VersatileMLDataSet only. /// </summary> public class EncogModel { /// <summary> /// The dataset to use. /// </summary> private readonly VersatileMLDataSet _dataset; /// <summary> /// The input features. /// </summary> private readonly IList<ColumnDefinition> _inputFeatures = new List<ColumnDefinition>(); /// <summary> /// The standard configrations for each method type. /// </summary> private readonly IDictionary<string, IMethodConfig> _methodConfigurations = new Dictionary<string, IMethodConfig>(); /// <summary> /// The predicted features. /// </summary> private readonly IList<ColumnDefinition> _predictedFeatures = new List<ColumnDefinition>(); /// <summary> /// The current method configuration, determined by the selected model. /// </summary> private IMethodConfig _config; /// <summary> /// The method arguments for the selected method. /// </summary> private string _methodArgs; /// <summary> /// The selected method type. /// </summary> private string _methodType; /// <summary> /// The training arguments for the selected training type. /// </summary> private string _trainingArgs; /// <summary> /// The selected training type. /// </summary> private string _trainingType; /// <summary> /// Default constructor. /// </summary> public EncogModel() { Report = new NullStatusReportable(); } /// <summary> /// Construct a model for the specified dataset. /// </summary> /// <param name="theDataset">The dataset.</param> public EncogModel(VersatileMLDataSet theDataset) : this() { _dataset = theDataset; _methodConfigurations[MLMethodFactory.TypeFeedforward] = new FeedforwardConfig(); _methodConfigurations[MLMethodFactory.TypeSVM] = new SVMConfig(); _methodConfigurations[MLMethodFactory.TypeRbfnetwork] = new RBFNetworkConfig(); _methodConfigurations[MLMethodFactory.TypeNEAT] = new NEATConfig(); _methodConfigurations[MLMethodFactory.TypePNN] = new PNNConfig(); } /// <summary> /// The training dataset. /// </summary> public MatrixMLDataSet TrainingDataset { get; set; } /// <summary> /// The validation dataset. /// </summary> public MatrixMLDataSet ValidationDataset { get; set; } /// <summary> /// The report. /// </summary> public IStatusReportable Report { get; set; } /// <summary> /// The data set. /// </summary> public VersatileMLDataSet Dataset { get { return _dataset; } } /// <summary> /// The input features. /// </summary> public IList<ColumnDefinition> InputFeatures { get { return _inputFeatures; } } /// <summary> /// The predicted features. /// </summary> public IList<ColumnDefinition> PredictedFeatures { get { return _predictedFeatures; } } /// <summary> /// The method configurations. /// </summary> public IDictionary<String, IMethodConfig> MethodConfigurations { get { return _methodConfigurations; } } /// <summary> /// Specify a validation set to hold back. /// </summary> /// <param name="validationPercent">The percent to use for validation.</param> /// <param name="shuffle">True to shuffle.</param> /// <param name="seed">The seed for random generation.</param> public void HoldBackValidation(double validationPercent, bool shuffle, int seed) { IList<DataDivision> dataDivisionList = new List<DataDivision>(); dataDivisionList.Add(new DataDivision(1.0 - validationPercent)); // Training dataDivisionList.Add(new DataDivision(validationPercent)); // Validation _dataset.Divide(dataDivisionList, shuffle, new MersenneTwisterGenerateRandom((uint) seed)); TrainingDataset = dataDivisionList[0].Dataset; ValidationDataset = dataDivisionList[1].Dataset; } /// <summary> /// Fit the model using cross validation. /// </summary> /// <param name="k">The number of folds total.</param> /// <param name="foldNum">The current fold.</param> /// <param name="fold">The current fold.</param> private void FitFold(int k, int foldNum, DataFold fold) { IMLMethod method = CreateMethod(); IMLTrain train = CreateTrainer(method, fold.Training); if (train.ImplementationType == TrainingImplementationType.Iterative) { var earlyStop = new SimpleEarlyStoppingStrategy( fold.Validation); train.AddStrategy(earlyStop); var line = new StringBuilder(); while (!train.TrainingDone) { train.Iteration(); line.Length = 0; line.Append("Fold #"); line.Append(foldNum); line.Append("/"); line.Append(k); line.Append(": Iteration #"); line.Append(train.IterationNumber); line.Append(", Training Error: "); line.Append(Format.FormatDouble(train.Error, 8)); line.Append(", Validation Error: "); line.Append(Format.FormatDouble(earlyStop.ValidationError, 8)); Report.Report(k, foldNum, line.ToString()); } fold.Score = earlyStop.ValidationError; fold.Method = method; } else if (train.ImplementationType == TrainingImplementationType.OnePass) { train.Iteration(); double validationError = CalculateError(method, fold.Validation); Report.Report(k, k, "Trained, Training Error: " + train.Error + ", Validatoin Error: " + validationError); fold.Score = validationError; fold.Method = method; } else { throw new EncogError("Unsupported training type for EncogModel: " + train.ImplementationType); } } /// <summary> /// Calculate the error for the given method and dataset. /// </summary> /// <param name="method">The method to use.</param> /// <param name="data">The data to use.</param> /// <returns>The error.</returns> public double CalculateError(IMLMethod method, IMLDataSet data) { if (_dataset.NormHelper.OutputColumns.Count == 1) { ColumnDefinition cd = _dataset.NormHelper .OutputColumns[0]; if (cd.DataType == ColumnType.Nominal) { return EncogUtility.CalculateClassificationError( (IMLClassification) method, data); } } return EncogUtility.CalculateRegressionError((IMLRegression) method, data); } /// <summary> /// Create a trainer. /// </summary> /// <param name="method">The method to train.</param> /// <param name="dataset">The dataset.</param> /// <returns>The trainer.</returns> private IMLTrain CreateTrainer(IMLMethod method, IMLDataSet dataset) { if (_trainingType == null) { throw new EncogError( "Please call selectTraining first to choose how to train."); } var trainFactory = new MLTrainFactory(); IMLTrain train = trainFactory.Create(method, dataset, _trainingType, _trainingArgs); return train; } /// <summary> /// Crossvalidate and fit. /// </summary> /// <param name="k">The number of folds.</param> /// <param name="shuffle">True if we should shuffle.</param> /// <returns>The trained method.</returns> public IMLMethod Crossvalidate(int k, bool shuffle) { var cross = new KFoldCrossvalidation( TrainingDataset, k); cross.Process(shuffle); int foldNumber = 0; foreach (DataFold fold in cross.Folds) { foldNumber++; Report.Report(k, foldNumber, "Fold #" + foldNumber); FitFold(k, foldNumber, fold); } double sum = 0; double bestScore = Double.PositiveInfinity; IMLMethod bestMethod = null; foreach (DataFold fold in cross.Folds) { sum += fold.Score; if (fold.Score < bestScore) { bestScore = fold.Score; bestMethod = fold.Method; } } sum = sum/cross.Folds.Count; Report.Report(k, k, "Cross-validated score:" + sum); return bestMethod; } /// <summary> /// Select the method to use. /// </summary> /// <param name="dataset">The dataset.</param> /// <param name="methodType">The type of method.</param> /// <param name="methodArgs">The method arguments.</param> /// <param name="trainingType">The training type.</param> /// <param name="trainingArgs">The training arguments.</param> public void SelectMethod(VersatileMLDataSet dataset, String methodType, String methodArgs, String trainingType, String trainingArgs) { if (!_methodConfigurations.ContainsKey(methodType)) { throw new EncogError("Don't know how to autoconfig method: " + methodType); } _methodType = methodType; _methodArgs = methodArgs; dataset.NormHelper.NormStrategy = _methodConfigurations[methodType] .SuggestNormalizationStrategy(dataset, methodArgs); } /// <summary> /// Create the selected method. /// </summary> /// <returns>The created method.</returns> public IMLMethod CreateMethod() { if (_methodType == null) { throw new EncogError( "Please call selectMethod first to choose what type of method you wish to use."); } var methodFactory = new MLMethodFactory(); IMLMethod method = methodFactory.Create(_methodType, _methodArgs, _dataset .NormHelper.CalculateNormalizedInputCount(), _config .DetermineOutputCount(_dataset)); return method; } /// <summary> /// Select the method to create. /// </summary> /// <param name="dataset">The dataset.</param> /// <param name="methodType">The method type.</param> public void SelectMethod(VersatileMLDataSet dataset, String methodType) { if (!_methodConfigurations.ContainsKey(methodType)) { throw new EncogError("Don't know how to autoconfig method: " + methodType); } _config = _methodConfigurations[methodType]; _methodType = methodType; _methodArgs = _config.SuggestModelArchitecture(dataset); dataset.NormHelper.NormStrategy = _config.SuggestNormalizationStrategy(dataset, _methodArgs); } /// <summary> /// Select the training type. /// </summary> /// <param name="dataset">The dataset.</param> public void SelectTrainingType(VersatileMLDataSet dataset) { if (_methodType == null) { throw new EncogError( "Please select your training method, before your training type."); } IMethodConfig config = _methodConfigurations[_methodType]; SelectTraining(dataset, config.SuggestTrainingType(), config.SuggestTrainingArgs(_trainingType)); } /// <summary> /// Select the training to use. /// </summary> /// <param name="dataset">The dataset.</param> /// <param name="trainingType">The type of training.</param> /// <param name="trainingArgs">The training arguments.</param> public void SelectTraining(VersatileMLDataSet dataset, String trainingType, String trainingArgs) { if (_methodType == null) { throw new EncogError( "Please select your training method, before your training type."); } _trainingType = trainingType; _trainingArgs = trainingArgs; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; [AddComponentMenu("2D Toolkit/Camera/tk2dCamera")] [ExecuteInEditMode] /// <summary> /// Maintains a screen resolution camera. /// Whole number increments seen through this camera represent one pixel. /// For example, setting an object to 300, 300 will position it at exactly that pixel position. /// </summary> public class tk2dCamera : MonoBehaviour { static int CURRENT_VERSION = 1; public int version = 0; [SerializeField] private tk2dCameraSettings cameraSettings = new tk2dCameraSettings(); /// <summary> /// The unity camera settings. /// Use this instead of camera.XXX to change parameters. /// </summary> public tk2dCameraSettings CameraSettings { get { return cameraSettings; } } /// <summary> /// Resolution overrides, if necessary. See <see cref="tk2dCameraResolutionOverride"/> /// </summary> public tk2dCameraResolutionOverride[] resolutionOverride = new tk2dCameraResolutionOverride[1] { tk2dCameraResolutionOverride.DefaultOverride }; /// <summary> /// The currently used override /// </summary> public tk2dCameraResolutionOverride CurrentResolutionOverride { get { tk2dCamera settings = SettingsRoot; Camera cam = ScreenCamera; float pixelWidth = cam.pixelWidth; float pixelHeight = cam.pixelHeight; #if UNITY_EDITOR if (settings.useGameWindowResolutionInEditor) { pixelWidth = settings.gameWindowResolution.x; pixelHeight = settings.gameWindowResolution.y; } else if (settings.forceResolutionInEditor) { pixelWidth = settings.forceResolution.x; pixelHeight = settings.forceResolution.y; } #endif tk2dCameraResolutionOverride currentResolutionOverride = null; if ((currentResolutionOverride == null || (currentResolutionOverride != null && (currentResolutionOverride.width != pixelWidth || currentResolutionOverride.height != pixelHeight)) )) { currentResolutionOverride = null; // find one if it matches the current resolution if (settings.resolutionOverride != null) { foreach (var ovr in settings.resolutionOverride) { if (ovr.Match((int)pixelWidth, (int)pixelHeight)) { currentResolutionOverride = ovr; break; } } } } return currentResolutionOverride; } } /// <summary> /// A tk2dCamera to inherit configuration from. /// All resolution and override settings will be pulled from the root inherited camera. /// This allows you to create a tk2dCamera prefab in your project or a master camera /// in the scene and guarantee that multiple instances of tk2dCameras referencing this /// will use exactly the same paramaters. /// </summary> public tk2dCamera InheritConfig { get { return inheritSettings; } set { if (inheritSettings != value) { inheritSettings = value; _settingsRoot = null; } } } [SerializeField] private tk2dCamera inheritSettings = null; /// <summary> /// Native resolution width of the camera. Override this in the inspector. /// Don't change this at runtime unless you understand the implications. /// </summary> public int nativeResolutionWidth = 960; /// <summary> /// Native resolution height of the camera. Override this in the inspector. /// Don't change this at runtime unless you understand the implications. /// </summary> public int nativeResolutionHeight = 640; [SerializeField] private Camera _unityCamera; private Camera UnityCamera { get { if (_unityCamera == null) { _unityCamera = camera; if (_unityCamera == null) { Debug.LogError("A unity camera must be attached to the tk2dCamera script"); } } return _unityCamera; } } static tk2dCamera inst; /// <summary> /// Global instance, used by sprite and textmesh class to quickly find the tk2dCamera instance. /// </summary> public static tk2dCamera Instance { get { return inst; } } // Global instance of active tk2dCameras, used to quickly find cameras matching a particular layer. private static List<tk2dCamera> allCameras = new List<tk2dCamera>(); /// <summary> /// Returns the first camera in the list that can "see" this layer, or null if none can be found /// </summary> public static tk2dCamera CameraForLayer( int layer ) { int layerMask = 1 << layer; int cameraCount = allCameras.Count; for (int i = 0; i < cameraCount; ++i) { tk2dCamera cam = allCameras[i]; if ((cam.UnityCamera.cullingMask & layerMask) == layerMask) { return cam; } } return null; } /// <summary> /// Returns screen extents - top, bottom, left and right will be the extent of the physical screen /// Regardless of resolution or override /// </summary> public Rect ScreenExtents { get { return _screenExtents; } } /// <summary> /// Returns screen extents - top, bottom, left and right will be the extent of the native screen /// before it gets scaled and processed by overrides /// </summary> public Rect NativeScreenExtents { get { return _nativeScreenExtents; } } /// <summary> /// Enable/disable viewport clipping. /// ScreenCamera must be valid for it to be actually enabled when rendering. /// </summary> public bool viewportClippingEnabled = false; /// <summary> /// Viewport clipping region. /// </summary> public Vector4 viewportRegion = new Vector4(0, 0, 100, 100); /// <summary> /// Target resolution /// The target resolution currently being used. /// If displaying on a 960x640 display, this will be the number returned here, regardless of scale, etc. /// If the editor resolution is forced, the returned value will be the forced resolution. /// </summary> public Vector2 TargetResolution { get { return _targetResolution; } } Vector2 _targetResolution = Vector2.zero; /// <summary> /// Native resolution /// The native resolution of this camera. /// This is the native resolution of the camera before any scaling is performed. /// The resolution the game is set up to run at initially. /// </summary> public Vector2 NativeResolution { get { return new Vector2(nativeResolutionWidth, nativeResolutionHeight); } } // Some obselete functions, use ScreenExtents instead [System.Obsolete] public Vector2 ScreenOffset { get { return new Vector2(ScreenExtents.xMin - NativeScreenExtents.xMin, ScreenExtents.yMin - NativeScreenExtents.yMin); } } [System.Obsolete] public Vector2 resolution { get { return new Vector2( ScreenExtents.xMax, ScreenExtents.yMax ); } } [System.Obsolete] public Vector2 ScreenResolution { get { return new Vector2( ScreenExtents.xMax, ScreenExtents.yMax ); } } [System.Obsolete] public Vector2 ScaledResolution { get { return new Vector2( ScreenExtents.width, ScreenExtents.height ); } } /// <summary> /// Zooms the current display /// A zoom factor of 2 will zoom in 2x, i.e. the object on screen will be twice as large /// Anchors will still be anchored, but will be scaled with the zoomScale. /// It is recommended to use a second camera for HUDs if necessary to avoid this behaviour. /// </summary> public float ZoomFactor { get { return zoomFactor; } set { zoomFactor = Mathf.Max(0.01f, value); } } /// <summary> /// Obselete - use <see cref="ZoomFactor"/> instead. /// </summary> [System.Obsolete] public float zoomScale { get { return 1.0f / Mathf.Max(0.001f, zoomFactor); } set { ZoomFactor = 1.0f / Mathf.Max(0.001f, value); } } [SerializeField] float zoomFactor = 1.0f; [HideInInspector] /// <summary> /// Forces the resolution in the editor. This option is only used when tk2dCamera can't detect the game window resolution. /// </summary> public bool forceResolutionInEditor = false; [HideInInspector] /// <summary> /// The resolution to force the game window to when <see cref="forceResolutionInEditor"/> is enabled. /// </summary> public Vector2 forceResolution = new Vector2(960, 640); #if UNITY_EDITOR // When true, overrides the "forceResolutionInEditor" flag above bool useGameWindowResolutionInEditor = false; // Usred when useGameWindowResolutionInEditor == true Vector2 gameWindowResolution = new Vector2(960, 640); #endif /// <summary> /// The camera that sees the screen - i.e. if viewport clipping is enabled, its the camera that sees the entire screen /// </summary> public Camera ScreenCamera { get { bool viewportClippingEnabled = this.viewportClippingEnabled && this.inheritSettings != null && this.inheritSettings.UnityCamera.rect == unitRect; return viewportClippingEnabled ? this.inheritSettings.UnityCamera : UnityCamera; } } // Use this for initialization void Awake () { Upgrade(); if (allCameras.IndexOf(this) == -1) { allCameras.Add(this); } tk2dCamera settings = SettingsRoot; tk2dCameraSettings inheritedCameraSettings = settings.CameraSettings; if (inheritedCameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { UnityCamera.transparencySortMode = inheritedCameraSettings.transparencySortMode; } } void OnEnable() { if (UnityCamera != null) { UpdateCameraMatrix(); } else { this.camera.enabled = false; } if (!viewportClippingEnabled) // the main camera can't display rect inst = this; if (allCameras.IndexOf(this) == -1) { allCameras.Add(this); } } void OnDestroy() { int idx = allCameras.IndexOf(this); if (idx != -1) { allCameras.RemoveAt( idx ); } } void OnPreCull() { // Commit all pending changes - this more or less guarantees // everything is committed before drawing this camera. tk2dUpdateManager.FlushQueues(); UpdateCameraMatrix(); } #if UNITY_EDITOR void LateUpdate() { if (!Application.isPlaying) { UpdateCameraMatrix(); } } #endif Rect _screenExtents; Rect _nativeScreenExtents; Rect unitRect = new Rect(0, 0, 1, 1); // Gives you the size of one pixel in world units at the native resolution // For perspective cameras, it is dependent on the distance to the camera. public float GetSizeAtDistance(float distance) { tk2dCameraSettings cameraSettings = SettingsRoot.CameraSettings; switch (cameraSettings.projection) { case tk2dCameraSettings.ProjectionType.Orthographic: if (cameraSettings.orthographicType == tk2dCameraSettings.OrthographicType.PixelsPerMeter) { return 1.0f / cameraSettings.orthographicPixelsPerMeter; } else { return 2.0f * cameraSettings.orthographicSize / SettingsRoot.nativeResolutionHeight; } case tk2dCameraSettings.ProjectionType.Perspective: return Mathf.Tan(CameraSettings.fieldOfView * Mathf.Deg2Rad * 0.5f) * distance * 2.0f / SettingsRoot.nativeResolutionHeight; } return 1; } // This returns the tk2dCamera object which has the settings stored on it // Trace back to the source, however far up the hierarchy that may be // You can't change this at runtime tk2dCamera _settingsRoot; public tk2dCamera SettingsRoot { get { if (_settingsRoot == null) { _settingsRoot = (inheritSettings == null || inheritSettings == this) ? this : inheritSettings.SettingsRoot; } return _settingsRoot; } } #if UNITY_EDITOR public static tk2dCamera Editor__Inst { get { if (inst != null) { return inst; } return GameObject.FindObjectOfType(typeof(tk2dCamera)) as tk2dCamera; } } #endif #if UNITY_EDITOR static bool Editor__getGameViewSizeError = false; public static bool Editor__gameViewReflectionError = false; // Try and get game view size // Will return true if it is able to work this out // If width / height == 0, it means the user has selected an aspect ratio "Resolution" public static bool Editor__GetGameViewSize(out float width, out float height, out float aspect) { try { Editor__gameViewReflectionError = false; System.Type gameViewType = System.Type.GetType("UnityEditor.GameView,UnityEditor"); System.Reflection.MethodInfo GetMainGameView = gameViewType.GetMethod("GetMainGameView", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); object mainGameViewInst = GetMainGameView.Invoke(null, null); if (mainGameViewInst == null) { width = height = aspect = 0; return false; } System.Reflection.FieldInfo s_viewModeResolutions = gameViewType.GetField("s_viewModeResolutions", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); if (s_viewModeResolutions == null) { System.Reflection.PropertyInfo currentGameViewSize = gameViewType.GetProperty("currentGameViewSize", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); object gameViewSize = currentGameViewSize.GetValue(mainGameViewInst, null); System.Type gameViewSizeType = gameViewSize.GetType(); int gvWidth = (int)gameViewSizeType.GetProperty("width").GetValue(gameViewSize, null); int gvHeight = (int)gameViewSizeType.GetProperty("height").GetValue(gameViewSize, null); int gvSizeType = (int)gameViewSizeType.GetProperty("sizeType").GetValue(gameViewSize, null); if (gvWidth == 0 || gvHeight == 0) { width = height = aspect = 0; return false; } else if (gvSizeType == 0) { width = height = 0; aspect = (float)gvWidth / (float)gvHeight; return true; } else { width = gvWidth; height = gvHeight; aspect = (float)gvWidth / (float)gvHeight; return true; } } else { Vector2[] viewModeResolutions = (Vector2[])s_viewModeResolutions.GetValue(null); float[] viewModeAspects = (float[])gameViewType.GetField("s_viewModeAspects", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(null); string[] viewModeStrings = (string[])gameViewType.GetField("s_viewModeAspectStrings", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(null); if (mainGameViewInst != null && viewModeStrings != null && viewModeResolutions != null && viewModeAspects != null) { int aspectRatio = (int)gameViewType.GetField("m_AspectRatio", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(mainGameViewInst); string thisViewModeString = viewModeStrings[aspectRatio]; if (thisViewModeString.Contains("Standalone")) { width = UnityEditor.PlayerSettings.defaultScreenWidth; height = UnityEditor.PlayerSettings.defaultScreenHeight; aspect = width / height; } else if (thisViewModeString.Contains("Web")) { width = UnityEditor.PlayerSettings.defaultWebScreenWidth; height = UnityEditor.PlayerSettings.defaultWebScreenHeight; aspect = width / height; } else { width = viewModeResolutions[ aspectRatio ].x; height = viewModeResolutions[ aspectRatio ].y; aspect = viewModeAspects[ aspectRatio ]; // this is an error state if (width == 0 && height == 0 && aspect == 0) { return false; } } return true; } } } catch (System.Exception e) { if (Editor__getGameViewSizeError == false) { Debug.LogError("tk2dCamera.GetGameViewSize - has a Unity update broken this?\nThis is not a fatal error, but a warning that you've probably not got the latest 2D Toolkit update.\n\n" + e.ToString()); Editor__getGameViewSizeError = true; } Editor__gameViewReflectionError = true; } width = height = aspect = 0; return false; } #endif public Matrix4x4 OrthoOffCenter(Vector2 scale, float left, float right, float bottom, float top, float near, float far) { // Additional half texel offset // Takes care of texture unit offset, if necessary. float x = (2.0f) / (right - left) * scale.x; float y = (2.0f) / (top - bottom) * scale.y; float z = -2.0f / (far - near); float a = -(right + left) / (right - left); float b = -(bottom + top) / (top - bottom); float c = -(far + near) / (far - near); Matrix4x4 m = new Matrix4x4(); m[0,0] = x; m[0,1] = 0; m[0,2] = 0; m[0,3] = a; m[1,0] = 0; m[1,1] = y; m[1,2] = 0; m[1,3] = b; m[2,0] = 0; m[2,1] = 0; m[2,2] = z; m[2,3] = c; m[3,0] = 0; m[3,1] = 0; m[3,2] = 0; m[3,3] = 1; return m; } Vector2 GetScaleForOverride(tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, float width, float height) { Vector2 scale = Vector2.one; float s = 1.0f; if (currentOverride == null) { return scale; } switch (currentOverride.autoScaleMode) { case tk2dCameraResolutionOverride.AutoScaleMode.PixelPerfect: s = 1; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitHeight: s = height / settings.nativeResolutionHeight; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitWidth: s = width / settings.nativeResolutionWidth; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitVisible: case tk2dCameraResolutionOverride.AutoScaleMode.ClosestMultipleOfTwo: float nativeAspect = (float)settings.nativeResolutionWidth / settings.nativeResolutionHeight; float currentAspect = width / height; if (currentAspect < nativeAspect) s = width / settings.nativeResolutionWidth; else s = height / settings.nativeResolutionHeight; if (currentOverride.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.ClosestMultipleOfTwo) { if (s > 1.0f) s = Mathf.Floor(s); // round number else s = Mathf.Pow(2, Mathf.Floor(Mathf.Log(s, 2))); // minimise only as power of two } scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit: scale.Set(width / settings.nativeResolutionWidth, height / settings.nativeResolutionHeight); break; case tk2dCameraResolutionOverride.AutoScaleMode.Fill: s = Mathf.Max(width / settings.nativeResolutionWidth,height / settings.nativeResolutionHeight); scale.Set(s, s); break; default: case tk2dCameraResolutionOverride.AutoScaleMode.None: s = currentOverride.scale; scale.Set(s, s); break; } return scale; } Vector2 GetOffsetForOverride(tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, Vector2 scale, float width, float height) { Vector2 offset = Vector2.zero; if (currentOverride == null) { return offset; } switch (currentOverride.fitMode) { case tk2dCameraResolutionOverride.FitMode.Center: if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.BottomLeft) { offset = new Vector2(Mathf.Round((settings.nativeResolutionWidth * scale.x - width ) / 2.0f), Mathf.Round((settings.nativeResolutionHeight * scale.y - height) / 2.0f)); } break; default: case tk2dCameraResolutionOverride.FitMode.Constant: offset = -currentOverride.offsetPixels; break; } return offset; } #if UNITY_EDITOR private Matrix4x4 Editor__GetPerspectiveMatrix() { float aspect = (float)nativeResolutionWidth / (float)nativeResolutionHeight; return Matrix4x4.Perspective(SettingsRoot.CameraSettings.fieldOfView, aspect, UnityCamera.nearClipPlane, UnityCamera.farClipPlane); } public Matrix4x4 Editor__GetNativeProjectionMatrix( ) { tk2dCamera settings = SettingsRoot; if (settings.CameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { return Editor__GetPerspectiveMatrix(); } Rect rect1 = new Rect(0, 0, 1, 1); Rect rect2 = new Rect(0, 0, 1, 1); return GetProjectionMatrixForOverride( settings, null, nativeResolutionWidth, nativeResolutionHeight, false, out rect1, out rect2 ); } public Matrix4x4 Editor__GetFinalProjectionMatrix( ) { tk2dCamera settings = SettingsRoot; if (settings.CameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { return Editor__GetPerspectiveMatrix(); } Vector2 resolution = GetScreenPixelDimensions(settings); Rect rect1 = new Rect(0, 0, 1, 1); Rect rect2 = new Rect(0, 0, 1, 1); return GetProjectionMatrixForOverride( settings, settings.CurrentResolutionOverride, resolution.x, resolution.y, false, out rect1, out rect2 ); } #endif Matrix4x4 GetProjectionMatrixForOverride( tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, float pixelWidth, float pixelHeight, bool halfTexelOffset, out Rect screenExtents, out Rect unscaledScreenExtents ) { Vector2 scale = GetScaleForOverride( settings, currentOverride, pixelWidth, pixelHeight ); Vector2 offset = GetOffsetForOverride( settings, currentOverride, scale, pixelWidth, pixelHeight); float left = offset.x, bottom = offset.y; float right = pixelWidth + offset.x, top = pixelHeight + offset.y; Vector2 nativeResolutionOffset = Vector2.zero; bool usingLegacyViewportClipping = false; // Correct for viewport clipping rendering // Coordinates in subrect are "native" pixels, but origin is from the extrema of screen if (this.viewportClippingEnabled && this.InheritConfig != null) { float vw = (right - left) / scale.x; float vh = (top - bottom) / scale.y; Vector4 sr = new Vector4((int)this.viewportRegion.x, (int)this.viewportRegion.y, (int)this.viewportRegion.z, (int)this.viewportRegion.w); usingLegacyViewportClipping = true; float viewportLeft = -offset.x / pixelWidth + sr.x / vw; float viewportBottom = -offset.y / pixelHeight + sr.y / vh; float viewportWidth = sr.z / vw; float viewportHeight = sr.w / vh; if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) { viewportLeft += (pixelWidth - settings.nativeResolutionWidth * scale.x) / pixelWidth / 2.0f; viewportBottom += (pixelHeight - settings.nativeResolutionHeight * scale.y) / pixelHeight / 2.0f; } Rect r = new Rect( viewportLeft, viewportBottom, viewportWidth, viewportHeight ); if (UnityCamera.rect.x != viewportLeft || UnityCamera.rect.y != viewportBottom || UnityCamera.rect.width != viewportWidth || UnityCamera.rect.height != viewportHeight) { UnityCamera.rect = r; } float maxWidth = Mathf.Min( 1.0f - r.x, r.width ); float maxHeight = Mathf.Min( 1.0f - r.y, r.height ); float rectOffsetX = sr.x * scale.x - offset.x; float rectOffsetY = sr.y * scale.y - offset.y; if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) { rectOffsetX -= settings.nativeResolutionWidth * 0.5f * scale.x; rectOffsetY -= settings.nativeResolutionHeight * 0.5f * scale.y; } if (r.x < 0.0f) { rectOffsetX += -r.x * pixelWidth; maxWidth = (r.x + r.width); } if (r.y < 0.0f) { rectOffsetY += -r.y * pixelHeight; maxHeight = (r.y + r.height); } left += rectOffsetX; bottom += rectOffsetY; right = pixelWidth * maxWidth + offset.x + rectOffsetX; top = pixelHeight * maxHeight + offset.y + rectOffsetY; } else { if (UnityCamera.rect != CameraSettings.rect) { UnityCamera.rect = CameraSettings.rect; } // By default the camera is orthographic, bottom left, 1 pixel per meter if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) { float w = (right - left) * 0.5f; left -= w; right -= w; float h = (top - bottom) * 0.5f; top -= h; bottom -= h; nativeResolutionOffset.Set(-nativeResolutionWidth / 2.0f, -nativeResolutionHeight / 2.0f); } } float zoomScale = 1.0f / ZoomFactor; // Only need the half texel offset on PC/D3D bool needHalfTexelOffset = (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.WindowsEditor); float halfTexel = (halfTexelOffset && needHalfTexelOffset) ? 0.5f : 0.0f; float orthoSize = settings.cameraSettings.orthographicSize; switch (settings.cameraSettings.orthographicType) { case tk2dCameraSettings.OrthographicType.OrthographicSize: orthoSize = 2.0f * settings.cameraSettings.orthographicSize / settings.nativeResolutionHeight; break; case tk2dCameraSettings.OrthographicType.PixelsPerMeter: orthoSize = 1.0f / settings.cameraSettings.orthographicPixelsPerMeter; break; } // Fixup for clipping if (!usingLegacyViewportClipping) { float clipWidth = Mathf.Min(UnityCamera.rect.width, 1.0f - UnityCamera.rect.x); float clipHeight = Mathf.Min(UnityCamera.rect.height, 1.0f - UnityCamera.rect.y); if (clipWidth > 0 && clipHeight > 0) { scale.x /= clipWidth; scale.y /= clipHeight; } } float s = orthoSize * zoomScale; screenExtents = new Rect(left * s / scale.x, bottom * s / scale.y, (right - left) * s / scale.x, (top - bottom) * s / scale.y); unscaledScreenExtents = new Rect(nativeResolutionOffset.x * s, nativeResolutionOffset.y * s, nativeResolutionWidth * s, nativeResolutionHeight * s); // Near and far clip planes are tweakable per camera, so we pull from current camera instance regardless of inherited values return OrthoOffCenter(scale, orthoSize * (left + halfTexel) * zoomScale, orthoSize * (right + halfTexel) * zoomScale, orthoSize * (bottom - halfTexel) * zoomScale, orthoSize * (top - halfTexel) * zoomScale, UnityCamera.nearClipPlane, UnityCamera.farClipPlane); } Vector2 GetScreenPixelDimensions(tk2dCamera settings) { Vector2 dimensions = new Vector2(ScreenCamera.pixelWidth, ScreenCamera.pixelHeight); #if UNITY_EDITOR // This bit here allocates memory, but only runs in the editor float gameViewPixelWidth = 0, gameViewPixelHeight = 0; float gameViewAspect = 0; settings.useGameWindowResolutionInEditor = false; if (Editor__GetGameViewSize( out gameViewPixelWidth, out gameViewPixelHeight, out gameViewAspect)) { if (gameViewPixelWidth != 0 && gameViewPixelHeight != 0) { if (!settings.useGameWindowResolutionInEditor || settings.gameWindowResolution.x != gameViewPixelWidth || settings.gameWindowResolution.y != gameViewPixelHeight) { settings.useGameWindowResolutionInEditor = true; settings.gameWindowResolution.x = gameViewPixelWidth; settings.gameWindowResolution.y = gameViewPixelHeight; } dimensions.x = settings.gameWindowResolution.x; dimensions.y = settings.gameWindowResolution.y; } } if (!settings.useGameWindowResolutionInEditor && settings.forceResolutionInEditor) { dimensions.x = settings.forceResolution.x; dimensions.y = settings.forceResolution.y; } #endif return dimensions; } private void Upgrade() { if (version != CURRENT_VERSION) { if (version == 0) { // Backwards compatibility cameraSettings.orthographicPixelsPerMeter = 1; cameraSettings.orthographicType = tk2dCameraSettings.OrthographicType.PixelsPerMeter; cameraSettings.orthographicOrigin = tk2dCameraSettings.OrthographicOrigin.BottomLeft; cameraSettings.projection = tk2dCameraSettings.ProjectionType.Orthographic; foreach (tk2dCameraResolutionOverride ovr in resolutionOverride) { ovr.Upgrade( version ); } // Mirror camera settings Camera unityCamera = camera; if (unityCamera != null) { cameraSettings.rect = unityCamera.rect; if (!unityCamera.isOrthoGraphic) { cameraSettings.projection = tk2dCameraSettings.ProjectionType.Perspective; cameraSettings.fieldOfView = unityCamera.fieldOfView * ZoomFactor; } unityCamera.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy; } } Debug.Log("tk2dCamera '" + this.name + "' - Upgraded from version " + version.ToString()); version = CURRENT_VERSION; } } /// <summary> /// Updates the camera matrix to ensure 1:1 pixel mapping /// Or however the override is set up. /// </summary> public void UpdateCameraMatrix() { Upgrade(); if (!this.viewportClippingEnabled) inst = this; Camera unityCamera = UnityCamera; tk2dCamera settings = SettingsRoot; tk2dCameraSettings inheritedCameraSettings = settings.CameraSettings; if (unityCamera.rect != cameraSettings.rect) unityCamera.rect = cameraSettings.rect; // Projection type is inherited from base camera _targetResolution = GetScreenPixelDimensions(settings); if (inheritedCameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { if (unityCamera.orthographic == true) unityCamera.orthographic = false; float fov = Mathf.Min(179.9f, inheritedCameraSettings.fieldOfView / Mathf.Max(0.001f, ZoomFactor)); if (unityCamera.fieldOfView != fov) unityCamera.fieldOfView = fov; _screenExtents.Set( -unityCamera.aspect, -1, unityCamera.aspect * 2, 2 ); _nativeScreenExtents = _screenExtents; unityCamera.ResetProjectionMatrix(); } else { if (unityCamera.orthographic == false) unityCamera.orthographic = true; // Find an override if necessary Matrix4x4 m = GetProjectionMatrixForOverride( settings, settings.CurrentResolutionOverride, _targetResolution.x, _targetResolution.y, true, out _screenExtents, out _nativeScreenExtents ); #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_1) // Windows phone? if (Application.platform == RuntimePlatform.WP8Player && (Screen.orientation == ScreenOrientation.LandscapeLeft || Screen.orientation == ScreenOrientation.LandscapeRight)) { float angle = (Screen.orientation == ScreenOrientation.LandscapeRight) ? 90.0f : -90.0f; Matrix4x4 m2 = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, angle), Vector3.one); m = m2 * m; } #endif if (unityCamera.projectionMatrix != m) { unityCamera.projectionMatrix = m; } } } }
// 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.Reflection; using Internal.Metadata.NativeFormat; using System.Threading; using Debug = System.Diagnostics.Debug; using Internal.TypeSystem; using Internal.NativeFormat; namespace Internal.TypeSystem.NativeFormat { /// <summary> /// Override of MetadataType that uses actual NativeFormat335 metadata. /// </summary> public sealed partial class NativeFormatType : MetadataType, NativeFormatMetadataUnit.IHandleObject { private static readonly LowLevelDictionary<string, TypeFlags> s_primitiveTypes = InitPrimitiveTypesDictionary(); private static LowLevelDictionary<string, TypeFlags> InitPrimitiveTypesDictionary() { LowLevelDictionary<string, TypeFlags> result = new LowLevelDictionary<string, TypeFlags>(); result.Add("Void", TypeFlags.Void); result.Add("Boolean", TypeFlags.Boolean); result.Add("Char", TypeFlags.Char); result.Add("SByte", TypeFlags.SByte); result.Add("Byte", TypeFlags.Byte); result.Add("Int16", TypeFlags.Int16); result.Add("UInt16", TypeFlags.UInt16); result.Add("Int32", TypeFlags.Int32); result.Add("UInt32", TypeFlags.UInt32); result.Add("Int64", TypeFlags.Int64); result.Add("UInt64", TypeFlags.UInt64); result.Add("IntPtr", TypeFlags.IntPtr); result.Add("UIntPtr", TypeFlags.UIntPtr); result.Add("Single", TypeFlags.Single); result.Add("Double", TypeFlags.Double); return result; } private NativeFormatModule _module; private NativeFormatMetadataUnit _metadataUnit; private TypeDefinitionHandle _handle; private TypeDefinition _typeDefinition; // Cached values private string _typeName; private string _typeNamespace; private TypeDesc[] _genericParameters; private MetadataType _baseType; private int _hashcode; internal NativeFormatType(NativeFormatMetadataUnit metadataUnit, TypeDefinitionHandle handle) { _handle = handle; _metadataUnit = metadataUnit; _typeDefinition = metadataUnit.MetadataReader.GetTypeDefinition(handle); _module = metadataUnit.GetModuleFromNamespaceDefinition(_typeDefinition.NamespaceDefinition); _baseType = this; // Not yet initialized flag #if DEBUG // Initialize name eagerly in debug builds for convenience InitializeName(); #endif } public override int GetHashCode() { if (_hashcode != 0) { return _hashcode; } int nameHash = TypeHashingAlgorithms.ComputeNameHashCode(this.GetFullName()); TypeDesc containingType = ContainingType; if (containingType == null) { _hashcode = nameHash; } else { _hashcode = TypeHashingAlgorithms.ComputeNestedTypeHashCode(containingType.GetHashCode(), nameHash); } return _hashcode; } Handle NativeFormatMetadataUnit.IHandleObject.Handle { get { return _handle; } } NativeFormatType NativeFormatMetadataUnit.IHandleObject.Container { get { return null; } } // TODO: Use stable hashcode based on the type name? // public override int GetHashCode() // { // } public override TypeSystemContext Context { get { return _module.Context; } } private void ComputeGenericParameters() { var genericParameterHandles = _typeDefinition.GenericParameters; int count = genericParameterHandles.Count; if (count > 0) { TypeDesc[] genericParameters = new TypeDesc[count]; int i = 0; foreach (var genericParameterHandle in genericParameterHandles) { genericParameters[i++] = new NativeFormatGenericParameter(_metadataUnit, genericParameterHandle); } Interlocked.CompareExchange(ref _genericParameters, genericParameters, null); } else { _genericParameters = TypeDesc.EmptyTypes; } } public override Instantiation Instantiation { get { if (_genericParameters == null) ComputeGenericParameters(); return new Instantiation(_genericParameters); } } public override ModuleDesc Module { get { return _module; } } public NativeFormatModule NativeFormatModule { get { return _module; } } public MetadataReader MetadataReader { get { return _metadataUnit.MetadataReader; } } public NativeFormatMetadataUnit MetadataUnit { get { return _metadataUnit; } } public TypeDefinitionHandle Handle { get { return _handle; } } private MetadataType InitializeBaseType() { var baseTypeHandle = _typeDefinition.BaseType; if (baseTypeHandle.IsNull(MetadataReader)) { _baseType = null; return null; } var type = _metadataUnit.GetType(baseTypeHandle) as MetadataType; if (type == null) { throw new BadImageFormatException(); } _baseType = type; return type; } public override DefType BaseType { get { if (_baseType == this) return InitializeBaseType(); return _baseType; } } public override MetadataType MetadataBaseType { get { if (_baseType == this) return InitializeBaseType(); return _baseType; } } protected override TypeFlags ComputeTypeFlags(TypeFlags mask) { TypeFlags flags = 0; if ((mask & TypeFlags.CategoryMask) != 0 && (flags & TypeFlags.CategoryMask) == 0) { TypeDesc baseType = this.BaseType; if (baseType != null && baseType.IsWellKnownType(WellKnownType.ValueType) && !this.IsWellKnownType(WellKnownType.Enum)) { TypeFlags categoryFlags; if (!TryGetCategoryFlagsForPrimitiveType(out categoryFlags)) { categoryFlags = TypeFlags.ValueType; } flags |= categoryFlags; } else if (baseType != null && baseType.IsWellKnownType(WellKnownType.Enum)) { flags |= TypeFlags.Enum; } else { if ((_typeDefinition.Flags & TypeAttributes.Interface) != 0) flags |= TypeFlags.Interface; else flags |= TypeFlags.Class; } // All other cases are handled during TypeSystemContext intitialization } if ((mask & TypeFlags.HasGenericVarianceComputed) != 0 && (flags & TypeFlags.HasGenericVarianceComputed) == 0) { flags |= TypeFlags.HasGenericVarianceComputed; foreach (GenericParameterDesc genericParam in Instantiation) { if (genericParam.Variance != GenericVariance.None) { flags |= TypeFlags.HasGenericVariance; break; } } } if ((mask & TypeFlags.HasFinalizerComputed) != 0) { flags |= TypeFlags.HasFinalizerComputed; if (GetFinalizer() != null) flags |= TypeFlags.HasFinalizer; } if ((mask & TypeFlags.AttributeCacheComputed) != 0) { flags |= TypeFlags.AttributeCacheComputed; if (IsValueType && HasCustomAttribute("System.Runtime.CompilerServices", "IsByRefLikeAttribute")) flags |= TypeFlags.IsByRefLike; } return flags; } private bool TryGetCategoryFlagsForPrimitiveType(out TypeFlags categoryFlags) { categoryFlags = 0; if (_module != _metadataUnit.Context.SystemModule) { // Primitive types reside in the system module return false; } NamespaceDefinition namespaceDef = MetadataReader.GetNamespaceDefinition(_typeDefinition.NamespaceDefinition); if (namespaceDef.ParentScopeOrNamespace.HandleType != HandleType.NamespaceDefinition) { // Primitive types are in the System namespace the parent of which is the root namespace return false; } if (!namespaceDef.Name.StringEquals("System", MetadataReader)) { // Namespace name must be 'System' return false; } NamespaceDefinitionHandle parentNamespaceDefHandle = namespaceDef.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(MetadataReader); NamespaceDefinition parentDef = MetadataReader.GetNamespaceDefinition(parentNamespaceDefHandle); if (parentDef.ParentScopeOrNamespace.HandleType != HandleType.ScopeDefinition) { // The root parent namespace should have scope (assembly) handle as its parent return false; } return s_primitiveTypes.TryGetValue(Name, out categoryFlags); } private string InitializeName() { var metadataReader = this.MetadataReader; _typeName = metadataReader.GetString(_typeDefinition.Name); return _typeName; } public override string Name { get { if (_typeName == null) return InitializeName(); return _typeName; } } private string InitializeNamespace() { if (ContainingType == null) { var metadataReader = this.MetadataReader; _typeNamespace = metadataReader.GetNamespaceName(_typeDefinition.NamespaceDefinition); return _typeNamespace; } else { _typeNamespace = ""; return _typeNamespace; } } public override string Namespace { get { if (_typeNamespace == null) return InitializeNamespace(); return _typeNamespace; } } public override IEnumerable<MethodDesc> GetMethods() { foreach (var handle in _typeDefinition.Methods) { yield return (MethodDesc)_metadataUnit.GetMethod(handle, this); } } public override MethodDesc GetMethod(string name, MethodSignature signature) { var metadataReader = this.MetadataReader; foreach (var handle in _typeDefinition.Methods) { if (metadataReader.GetMethod(handle).Name.StringEquals(name, metadataReader)) { MethodDesc method = (MethodDesc)_metadataUnit.GetMethod(handle, this); if (signature == null || signature.Equals(method.Signature)) return method; } } return null; } public override MethodDesc GetStaticConstructor() { var metadataReader = this.MetadataReader; foreach (var handle in _typeDefinition.Methods) { var methodDefinition = metadataReader.GetMethod(handle); if (methodDefinition.Flags.IsRuntimeSpecialName() && methodDefinition.Name.StringEquals(".cctor", metadataReader)) { MethodDesc method = (MethodDesc)_metadataUnit.GetMethod(handle, this); return method; } } return null; } public override MethodDesc GetDefaultConstructor() { if (IsAbstract) return null; MetadataReader metadataReader = this.MetadataReader; foreach (var handle in _typeDefinition.Methods) { var methodDefinition = metadataReader.GetMethod(handle); MethodAttributes attributes = methodDefinition.Flags; if (attributes.IsRuntimeSpecialName() && attributes.IsPublic() && methodDefinition.Name.StringEquals(".ctor", metadataReader)) { MethodDesc method = (MethodDesc)_metadataUnit.GetMethod(handle, this); if (method.Signature.Length != 0) continue; return method; } } return null; } public override MethodDesc GetFinalizer() { // System.Object defines Finalize but doesn't use it, so we can determine that a type has a Finalizer // by checking for a virtual method override that lands anywhere other than Object in the inheritance // chain. if (!HasBaseType) return null; TypeDesc objectType = Context.GetWellKnownType(WellKnownType.Object); MethodDesc decl = objectType.GetMethod("Finalize", null); if (decl != null) { MethodDesc impl = this.FindVirtualFunctionTargetMethodOnObjectType(decl); if (impl == null) { // TODO: invalid input: the type doesn't derive from our System.Object ThrowHelper.ThrowTypeLoadException(this); } if (impl.OwningType != objectType) { return impl; } return null; } ThrowHelper.ThrowTypeLoadException(objectType); return null; } public override IEnumerable<FieldDesc> GetFields() { foreach (var handle in _typeDefinition.Fields) { yield return _metadataUnit.GetField(handle, this); } } public override FieldDesc GetField(string name) { var metadataReader = this.MetadataReader; foreach (var handle in _typeDefinition.Fields) { if (metadataReader.GetField(handle).Name.StringEquals(name, metadataReader)) { return _metadataUnit.GetField(handle, this); } } return null; } public override IEnumerable<MetadataType> GetNestedTypes() { foreach (var handle in _typeDefinition.NestedTypes) { yield return (MetadataType)_metadataUnit.GetType(handle); } } public override MetadataType GetNestedType(string name) { var metadataReader = this.MetadataReader; foreach (var handle in _typeDefinition.NestedTypes) { if (metadataReader.GetTypeDefinition(handle).Name.StringEquals(name, metadataReader)) return (MetadataType)_metadataUnit.GetType(handle); } return null; } public TypeAttributes Attributes { get { return _typeDefinition.Flags; } } // // ContainingType of nested type // public override DefType ContainingType { get { var handle = _typeDefinition.EnclosingType; if (handle.IsNull(MetadataReader)) return null; return (DefType)_metadataUnit.GetType(handle); } } public override bool HasCustomAttribute(string attributeNamespace, string attributeName) { return MetadataReader.HasCustomAttribute(_typeDefinition.CustomAttributes, attributeNamespace, attributeName); } public override ClassLayoutMetadata GetClassLayout() { ClassLayoutMetadata result; result.PackingSize = checked((int)_typeDefinition.PackingSize); result.Size = checked((int)_typeDefinition.Size); // Skip reading field offsets if this is not explicit layout if (IsExplicitLayout) { var fieldDefinitionHandles = _typeDefinition.Fields; var numInstanceFields = 0; foreach (var handle in fieldDefinitionHandles) { var fieldDefinition = MetadataReader.GetField(handle); if ((fieldDefinition.Flags & FieldAttributes.Static) != 0) continue; numInstanceFields++; } result.Offsets = new FieldAndOffset[numInstanceFields]; int index = 0; foreach (var handle in fieldDefinitionHandles) { var fieldDefinition = MetadataReader.GetField(handle); if ((fieldDefinition.Flags & FieldAttributes.Static) != 0) continue; // Note: GetOffset() returns -1 when offset was not set in the metadata int fieldOffsetInMetadata = (int)fieldDefinition.Offset; LayoutInt fieldOffset = fieldOffsetInMetadata == -1 ? FieldAndOffset.InvalidOffset : new LayoutInt(fieldOffsetInMetadata); result.Offsets[index] = new FieldAndOffset(_metadataUnit.GetField(handle, this), fieldOffset); index++; } } else result.Offsets = null; return result; } public override bool IsExplicitLayout { get { return (_typeDefinition.Flags & TypeAttributes.ExplicitLayout) != 0; } } public override bool IsSequentialLayout { get { return (_typeDefinition.Flags & TypeAttributes.SequentialLayout) != 0; } } public override bool IsBeforeFieldInit { get { return (_typeDefinition.Flags & TypeAttributes.BeforeFieldInit) != 0; } } public override bool IsSealed { get { return (_typeDefinition.Flags & TypeAttributes.Sealed) != 0; } } public override bool IsAbstract { get { return (_typeDefinition.Flags & TypeAttributes.Abstract) != 0; } } } }
#if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFAB_STATIC_API using PlayFab.ProfilesModels; using PlayFab.Internal; #pragma warning disable 0649 using System; // This is required for the Obsolete Attribute flag // which is not always present in all API's #pragma warning restore 0649 using System.Collections.Generic; using System.Threading.Tasks; namespace PlayFab { /// <summary> /// All PlayFab entities have profiles, which hold top-level properties about the entity. These APIs give you the tools /// needed to manage entity profiles. /// </summary> public static class PlayFabProfilesAPI { /// <summary> /// Verify entity login. /// </summary> public static bool IsEntityLoggedIn() { return PlayFabSettings.staticPlayer.IsEntityLoggedIn(); } /// <summary> /// Clear the Client SessionToken which allows this Client to call API calls requiring login. /// A new/fresh login will be required after calling this. /// </summary> public static void ForgetAllCredentials() { PlayFabSettings.staticPlayer.ForgetAllCredentials(); } /// <summary> /// Gets the global title access policy /// </summary> public static async Task<PlayFabResult<GetGlobalPolicyResponse>> GetGlobalPolicyAsync(GetGlobalPolicyRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Profile/GetGlobalPolicy", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetGlobalPolicyResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetGlobalPolicyResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetGlobalPolicyResponse> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the entity's profile. /// </summary> public static async Task<PlayFabResult<GetEntityProfileResponse>> GetProfileAsync(GetEntityProfileRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Profile/GetProfile", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetEntityProfileResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetEntityProfileResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetEntityProfileResponse> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the entity's profile. /// </summary> public static async Task<PlayFabResult<GetEntityProfilesResponse>> GetProfilesAsync(GetEntityProfilesRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Profile/GetProfiles", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetEntityProfilesResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetEntityProfilesResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetEntityProfilesResponse> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the title player accounts associated with the given master player account. /// </summary> public static async Task<PlayFabResult<GetTitlePlayersFromMasterPlayerAccountIdsResponse>> GetTitlePlayersFromMasterPlayerAccountIdsAsync(GetTitlePlayersFromMasterPlayerAccountIdsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Profile/GetTitlePlayersFromMasterPlayerAccountIds", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetTitlePlayersFromMasterPlayerAccountIdsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetTitlePlayersFromMasterPlayerAccountIdsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetTitlePlayersFromMasterPlayerAccountIdsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Sets the global title access policy /// </summary> public static async Task<PlayFabResult<SetGlobalPolicyResponse>> SetGlobalPolicyAsync(SetGlobalPolicyRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Profile/SetGlobalPolicy", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<SetGlobalPolicyResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<SetGlobalPolicyResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<SetGlobalPolicyResponse> { Result = result, CustomData = customData }; } /// <summary> /// Updates the entity's language. The precedence hierarchy for communication to the player is Title Player Account /// language, Master Player Account language, and then title default language if the first two aren't set or supported. /// </summary> public static async Task<PlayFabResult<SetProfileLanguageResponse>> SetProfileLanguageAsync(SetProfileLanguageRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Profile/SetProfileLanguage", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<SetProfileLanguageResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<SetProfileLanguageResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<SetProfileLanguageResponse> { Result = result, CustomData = customData }; } /// <summary> /// Sets the profiles access policy /// </summary> public static async Task<PlayFabResult<SetEntityProfilePolicyResponse>> SetProfilePolicyAsync(SetEntityProfilePolicyRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Profile/SetProfilePolicy", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<SetEntityProfilePolicyResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<SetEntityProfilePolicyResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<SetEntityProfilePolicyResponse> { Result = result, CustomData = customData }; } } } #endif
//Copyright (c) ServiceStack, Inc. All Rights Reserved. //License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt using System; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using ServiceStack.Text.Common; namespace ServiceStack.Text.Json { public struct JsonTypeSerializer : ITypeSerializer { public static ITypeSerializer Instance = new JsonTypeSerializer(); public ObjectDeserializerDelegate ObjectDeserializer { get; set; } public bool IncludeNullValues => JsConfig.IncludeNullValues; public bool IncludeNullValuesInDictionaries => JsConfig.IncludeNullValuesInDictionaries; public string TypeAttrInObject => JsConfig.JsonTypeAttrInObject; internal static string GetTypeAttrInObject(string typeAttr) => $"{{\"{typeAttr}\":"; public WriteObjectDelegate GetWriteFn<T>() => JsonWriter<T>.WriteFn(); public WriteObjectDelegate GetWriteFn(Type type) => JsonWriter.GetWriteFn(type); public TypeInfo GetTypeInfo(Type type) => JsonWriter.GetTypeInfo(type); /// <summary> /// Shortcut escape when we're sure value doesn't contain any escaped chars /// </summary> /// <param name="writer"></param> /// <param name="value"></param> public void WriteRawString(TextWriter writer, string value) { writer.Write(JsWriter.QuoteChar); writer.Write(value); writer.Write(JsWriter.QuoteChar); } public void WritePropertyName(TextWriter writer, string value) { if (JsState.WritingKeyCount > 0) { writer.Write(JsWriter.EscapedQuoteString); writer.Write(value); writer.Write(JsWriter.EscapedQuoteString); } else { WriteRawString(writer, value); } } public void WriteString(TextWriter writer, string value) { JsonUtils.WriteString(writer, value); } public void WriteBuiltIn(TextWriter writer, object value) { if (JsState.WritingKeyCount > 0 && !JsState.IsWritingValue) writer.Write(JsonUtils.QuoteChar); WriteRawString(writer, value.ToString()); if (JsState.WritingKeyCount > 0 && !JsState.IsWritingValue) writer.Write(JsonUtils.QuoteChar); } public void WriteObjectString(TextWriter writer, object value) { JsonUtils.WriteString(writer, value?.ToString()); } public void WriteFormattableObjectString(TextWriter writer, object value) { var formattable = value as IFormattable; JsonUtils.WriteString(writer, formattable?.ToString(null, CultureInfo.InvariantCulture)); } public void WriteException(TextWriter writer, object value) { WriteString(writer, ((Exception)value).Message); } public void WriteDateTime(TextWriter writer, object oDateTime) { var dateTime = (DateTime)oDateTime; switch (JsConfig.DateHandler) { case DateHandler.UnixTime: writer.Write(dateTime.ToUnixTime()); return; case DateHandler.UnixTimeMs: writer.Write(dateTime.ToUnixTimeMs()); return; } writer.Write(JsWriter.QuoteString); DateTimeSerializer.WriteWcfJsonDate(writer, dateTime); writer.Write(JsWriter.QuoteString); } public void WriteNullableDateTime(TextWriter writer, object dateTime) { if (dateTime == null) writer.Write(JsonUtils.Null); else WriteDateTime(writer, dateTime); } public void WriteDateTimeOffset(TextWriter writer, object oDateTimeOffset) { writer.Write(JsWriter.QuoteString); DateTimeSerializer.WriteWcfJsonDateTimeOffset(writer, (DateTimeOffset)oDateTimeOffset); writer.Write(JsWriter.QuoteString); } public void WriteNullableDateTimeOffset(TextWriter writer, object dateTimeOffset) { if (dateTimeOffset == null) writer.Write(JsonUtils.Null); else WriteDateTimeOffset(writer, dateTimeOffset); } public void WriteTimeSpan(TextWriter writer, object oTimeSpan) { var stringValue = JsConfig.TimeSpanHandler == TimeSpanHandler.StandardFormat ? oTimeSpan.ToString() : DateTimeSerializer.ToXsdTimeSpanString((TimeSpan)oTimeSpan); WriteRawString(writer, stringValue); } public void WriteNullableTimeSpan(TextWriter writer, object oTimeSpan) { if (oTimeSpan == null) return; WriteTimeSpan(writer, ((TimeSpan?)oTimeSpan).Value); } public void WriteGuid(TextWriter writer, object oValue) { WriteRawString(writer, ((Guid)oValue).ToString("N")); } public void WriteNullableGuid(TextWriter writer, object oValue) { if (oValue == null) return; WriteRawString(writer, ((Guid)oValue).ToString("N")); } public void WriteBytes(TextWriter writer, object oByteValue) { if (oByteValue == null) return; WriteRawString(writer, Convert.ToBase64String((byte[])oByteValue)); } public void WriteChar(TextWriter writer, object charValue) { if (charValue == null) writer.Write(JsonUtils.Null); else WriteString(writer, ((char)charValue).ToString()); } public void WriteByte(TextWriter writer, object byteValue) { if (byteValue == null) writer.Write(JsonUtils.Null); else writer.Write((byte)byteValue); } public void WriteSByte(TextWriter writer, object sbyteValue) { if (sbyteValue == null) writer.Write(JsonUtils.Null); else writer.Write((sbyte)sbyteValue); } public void WriteInt16(TextWriter writer, object intValue) { if (intValue == null) writer.Write(JsonUtils.Null); else writer.Write((short)intValue); } public void WriteUInt16(TextWriter writer, object intValue) { if (intValue == null) writer.Write(JsonUtils.Null); else writer.Write((ushort)intValue); } public void WriteInt32(TextWriter writer, object intValue) { if (intValue == null) writer.Write(JsonUtils.Null); else writer.Write((int)intValue); } public void WriteUInt32(TextWriter writer, object uintValue) { if (uintValue == null) writer.Write(JsonUtils.Null); else writer.Write((uint)uintValue); } public void WriteInt64(TextWriter writer, object integerValue) { if (integerValue == null) writer.Write(JsonUtils.Null); else writer.Write((long)integerValue); } public void WriteUInt64(TextWriter writer, object ulongValue) { if (ulongValue == null) { writer.Write(JsonUtils.Null); } else writer.Write((ulong)ulongValue); } public void WriteBool(TextWriter writer, object boolValue) { if (boolValue == null) writer.Write(JsonUtils.Null); else writer.Write(((bool)boolValue) ? JsonUtils.True : JsonUtils.False); } public void WriteFloat(TextWriter writer, object floatValue) { if (floatValue == null) writer.Write(JsonUtils.Null); else { var floatVal = (float)floatValue; if (Equals(floatVal, float.MaxValue) || Equals(floatVal, float.MinValue)) writer.Write(floatVal.ToString("r", CultureInfo.InvariantCulture)); else writer.Write(floatVal.ToString("r", CultureInfo.InvariantCulture)); } } public void WriteDouble(TextWriter writer, object doubleValue) { if (doubleValue == null) writer.Write(JsonUtils.Null); else { var doubleVal = (double)doubleValue; if (Equals(doubleVal, double.MaxValue) || Equals(doubleVal, double.MinValue)) writer.Write(doubleVal.ToString("r", CultureInfo.InvariantCulture)); else writer.Write(doubleVal.ToString(CultureInfo.InvariantCulture)); } } public void WriteDecimal(TextWriter writer, object decimalValue) { if (decimalValue == null) writer.Write(JsonUtils.Null); else writer.Write(((decimal)decimalValue).ToString(CultureInfo.InvariantCulture)); } public void WriteEnum(TextWriter writer, object enumValue) { if (enumValue == null) return; var serializedValue = CachedTypeInfo.Get(enumValue.GetType()).EnumInfo.GetSerializedValue(enumValue); if (serializedValue is string strEnum) WriteRawString(writer, strEnum); else JsWriter.WriteEnumFlags(writer, enumValue); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ParseStringDelegate GetParseFn<T>() { return JsonReader.Instance.GetParseFn<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ParseStringSpanDelegate GetParseStringSpanFn<T>() { return JsonReader.Instance.GetParseStringSpanFn<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ParseStringDelegate GetParseFn(Type type) { return JsonReader.GetParseFn(type); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ParseStringSpanDelegate GetParseStringSpanFn(Type type) { return JsonReader.GetParseStringSpanFn(type); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public string ParseRawString(string value) { return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public string ParseString(ReadOnlySpan<char> value) { return value.IsNullOrEmpty() ? null : ParseRawString(value.ToString()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public string ParseString(string value) { return string.IsNullOrEmpty(value) ? value : ParseRawString(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsEmptyMap(ReadOnlySpan<char> value, int i = 1) { for (; i < value.Length; i++) { var c = value[i]; if (!JsonUtils.IsWhiteSpace(c)) break; } //Whitespace inline if (value.Length == i) return true; return value[i++] == JsWriter.MapEndChar; } internal static ReadOnlySpan<char> ParseString(ReadOnlySpan<char> json, ref int index) { var jsonLength = json.Length; if (json[index] != JsonUtils.QuoteChar) throw new Exception("Invalid unquoted string starting with: " + json.SafeSubstring(50).ToString()); var startIndex = ++index; do { var c = json[index]; if (c == JsonUtils.QuoteChar) break; if (c == JsonUtils.EscapeChar) { index++; if (json[index] == 'u') index += 4; } } while (index++ < jsonLength); if (index == jsonLength) throw new Exception("Invalid unquoted string ending with: " + json.SafeSubstring(json.Length - 50, 50).ToString()); index++; var str = json.Slice(startIndex, Math.Min(index, jsonLength) - startIndex - 1); if (str.Length == 0) return TypeConstants.EmptyStringSpan; return str; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public string UnescapeString(string value) { var i = 0; return UnescapeJsonString(value, ref i); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<char> UnescapeString(ReadOnlySpan<char> value) { var i = 0; return UnescapeJsonString(value, ref i); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public object UnescapeStringAsObject(ReadOnlySpan<char> value) { var ignore = 0; return UnescapeJsString(value, JsonUtils.QuoteChar, removeQuotes: true, ref ignore).Value(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public string UnescapeSafeString(string value) => UnescapeSafeString(value.AsSpan()).ToString(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<char> UnescapeSafeString(ReadOnlySpan<char> value) { if (value.IsEmpty) return value; if (value[0] == JsonUtils.QuoteChar && value[value.Length - 1] == JsonUtils.QuoteChar) return value.Slice(1, value.Length - 2); return value; } static readonly char[] IsSafeJsonChars = { JsonUtils.QuoteChar, JsonUtils.EscapeChar }; internal static ReadOnlySpan<char> ParseJsonString(ReadOnlySpan<char> json, ref int index) { for (; index < json.Length; index++) { var ch = json[index]; if (!JsonUtils.IsWhiteSpace(ch)) break; } //Whitespace inline return UnescapeJsonString(json, ref index); } private static string UnescapeJsonString(string json, ref int index) { return json != null ? UnescapeJsonString(json.AsSpan(), ref index).ToString() : null; } private static ReadOnlySpan<char> UnescapeJsonString(ReadOnlySpan<char> json, ref int index) => UnescapeJsString(json, JsonUtils.QuoteChar, removeQuotes:true, ref index); public static ReadOnlySpan<char> UnescapeJsString(ReadOnlySpan<char> json, char quoteChar) { var ignore = 0; return UnescapeJsString(json, quoteChar, removeQuotes:false, ref ignore); } public static ReadOnlySpan<char> UnescapeJsString(ReadOnlySpan<char> json, char quoteChar, bool removeQuotes, ref int index) { if (json.IsNullOrEmpty()) return json; var jsonLength = json.Length; var buffer = json; var firstChar = buffer[index]; if (firstChar == quoteChar) { index++; //MicroOp: See if we can short-circuit evaluation (to avoid StringBuilder) var jsonAtIndex = json.Slice(index); var strEndPos = jsonAtIndex.IndexOfAny(IsSafeJsonChars); if (strEndPos == -1) return jsonAtIndex.Slice(0, jsonLength); if (jsonAtIndex[strEndPos] == quoteChar) { var potentialValue = jsonAtIndex.Slice(0, strEndPos); index += strEndPos + 1; return potentialValue.Length > 0 ? potentialValue : TypeConstants.EmptyStringSpan; } } else { var i = index; var end = jsonLength; while (i < end) { var c = buffer[i]; if (c == quoteChar || c == JsonUtils.EscapeChar) break; i++; } if (i == end) return buffer.Slice(index, jsonLength - index); } return Unescape(json, removeQuotes:removeQuotes, quoteChar:quoteChar); } public static string Unescape(string input) => Unescape(input, true); public static string Unescape(string input, bool removeQuotes) => Unescape(input.AsSpan(), removeQuotes).ToString(); public static ReadOnlySpan<char> Unescape(ReadOnlySpan<char> input) => Unescape(input, true); public static ReadOnlySpan<char> Unescape(ReadOnlySpan<char> input, bool removeQuotes) => Unescape(input, removeQuotes, JsonUtils.QuoteChar); public static ReadOnlySpan<char> Unescape(ReadOnlySpan<char> input, bool removeQuotes, char quoteChar) { var length = input.Length; int start = 0; int count = 0; var output = StringBuilderThreadStatic.Allocate(); for (; count < length;) { var c = input[count]; if (removeQuotes) { if (c == quoteChar) { if (start != count) { output.Append(input.Slice(start, count - start)); } count++; start = count; continue; } } if (c == JsonUtils.EscapeChar) { if (start != count) { output.Append(input.Slice(start, count - start)); } start = count; count++; if (count >= length) continue; //we will always be parsing an escaped char here c = input[count]; switch (c) { case 'a': output.Append('\a'); count++; break; case 'b': output.Append('\b'); count++; break; case 'f': output.Append('\f'); count++; break; case 'n': output.Append('\n'); count++; break; case 'r': output.Append('\r'); count++; break; case 'v': output.Append('\v'); count++; break; case 't': output.Append('\t'); count++; break; case 'u': if (count + 4 < length) { var unicodeString = input.Slice(count + 1, 4); var unicodeIntVal = MemoryProvider.Instance.ParseUInt32(unicodeString, NumberStyles.HexNumber); output.Append(ConvertFromUtf32((int)unicodeIntVal)); count += 5; } else { output.Append(c); } break; case 'x': if (count + 4 < length) { var unicodeString = input.Slice(count + 1, 4); var unicodeIntVal = MemoryProvider.Instance.ParseUInt32(unicodeString, NumberStyles.HexNumber); output.Append(ConvertFromUtf32((int)unicodeIntVal)); count += 5; } else if (count + 2 < length) { var unicodeString = input.Slice(count + 1, 2); var unicodeIntVal = MemoryProvider.Instance.ParseUInt32(unicodeString, NumberStyles.HexNumber); output.Append(ConvertFromUtf32((int)unicodeIntVal)); count += 3; } else { output.Append(input.Slice(start, count - start)); } break; default: output.Append(c); count++; break; } start = count; } else { count++; } } output.Append(input.Slice(start, length - start)); return StringBuilderThreadStatic.ReturnAndFree(output).AsSpan(); } /// <summary> /// Given a character as utf32, returns the equivalent string provided that the character /// is legal json. /// </summary> /// <param name="utf32"></param> /// <returns></returns> public static string ConvertFromUtf32(int utf32) { if (utf32 < 0 || utf32 > 0x10FFFF) throw new ArgumentOutOfRangeException(nameof(utf32), "The argument must be from 0 to 0x10FFFF."); if (utf32 < 0x10000) return new string((char)utf32, 1); utf32 -= 0x10000; return new string(new[] {(char) ((utf32 >> 10) + 0xD800), (char) (utf32 % 0x0400 + 0xDC00)}); } public string EatTypeValue(string value, ref int i) { return EatValue(value, ref i); } public ReadOnlySpan<char> EatTypeValue(ReadOnlySpan<char> value, ref int i) { return EatValue(value, ref i); } public bool EatMapStartChar(string value, ref int i) => EatMapStartChar(value.AsSpan(), ref i); public bool EatMapStartChar(ReadOnlySpan<char> value, ref int i) { for (; i < value.Length; i++) { var c = value[i]; if (!JsonUtils.IsWhiteSpace(c)) break; } //Whitespace inline return value[i++] == JsWriter.MapStartChar; } public string EatMapKey(string value, ref int i) => EatMapKey(value.AsSpan(), ref i).ToString(); public ReadOnlySpan<char> EatMapKey(ReadOnlySpan<char> value, ref int i) { var valueLength = value.Length; for (; i < value.Length; i++) { var c = value[i]; if (!JsonUtils.IsWhiteSpace(c)) break; } //Whitespace inline var tokenStartPos = i; var valueChar = value[i]; switch (valueChar) { //If we are at the end, return. case JsWriter.ItemSeperator: case JsWriter.MapEndChar: return default(ReadOnlySpan<char>); //Is Within Quotes, i.e. "..." case JsWriter.QuoteChar: return ParseString(value, ref i); } //Is Value while (++i < valueLength) { valueChar = value[i]; if (valueChar == JsWriter.ItemSeperator //If it doesn't have quotes it's either a keyword or number so also has a ws boundary || (JsonUtils.IsWhiteSpace(valueChar)) ) { break; } } return value.Slice(tokenStartPos, i - tokenStartPos); } public bool EatMapKeySeperator(string value, ref int i) => EatMapKeySeperator(value.AsSpan(), ref i); public bool EatMapKeySeperator(ReadOnlySpan<char> value, ref int i) { for (; i < value.Length; i++) { var c = value[i]; if (!JsonUtils.IsWhiteSpace(c)) break; } //Whitespace inline if (value.Length == i) return false; return value[i++] == JsWriter.MapKeySeperator; } public bool EatItemSeperatorOrMapEndChar(string value, ref int i) { return EatItemSeperatorOrMapEndChar(value.AsSpan(), ref i); } public bool EatItemSeperatorOrMapEndChar(ReadOnlySpan<char> value, ref int i) { for (; i < value.Length; i++) { var c = value[i]; if (!JsonUtils.IsWhiteSpace(c)) break; } //Whitespace inline if (i == value.Length) return false; var success = value[i] == JsWriter.ItemSeperator || value[i] == JsWriter.MapEndChar; if (success) { i++; for (; i < value.Length; i++) { var c = value[i]; if (!JsonUtils.IsWhiteSpace(c)) break; } //Whitespace inline } else if (Env.StrictMode) throw new Exception( $"Expected '{JsWriter.ItemSeperator}' or '{JsWriter.MapEndChar}'"); return success; } public void EatWhitespace(ReadOnlySpan<char> value, ref int i) { for (; i < value.Length; i++) { var c = value[i]; if (!JsonUtils.IsWhiteSpace(c)) break; } //Whitespace inline } public void EatWhitespace(string value, ref int i) { for (; i < value.Length; i++) { var c = value[i]; if (!JsonUtils.IsWhiteSpace(c)) break; } //Whitespace inline } public string EatValue(string value, ref int i) { return EatValue(value.AsSpan(), ref i).ToString(); } public ReadOnlySpan<char> EatValue(ReadOnlySpan<char> value, ref int i) { var buf = value; var valueLength = value.Length; if (i == valueLength) return default; while (i < valueLength && JsonUtils.IsWhiteSpace(buf[i])) i++; //Whitespace inline if (i == valueLength) return default; var tokenStartPos = i; var valueChar = buf[i]; var withinQuotes = false; var endsToEat = 1; switch (valueChar) { //If we are at the end, return. case JsWriter.ItemSeperator: case JsWriter.MapEndChar: return default; //Is Within Quotes, i.e. "..." case JsWriter.QuoteChar: return ParseString(value, ref i); //Is Type/Map, i.e. {...} case JsWriter.MapStartChar: while (++i < valueLength) { valueChar = buf[i]; if (valueChar == JsonUtils.EscapeChar) { i++; continue; } if (valueChar == JsWriter.QuoteChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.MapStartChar) endsToEat++; if (valueChar == JsWriter.MapEndChar && --endsToEat == 0) { i++; break; } } return value.Slice(tokenStartPos, i - tokenStartPos); //Is List, i.e. [...] case JsWriter.ListStartChar: while (++i < valueLength) { valueChar = buf[i]; if (valueChar == JsonUtils.EscapeChar) { i++; continue; } if (valueChar == JsWriter.QuoteChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.ListStartChar) endsToEat++; if (valueChar == JsWriter.ListEndChar && --endsToEat == 0) { i++; break; } } return value.Slice(tokenStartPos, i - tokenStartPos); } //Is Value while (++i < valueLength) { valueChar = buf[i]; if (valueChar == JsWriter.ItemSeperator || valueChar == JsWriter.MapEndChar //If it doesn't have quotes it's either a keyword or number so also has a ws boundary || JsonUtils.IsWhiteSpace(valueChar) ) { break; } } var strValue = value.Slice(tokenStartPos, i - tokenStartPos); return strValue.Equals(JsonUtils.Null.AsSpan(), StringComparison.Ordinal) ? default : strValue; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using gView.Framework.UI; using gView.Framework.Carto; using gView.Framework.Data; using gView.Framework.system; using gView.Explorer.UI; namespace gView.Framework.UI.Controls { [gView.Framework.system.RegisterPlugIn("3143FA90-587B-4cd0-B508-1BE88882E6B3")] public partial class PreviewControl : UserControl, IExplorerTabPage { private IExplorerObject _exObject = null; private ToolButton _activeToolButton; private MapDocument _mapDocument; private IMap _map; private List<ITool> _tools = new List<ITool>(); public PreviewControl() { InitializeComponent(); } #region IExplorerTabPage Members public new Control Control { get { return this; } } public void OnCreate(object hook) { if (hook is IGUIApplication) { _mapDocument = new MapDocument(new ExplorerMapApplication((IGUIApplication)hook, this, mapView1)); _map = new Map(); _map.Display.refScale = 0; _map.DrawingLayer += new DrawingLayerEvent(DrawingLayer); _mapDocument.AddMap(_map); _mapDocument.FocusMap = _map; PlugInManager compMan = new PlugInManager(); ITool zoomin = compMan.CreateInstance(KnownObjects.Tools_DynamicZoomIn) as ITool; ITool zoomout = compMan.CreateInstance(KnownObjects.Tools_DynamicZoomOut) as ITool; ITool smartNav = compMan.CreateInstance(KnownObjects.Tools_SmartNavigation) as ITool; ITool pan = compMan.CreateInstance(KnownObjects.Tools_Pan) as ITool; //ITool zoomextent = compMan.CreateInstance(KnownObjects.Tools_Zoom2Extent) as ITool; //ITool toc = compMan.CreateInstance(KnownObjects.Tools_TOC) as ITool; ITool identify = compMan.CreateInstance(KnownObjects.Tools_Identify) as ITool; ITool queryCombo = compMan.CreateInstance(KnownObjects.Tools_QueryThemeCombo) as ITool; if (zoomin != null) zoomin.OnCreate(_mapDocument); if (zoomout != null) zoomout.OnCreate(_mapDocument); if (smartNav != null) smartNav.OnCreate(_mapDocument); if (pan != null) pan.OnCreate(_mapDocument); if (identify != null) { identify.OnCreate(_mapDocument); identify.OnCreate(this); } if (queryCombo != null) queryCombo.OnCreate(_mapDocument); //if (zoomextent != null) zoomextent.OnCreate(_mapDocument); //if (toc != null) toc.OnCreate(_mapDocument); if (zoomin != null) toolStrip.Items.Add(new ToolButton(zoomin)); if (zoomout != null) toolStrip.Items.Add(new ToolButton(zoomout)); if (smartNav != null) toolStrip.Items.Add(_activeToolButton = new ToolButton(smartNav)); if (pan != null) toolStrip.Items.Add(new ToolButton(pan)); //if(zoomextent!=null) toolStrip.Items.Add(new ToolButton(zoomextent)); //if(toc!=null) toolStrip.Items.Add(new ToolButton(toc)); if (identify != null) toolStrip.Items.Add(new ToolButton(identify)); if (queryCombo is IToolItem) toolStrip.Items.Add(((IToolItem)queryCombo).ToolItem); if (zoomin != null) _tools.Add(zoomin); if (zoomout != null) _tools.Add(zoomout); if (smartNav != null) _tools.Add(smartNav); if (pan != null) _tools.Add(pan); //if (zoomextent != null) _tools.Add(zoomextent); //if (toc != null) _tools.Add(toc); if (identify != null) _tools.Add(identify); if (queryCombo != null) _tools.Add(queryCombo); _activeToolButton.Checked = true; mapView1.Map = _map; _map.NewBitmap += new NewBitmapEvent(mapView1.NewBitmapCreated); _map.DoRefreshMapView += new DoRefreshMapViewEvent(mapView1.MakeMapViewRefresh); mapView1.Tool = _activeToolButton.Tool; } } public void OnShow() { if (this.InvokeRequired) { this.Invoke(new MethodInvoker(() => { OnShow(); })); } else { mapView1.RefreshMap(DrawPhase.Geography); } } public void OnHide() { if (this.InvokeRequired) { this.Invoke(new MethodInvoker(() => { OnHide(); })); } else { mapView1.CancelDrawing(DrawPhase.All); } } private void InkokeSetExplorerObject() { if (this.InvokeRequired) { this.Invoke(new MethodInvoker(() => { InkokeSetExplorerObject(); })); } else { mapView1.CancelDrawing(DrawPhase.All); foreach (IDatasetElement element in _map.MapElements) { _map.RemoveLayer(element as ILayer); } if (_exObject != null) { if (_exObject.Object is IFeatureClass && ((IFeatureClass)_exObject.Object).Envelope != null) { mapView1.Map = _map; _map.AddLayer(LayerFactory.Create(_exObject.Object as IClass)); _map.Display.Limit = ((IFeatureClass)_exObject.Object).Envelope; _map.Display.ZoomTo(((IFeatureClass)_exObject.Object).Envelope); } else if (_exObject.Object is IRasterClass && ((IRasterClass)_exObject.Object).Polygon != null) { mapView1.Map = _map; _map.AddLayer(LayerFactory.Create(_exObject.Object as IClass)); _map.Display.Limit = ((IRasterClass)_exObject.Object).Polygon.Envelope; _map.Display.ZoomTo(((IRasterClass)_exObject.Object).Polygon.Envelope); } else if (_exObject.Object is IWebServiceClass && ((IWebServiceClass)_exObject.Object).Envelope != null) { mapView1.Map = _map; _map.AddLayer(LayerFactory.Create(_exObject.Object as IClass)); _map.Display.Limit = ((IWebServiceClass)_exObject.Object).Envelope; _map.Display.ZoomTo(((IWebServiceClass)_exObject.Object).Envelope); } else if (_exObject.Object is IFeatureDataset) { mapView1.Map = _map; IFeatureDataset dataset = (IFeatureDataset)_exObject.Object; foreach (IDatasetElement element in dataset.Elements) { ILayer layer = LayerFactory.Create(element.Class) as ILayer; if (layer == null) continue; _map.AddLayer(layer); } _map.Display.Limit = dataset.Envelope; _map.Display.ZoomTo(dataset.Envelope); } else if (_exObject.Object is Map) { Map map = (Map)_exObject.Object; map.NewBitmap -= new NewBitmapEvent(mapView1.NewBitmapCreated); map.DoRefreshMapView -= new DoRefreshMapViewEvent(mapView1.MakeMapViewRefresh); map.NewBitmap += new NewBitmapEvent(mapView1.NewBitmapCreated); map.DoRefreshMapView += new DoRefreshMapViewEvent(mapView1.MakeMapViewRefresh); mapView1.Map = (Map)_exObject.Object; } } } } public IExplorerObject ExplorerObject { get { return _exObject; } set { if (_exObject == value || _map == null) return; _exObject = value; InkokeSetExplorerObject(); } } public bool ShowWith(IExplorerObject exObject) { if (exObject == null) return false; if (TypeHelper.Match(exObject.ObjectType, typeof(IFeatureClass)) || TypeHelper.Match(exObject.ObjectType, typeof(IRasterClass)) || TypeHelper.Match(exObject.ObjectType, typeof(IWebServiceClass)) || TypeHelper.Match(exObject.ObjectType, typeof(IFeatureDataset)) || TypeHelper.Match(exObject.ObjectType, typeof(Map))) return true; return false; } public string Title { get { return "Preview"; } } public void RefreshContents() { if (this.InvokeRequired) { this.Invoke(new MethodInvoker(() => { RefreshContents(); })); } else { mapView1.CancelDrawing(DrawPhase.All); mapView1.RefreshMap(DrawPhase.All); } } #endregion private void toolStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { if (!(e.ClickedItem is ToolButton) || _activeToolButton == e.ClickedItem) return; _activeToolButton.Checked = false; _activeToolButton = (ToolButton)e.ClickedItem; _activeToolButton.Checked = true; mapView1.Tool = _activeToolButton.Tool; } internal ITool Tool(Guid guid) { foreach (ITool tool in _tools) { if (PlugInManager.PlugInID(tool) == guid) return tool; } return null; } public void RefreshMap() { if (this.InvokeRequired) { this.Invoke(new MethodInvoker(() => { RefreshMap(); })); } else { if (mapView1 != null) mapView1.RefreshMap(DrawPhase.All); } } #region IOrder Members public int SortOrder { get { return 10; } } #endregion #region mapView private delegate void DrawingLayerCallback(string layerName); private void DrawingLayer(string layerName) { if (statusStrip1.InvokeRequired) { DrawingLayerCallback d = new DrawingLayerCallback(DrawingLayer); this.Invoke(d, new object[] { layerName }); } else { if (layerName == "") toolStripStatusLabel1.Text = ""; else toolStripStatusLabel1.Text = "Drawing Layer " + layerName + "..."; } } private void mapView1_AfterRefreshMap() { DrawingLayer(""); } private delegate void CursorMoveCallback(int x, int y, double X, double Y); private void mapView1_CursorMove(int x, int y, double X, double Y) { if (statusStrip1.InvokeRequired) { CursorMoveCallback d = new CursorMoveCallback(mapView1_CursorMove); this.Invoke(d, new object[] { x, y, X, Y }); } else { toolStripStatusLabel2.Text = "X: " + Math.Round(X, 2); toolStripStatusLabel3.Text = "Y: " + Math.Round(Y, 2); } } #endregion } internal class ToolButton : ToolStripButton { private ITool _tool; public ToolButton(ITool tool) : base((Image)tool.Image) { _tool = tool; } public ITool Tool { get { return _tool; } } } [gView.Framework.system.RegisterPlugIn("62661EF5-2B98-4189-BFCD-7629476FA91C")] public class DataTablePage : IExplorerTabPage { gView.Framework.UI.Dialogs.FormDataTable _table = null; IExplorerObject _exObject = null; #region IExplorerTabPage Members public Control Control { get { if (_table == null) _table = new gView.Framework.UI.Dialogs.FormDataTable(null); _table.StartWorkerOnShown = false; _table.ShowExtraButtons = false; return _table; } } public void OnCreate(object hook) { } public void OnShow() { OnHide(); if (_exObject == null) return; if (_exObject.Object is ITableClass && _table != null) { _table.TableClass = (ITableClass)_exObject.Object; _table.StartWorkerThread(); } } public void OnHide() { //MessageBox.Show("get hidden..."); if (_table != null) { _table.TableClass = null; } } public IExplorerObject ExplorerObject { get { return _exObject; } set { _exObject = value; //OnShow(); } } public bool ShowWith(IExplorerObject exObject) { if (exObject == null) return false; if (TypeHelper.Match(exObject.ObjectType, typeof(ITableClass))) { //if (TypeHelper.Match(exObject.ObjectType, typeof(INetworkClass)) && // ((IFeatureClass)exObject.Object).GeometryType == gView.Framework.Geometry.geometryType.Network) // return false; return true; } return false; } public string Title { get { return "Data Table"; } } public void RefreshContents() { } #endregion #region IOrder Members public int SortOrder { get { return 20; } } #endregion } }
namespace Fixtures.SwaggerBatHttp { using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; internal partial class HttpRedirects : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpRedirects { /// <summary> /// Initializes a new instance of the HttpRedirects class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal HttpRedirects(AutoRestHttpInfrastructureTestService client) { this.Client = client; } /// <summary> /// Gets a reference to the AutoRestHttpInfrastructureTestService /// </summary> public AutoRestHttpInfrastructureTestService Client { get; private set; } /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> Head300WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Head300", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/300"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("HEAD"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MultipleChoices"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse<IList<string>>> Get300WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Get300", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/300"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MultipleChoices"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<IList<string>>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MultipleChoices")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<IList<string>>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> Head301WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Head301", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/301"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("HEAD"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MovedPermanently"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> Get301WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Get301", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/301"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MovedPermanently"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Put true Boolean value in request returns 301. This request should not be /// automatically redirected, but should return the received 301 to the /// caller for evaluation /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> Put301WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Put301", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/301"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MovedPermanently"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> Head302WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Head302", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/302"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("HEAD"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "Redirect"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> Get302WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Get302", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/302"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "Redirect"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Patch true Boolean value in request returns 302. This request should not /// be automatically redirected, but should return the received 302 to the /// caller for evaluation /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> Patch302WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Patch302", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/302"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "Redirect"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Post true Boolean value in request returns 303. This request should be /// automatically redirected usign a get, ultimately returning a 200 status /// code /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> Post303WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Post303", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/303"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("POST"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "SeeOther"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Redirect with 307, resulting in a 200 success /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> Head307WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Head307", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/307"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("HEAD"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Redirect get with 307, resulting in a 200 success /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> Get307WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Get307", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/307"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Put redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> Put307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Put307", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/307"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Patch redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> Patch307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Patch307", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/307"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Post redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> Post307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Post307", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/307"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("POST"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Delete redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<HttpOperationResponse> Delete307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Delete307", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//http/redirect/307"; // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("DELETE"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } } }
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); } // Update is called once per frame private void Update() { RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); //PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; // PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; // PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 // int n = Random.Range(1, m_FootstepSounds.Length); // m_AudioSource.clip = m_FootstepSounds[n]; //m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time // m_FootstepSounds[n] = m_FootstepSounds[0]; //m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
/****************************************************************************** * The MIT License * Copyright (c) 2007 Novell Inc., www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // Authors: // Thomas Wiest ([email protected]) // Rusty Howell ([email protected]) // // (C) Novell Inc. using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Text; using System.Management.Internal.CimXml; using System.Management.Internal.Net; using System.Management.Internal.Batch; namespace System.Management.Internal { #region Delegates internal delegate void CimDataTypeHandler(CimXmlHeader header, object CimObject); #endregion /// <summary> /// /// </summary> internal class WbemClient { protected delegate string FakeCimomHandler(string request); string _hostname; int _port; CimName _defaultNamespace; NetworkCredential _credentials; bool _isSecure; bool _isAuthenticated; ICertificatePolicy _certificatePolicy; FakeCimomHandler _fakeCimom; /// <summary> /// /// </summary> public int TestType; #region Constructors public WbemClient(string hostname, string username, string password, string defaultNamespace) : this(hostname, -1, new NetworkCredential(username, password), defaultNamespace) { } public WbemClient(string hostname, int port, string username, string password, string defaultNamespace) : this(hostname, port, new NetworkCredential(username, password), defaultNamespace) { } public WbemClient(string hostname, NetworkCredential credentials, string defaultNamespace) : this(hostname, -1, credentials, defaultNamespace) { } public WbemClient(string hostname, int port, NetworkCredential credentials, string defaultNamespace) { Hostname = hostname; Port = port; Credentials = credentials; DefaultNamespace = defaultNamespace; IsSecure = true; IsAuthenticated = false; FakeCimom = null; } #endregion #region Properties and Indexers public string Hostname { get { return _hostname; } set { _hostname = value; } } public int Port { get { if (_port == -1) { if (IsSecure) return 5989; // Default secure port else return 5988; // Default non-secure port } else return _port; } set { _port = value; } } public CimName DefaultNamespace { get { return _defaultNamespace; } set { _defaultNamespace = value; } } public NetworkCredential Credentials { get { return _credentials; } set { _credentials = value; } } public string Username { get { return Credentials.UserName; } set { Credentials.UserName = value; } } public string Password { get { return Credentials.Password; } set { Credentials.Password = value; } } public bool IsSecure { get { return _isSecure; } set { _isSecure = value; } } public bool IsAuthenticated { get { return _isAuthenticated; } private set { _isAuthenticated = value; } } protected FakeCimomHandler FakeCimom { get { return _fakeCimom; } set { _fakeCimom = value; } } public string Url { get { string prefix; if (this.IsSecure) prefix = "https://"; else prefix = "http://"; return (prefix + this.Hostname + ":" + this.Port + "/cimom"); } } public ICertificatePolicy CertificatePolicy { get { return _certificatePolicy; } set { _certificatePolicy = value; } } #endregion #region Methods #region From Spec // http://www.dmtf.org/standards/published_documents/DSP0200.html #region 2.3.2.1. GetClass /// <summary> /// /// </summary> /// <param name="className"></param> /// <returns></returns> public CimClass GetClass(CimName className) { return GetClass(new GetClassOpSettings(className)); } /// <summary> /// /// </summary> /// <param name="settings"></param> /// <returns></returns> public CimClass GetClass(GetClassOpSettings settings) { SingleResponse response = MakeSingleRequest("GetClass", settings); if (response.Value == null) { return null; } CheckSingleResponse(response, typeof(CimClassList)); return ((CimClassList)response.Value)[0]; } #endregion #region 2.3.2.2. GetInstance public CimInstance GetInstance(CimInstanceName instanceName) { return GetInstance(new GetInstanceOpSettings(instanceName)); } public CimInstance GetInstance(GetInstanceOpSettings settings) { SingleResponse response = MakeSingleRequest("GetInstance", settings); if (response.Value == null) { return null; } CheckSingleResponse(response, typeof(CimInstanceList)); return CombineInstanceAndInstanceName(((CimInstanceList)response.Value)[0], settings.InstanceName); } #endregion #region 2.3.2.3 DeleteClass /// <summary> /// Deletes a class definition from the cimom /// </summary> /// <param name="className"></param> public void DeleteClass(CimName className) { DeleteClass(new DeleteClassOpSettings(className)); } /// <summary> /// Deletes a class definition from the cimom /// </summary> /// <param name="settings"></param> public void DeleteClass(DeleteClassOpSettings settings) { SingleResponse response = MakeSingleRequest("DeleteClass", settings); if (response != null) { // A Cimom error occurred CheckSingleResponse(response, typeof(CimomError)); } } #endregion #region 2.3.2.4. DeleteInstance /// <summary> /// Deletes the instance from the Cimom /// </summary> /// <param name="instanceName">Name of the instance to delete</param> public void DeleteInstance(CimInstanceName instanceName) { DeleteInstanceOpSettings settings = new DeleteInstanceOpSettings(instanceName); DeleteInstance(settings); } public void DeleteInstance(DeleteInstanceOpSettings settings) { SingleResponse response = MakeSingleRequest("DeleteInstance", settings); if (response != null) { // A Cimom error occurred CheckSingleResponse(response, typeof(CimomError)); } } #endregion #region 2.3.2.5 CreateClass /// <summary> /// Creates a class on the Cimom /// </summary> /// <param name="newClass">CimClass to create</param> public void CreateClass(CimClass newClass) { CreateClass(new CreateClassOpSettings(newClass)); } public void CreateClass(CreateClassOpSettings settings) { SingleResponse response = MakeSingleRequest("CreateClass", settings); if (response != null) { // A Cimom error occurred CheckSingleResponse(response, typeof(CimomError)); } } #endregion #region 2.3.2.6 CreateInstance public CimInstance CreateInstance(CimInstance instance) { return CreateInstance(new CreateInstanceOpSettings(instance)); } public CimInstance CreateInstance(CreateInstanceOpSettings settings) { SingleResponse response = MakeSingleRequest("CreateInstance", settings); if (response.Value == null) { return null; } CheckSingleResponse(response, typeof(CimInstanceNameList)); return CombineInstanceAndInstanceName(settings.Instance, ((CimInstanceNameList)response.Value)[0]); } #endregion #region 2.3.2.7. ModifyClass /// <summary> /// Modify a class on the Cimom /// </summary> /// <param name="modifiedClass">Class to modify</param> public void ModifyClass(CimClass modifiedClass) { ModifyClass(new ModifyClassOpSettings(modifiedClass)); } public void ModifyClass(ModifyClassOpSettings settings) { SingleResponse response = MakeSingleRequest("ModifyClass", settings); if (response != null) { // A Cimom error occurred CheckSingleResponse(response, typeof(CimomError)); } } #endregion #region 2.3.2.8. ModifyInstance public void ModifyInstance(CimInstance instance) { ModifyInstanceOpSettings settings = new ModifyInstanceOpSettings(instance); ModifyInstance(settings); } public void ModifyInstance(ModifyInstanceOpSettings settings) { SingleResponse response = MakeSingleRequest("ModifyInstance", settings); if (response != null) { // A Cimom error occurred CheckSingleResponse(response, typeof(CimomError)); } } #endregion #region 2.3.2.9. EnumerateClasses #region Call Back Versions public void EnumerateClasses(CimDataTypeHandler callBack) { EnumerateClasses(new EnumerateClassesOpSettings(), callBack); } public void EnumerateClasses(EnumerateClassesOpSettings settings, CimDataTypeHandler callBack) { ParseResponse pr = new ParseResponse(); string opXml = CimXml.CreateRequest.ToXml(settings, this.DefaultNamespace); string respXml = ExecuteRequest("EnumerateClasses", opXml); pr.ParseXml(respXml, callBack); } #endregion public CimClassList EnumerateClasses() { return EnumerateClasses(new EnumerateClassesOpSettings()); } public CimClassList EnumerateClasses(EnumerateClassesOpSettings settings) { SingleResponse response = MakeSingleRequest("EnumerateClasses", settings); if (response.Value == null) { return new CimClassList(); // return an empty list } CheckSingleResponse(response, typeof(CimClassList)); return (CimClassList)response.Value; } #endregion #region 2.3.2.10. EnumerateClassNames #region Call Back Versions public void EnumerateClassNames(CimDataTypeHandler callBack) { EnumerateClassNames(new EnumerateClassNamesOpSettings(), callBack); } public void EnumerateClassNames(CimName className, CimDataTypeHandler callBack) { EnumerateClassNames(new EnumerateClassNamesOpSettings(className), callBack); } public void EnumerateClassNames(EnumerateClassNamesOpSettings settings, CimDataTypeHandler callBack) { ParseResponse pr = new ParseResponse(); string reqXml = CimXml.CreateRequest.ToXml(settings, this.DefaultNamespace); string respXml = ExecuteRequest("EnumerateClassNames", reqXml); pr.ParseXml(respXml, callBack); } #endregion public CimNameList EnumerateClassNames() { return EnumerateClassNames(new EnumerateClassNamesOpSettings()); } public CimNameList EnumerateClassNames(CimName className) { return EnumerateClassNames(new EnumerateClassNamesOpSettings(className)); } public CimNameList EnumerateClassNames(EnumerateClassNamesOpSettings settings) { SingleResponse response = MakeSingleRequest("EnumerateClassNames", settings); if (response.Value == null) { return new CimNameList(); // return an empty list } CheckSingleResponse(response, typeof(CimNameList)); return (CimNameList)response.Value; } #endregion #region 2.3.2.11. EnumerateInstances #region Call Back Versions public void EnumerateInstances(CimName className, CimDataTypeHandler callBack) { EnumerateInstances(new EnumerateInstancesOpSettings(className), callBack); } public void EnumerateInstances(EnumerateInstancesOpSettings settings, CimDataTypeHandler callBack) { string reqXml = CimXml.CreateRequest.ToXml(settings, this.DefaultNamespace); string respXml = ExecuteRequest("EnumerateInstances", reqXml); ParseResponse pr = new ParseResponse(); pr.ParseXml(respXml, callBack); } #endregion public CimInstanceList EnumerateInstances(CimName className) { return EnumerateInstances(new EnumerateInstancesOpSettings(className)); } public CimInstanceList EnumerateInstances(EnumerateInstancesOpSettings settings) { SingleResponse response = MakeSingleRequest("EnumerateInstances", settings); if (response.Value == null) { return new CimInstanceList(); // return an empty list } CheckSingleResponse(response, typeof(CimInstanceList)); return (CimInstanceList)response.Value; } #endregion #region 2.3.2.12. EnumerateInstanceNames #region Call Back Versions public void EnumerateInstanceNames(CimName className, CimDataTypeHandler callBack) { EnumerateInstanceNames(new EnumerateInstanceNamesOpSettings(className), callBack); } public void EnumerateInstanceNames(EnumerateInstanceNamesOpSettings settings, CimDataTypeHandler callBack) { ParseResponse pr = new ParseResponse(); string reqXml = CimXml.CreateRequest.ToXml(settings, this.DefaultNamespace); string respXml = ExecuteRequest("EnumerateInstances", reqXml); pr.ParseXml(respXml, callBack); } #endregion public CimInstanceNameList EnumerateInstanceNames(CimName className) { return EnumerateInstanceNames(new EnumerateInstanceNamesOpSettings(className)); } public CimInstanceNameList EnumerateInstanceNames(EnumerateInstanceNamesOpSettings settings) { SingleResponse response = MakeSingleRequest("EnumerateInstanceNames", settings); if (response.Value == null) { return new CimInstanceNameList(); // return an empty list } CheckSingleResponse(response, typeof(CimInstanceNameList)); return (CimInstanceNameList)response.Value; } #endregion #region 2.3.2.13 ExecQuery public object ExecQuery(string queryLanguage, string query) { ExecQueryOpSettings settings = new ExecQueryOpSettings(queryLanguage, query); return ExecQuery(settings); } public object ExecQuery(ExecQueryOpSettings settings) { // OpenWbem doesn't support this call yet :( ////I think this returns a list of ValueObjectWithPath objects ParseResponse pr = new ParseResponse(); string opXml = CimXml.CreateRequest.ToXml(settings, this.DefaultNamespace); string respXml = ExecuteRequest("ExecQuery", opXml); BatchResponse responses = pr.ParseXml(respXml); if (responses.Count != 1) throw (new Exception("Not a single response to a single request")); return responses [0].Value; } #endregion #region 2.3.2.14 Associators #region 2.3.2.14a Associators with class name #region Call Back Versions public void Associators(CimName className, CimDataTypeHandler callBack) { Associators(new AssociatorsWithClassNameOpSettings(className), callBack); } public void Associators(AssociatorsWithClassNameOpSettings settings, CimDataTypeHandler callBack) { ParseResponse pr = new ParseResponse(); string opXml = CimXml.CreateRequest.ToXml(settings, this.DefaultNamespace); string respXml = ExecuteRequest("Associators", opXml); pr.ParseXml(respXml, callBack); } #endregion public CimClassPathList Associators(CimName className) { return Associators(new AssociatorsWithClassNameOpSettings(className)); } public CimClassPathList Associators(AssociatorsWithClassNameOpSettings settings) { SingleResponse response = MakeSingleRequest("Associators", settings); if (response.Value == null) { return new CimClassPathList(); // return an empty list } CheckSingleResponse(response, typeof(CimClassPathList)); return (CimClassPathList)response.Value; } #endregion #region 2.3.2.14b Associators with instance name #region Call Back Versions public void Associators(CimInstanceName instanceName, CimDataTypeHandler callBack) { Associators(new AssociatorsWithInstanceNameOpSettings(instanceName), callBack); } public void Associators(AssociatorsWithInstanceNameOpSettings settings, CimDataTypeHandler callBack) { ParseResponse pr = new ParseResponse(); string opXml = CimXml.CreateRequest.ToXml(settings, this.DefaultNamespace); string respXml = ExecuteRequest("Associators", opXml); pr.ParseXml(respXml, callBack); } #endregion public CimInstancePathList Associators(CimInstanceName instanceName) { return Associators(new AssociatorsWithInstanceNameOpSettings(instanceName)); } public CimInstancePathList Associators(AssociatorsWithInstanceNameOpSettings settings) { SingleResponse response = MakeSingleRequest("Associators", settings); if (response.Value == null) { return new CimInstancePathList(); // return an empty list } CheckSingleResponse(response, typeof(CimInstancePathList)); return (CimInstancePathList)response.Value; } #endregion #endregion #region 2.3.2.15 AssociatorNames #region 2.3.2.15a AssociatorNames with class names #region Call Back Versions public void AssociatorNames(CimName className, CimDataTypeHandler callBack) { AssociatorNames(new AssociatorNamesWithClassNameOpSettings(className), callBack); } public void AssociatorNames(AssociatorNamesWithClassNameOpSettings settings, CimDataTypeHandler callBack) { ParseResponse pr = new ParseResponse(); string opXml = CimXml.CreateRequest.ToXml(settings, this.DefaultNamespace); string respXml = ExecuteRequest("AssociatorNames", opXml); pr.ParseXml(respXml, callBack); } #endregion public CimClassNamePathList AssociatorNames(CimName className) { return AssociatorNames(new AssociatorNamesWithClassNameOpSettings(className)); } public CimClassNamePathList AssociatorNames(AssociatorNamesWithClassNameOpSettings settings) { SingleResponse response = MakeSingleRequest("AssociatorNames", settings); if (response.Value == null) { return new CimClassNamePathList(); // return an empty list } CheckSingleResponse(response, typeof(CimClassNamePathList)); return (CimClassNamePathList)response.Value; } #endregion #region 2.3.2.15b AssociatorNames with instance names #region Call Back Versions public void AssociatorNames(CimInstanceName instanceName, CimDataTypeHandler callBack) { AssociatorNames(new AssociatorNamesWithInstanceNameOpSettings(instanceName), callBack); } public void AssociatorNames(AssociatorNamesWithInstanceNameOpSettings settings, CimDataTypeHandler callBack) { ParseResponse pr = new ParseResponse(); string opXml = CimXml.CreateRequest.ToXml(settings, this.DefaultNamespace); string respXml = ExecuteRequest("AssociatorNames", opXml); pr.ParseXml(respXml, callBack); } #endregion public CimInstanceNamePathList AssociatorNames(CimInstanceName instanceName) { return AssociatorNames(new AssociatorNamesWithInstanceNameOpSettings(instanceName)); } public CimInstanceNamePathList AssociatorNames(AssociatorNamesWithInstanceNameOpSettings settings) { SingleResponse response = MakeSingleRequest("AssociatorNames", settings); if (response.Value == null) { return new CimInstanceNamePathList(); // return an empty list } CheckSingleResponse(response, typeof(CimInstanceNamePathList)); return (CimInstanceNamePathList)response.Value; } #endregion #endregion #region 2.3.2.16 References #region 2.3.2.16 References with class names #region Call Back Versions public void References(CimName className, CimDataTypeHandler callBack) { References(new ReferencesWithClassNameOpSettings(className), callBack); } public void References(ReferencesWithClassNameOpSettings settings, CimDataTypeHandler callBack) { ParseResponse pr = new ParseResponse(); string opXml = CimXml.CreateRequest.ToXml(settings, this.DefaultNamespace); string respXml = ExecuteRequest("References", opXml); pr.ParseXml(respXml, callBack); } #endregion public CimClassPathList References(CimName className) { return References(new ReferencesWithClassNameOpSettings(className)); } public CimClassPathList References(ReferencesWithClassNameOpSettings settings) { SingleResponse response = MakeSingleRequest("References", settings); if (response.Value == null) { return new CimClassPathList(); // return an empty list } CheckSingleResponse(response, typeof(CimClassPathList)); return (CimClassPathList)response.Value; } #endregion #region 2.3.2.16 References with instance names #region Call Back Versions public void References(CimInstanceName instanceName, CimDataTypeHandler callBack) { References(new ReferencesWithInstanceNameOpSettings(instanceName), callBack); } public void References(ReferencesWithInstanceNameOpSettings settings, CimDataTypeHandler callBack) { ParseResponse pr = new ParseResponse(); string opXml = CimXml.CreateRequest.ToXml(settings, this.DefaultNamespace); string respXml = ExecuteRequest("References", opXml); pr.ParseXml(respXml, callBack); } #endregion public CimInstancePathList References(CimInstanceName instanceName) { return References(new ReferencesWithInstanceNameOpSettings(instanceName)); } public CimInstancePathList References(ReferencesWithInstanceNameOpSettings settings) { SingleResponse response = MakeSingleRequest("References", settings); if (response.Value == null) { return new CimInstancePathList(); // return an empty list } CheckSingleResponse(response, typeof(CimInstancePathList)); return (CimInstancePathList)response.Value; } #endregion #endregion #region 2.3.2.17 ReferenceNames #region 2.3.2.17a ReferenceNames with class names #region Call Back Versions public void ReferenceNames(CimName className, CimDataTypeHandler callBack) { ReferenceNames(new ReferenceNamesWithClassNameOpSettings(className), callBack); } public void ReferenceNames(ReferenceNamesWithClassNameOpSettings settings, CimDataTypeHandler callBack) { ParseResponse pr = new ParseResponse(); string opXml = CimXml.CreateRequest.ToXml(settings, this.DefaultNamespace); string respXml = ExecuteRequest("References", opXml); pr.ParseXml(respXml, callBack); } #endregion public CimClassNamePathList ReferenceNames(CimName className) { return ReferenceNames(new ReferenceNamesWithClassNameOpSettings(className)); } public CimClassNamePathList ReferenceNames(ReferenceNamesWithClassNameOpSettings settings) { SingleResponse response = MakeSingleRequest("References", settings); if (response.Value == null) { return new CimClassNamePathList(); // return an empty list } CheckSingleResponse(response, typeof(CimClassNamePathList)); return (CimClassNamePathList)response.Value; } #endregion #region 2.3.2.17b ReferenceNames with instance names #region Call Back Versions public void ReferenceNames(CimInstanceName instanceName, CimDataTypeHandler callBack) { ReferenceNames(new ReferenceNamesWithInstanceNameOpSettings(instanceName), callBack); } public void ReferenceNames(ReferenceNamesWithInstanceNameOpSettings settings, CimDataTypeHandler callBack) { ParseResponse pr = new ParseResponse(); string opXml = CimXml.CreateRequest.ToXml(settings, this.DefaultNamespace); string respXml = ExecuteRequest("References", opXml); pr.ParseXml(respXml, callBack); } #endregion public CimInstanceNamePathList ReferenceNames(CimInstanceName instanceName) { return ReferenceNames(new ReferenceNamesWithInstanceNameOpSettings(instanceName)); } public CimInstanceNamePathList ReferenceNames(ReferenceNamesWithInstanceNameOpSettings settings) { SingleResponse response = MakeSingleRequest("ReferenceNames", settings); if (response.Value == null) { return new CimInstanceNamePathList(); // return an empty list } CheckSingleResponse(response, typeof(CimInstanceNamePathList)); return (CimInstanceNamePathList)response.Value; } #endregion #endregion #region 2.3.2.18. GetProperty public string GetProperty(CimInstanceName instanceName, string propertyName) { GetPropertyOpSettings settings = new GetPropertyOpSettings(instanceName, propertyName); return GetProperty(settings); } public string GetProperty(GetPropertyOpSettings settings) { SingleResponse response = MakeSingleRequest("GetProperty", settings); if (response.Value == null) { return string.Empty; } CheckSingleResponse(response, typeof(string)); return ((string)response.Value); } #endregion #region 2.3.2.19 SetProperty public void SetProperty(CimInstanceName instanceName, string propertyName) { SetPropertyOpSettings settings = new SetPropertyOpSettings(instanceName, propertyName); SetProperty(settings); } public void SetProperty(CimInstanceName instanceName, string propertyName, string value) { SetPropertyOpSettings settings = new SetPropertyOpSettings(instanceName, propertyName, value); SetProperty(settings); } public void SetProperty(SetPropertyOpSettings settings) { SingleResponse response = MakeSingleRequest("SetProperty", settings); if (response != null) { // A Cimom error occurred CheckSingleResponse(response, typeof(CimomError)); } } #endregion #region 2.3.2.20 GetQualifier public CimQualifierDeclaration GetQualifier(string qualifierName) { return GetQualifier(new GetQualifierOpSettings(qualifierName)); } public CimQualifierDeclaration GetQualifier(GetQualifierOpSettings settings) { SingleResponse response = MakeSingleRequest("GetQualifier", settings); if (response.Value == null) { return null; } CheckSingleResponse(response, typeof(CimQualifierDeclarationList)); return ((CimQualifierDeclarationList)response.Value)[0]; } #endregion #region 2.3.2.21 SetQualifier public void SetQualifier(CimQualifierDeclaration qualifierDeclaration) { SetQualifier(new SetQualifierOpSettings(qualifierDeclaration)); } public void SetQualifier(SetQualifierOpSettings settings) { SingleResponse response = MakeSingleRequest("SetQualifier", settings); if (response != null) { // A Cimom error occurred CheckSingleResponse(response, typeof(CimomError)); } } #endregion #region 2.3.2.22 DeleteQualifier public void DeleteQualifier(string qualifierName) { DeleteQualifier(new DeleteQualifierOpSettings(qualifierName)); } public void DeleteQualifier(DeleteQualifierOpSettings settings) { SingleResponse response = MakeSingleRequest("DeleteQualifier", settings); if (response != null) { // A Cimom error occurred CheckSingleResponse(response, typeof(CimomError)); } } #endregion #region 2.3.2.23 EnumerateQualifiers public CimQualifierDeclarationList EnumerateQualifiers() { return EnumerateQualifiers(new EnumerateQualifierOpSettings()); } public CimQualifierDeclarationList EnumerateQualifiers(EnumerateQualifierOpSettings settings) { SingleResponse response = MakeSingleRequest("DeleteQualifier", settings); if (response.Value == null) { return new CimQualifierDeclarationList(); // return an empty list } CheckSingleResponse(response, typeof(CimQualifierDeclarationList)); return (CimQualifierDeclarationList)response.Value; } #endregion #region 2.3.2.24 ExecuteQuery public CimTable ExecuteQuery(string queryLanguage, string query) { ExecuteQueryOpSettings settings = new ExecuteQueryOpSettings(queryLanguage, query); return ExecuteQuery(settings); } public CimTable ExecuteQuery(ExecuteQueryOpSettings settings) { SingleResponse response = MakeSingleRequest("ExecuteQuery", settings); if (response.Value == null) { return null; } CheckSingleResponse(response, typeof(CimQualifierDeclarationList)); return null; } #endregion #endregion #region Extra #region EnumerateLeafClasses public CimClassList EnumerateLeafClasses() { return EnumerateLeafClasses(new EnumerateLeafClassesOpSettings()); } public CimClassList EnumerateLeafClasses(EnumerateLeafClassesOpSettings settings) { CimClassList allClasses = EnumerateClasses(new EnumerateClassesOpSettings(settings)); CimClassList leafClasses = new CimClassList(); Dictionary<CimName, bool> superClasses = new Dictionary<CimName, bool>(); //changed for MONO //foreach (CimClass curClass in allClasses) for (int i = 0; i < allClasses.Count; ++i) { CimClass curClass = allClasses[i]; if (curClass.SuperClass.IsSet) { if (!superClasses.ContainsKey(curClass.SuperClass)) { superClasses.Add(curClass.SuperClass, true); } } } //foreach (CimClass curClass in allClasses) for (int i = 0; i < allClasses.Count; ++i) { CimClass curClass = allClasses[i]; if (!superClasses.ContainsKey(curClass.ClassName)) { leafClasses.Add(curClass); } } return leafClasses; } #endregion #region EnumerateLeafClassNames public CimNameList EnumerateLeafClassNames() { CimClassList leafClasses = EnumerateLeafClasses(); CimNameList leafClassNames = new CimNameList(); //changed for MONO //foreach (CimClass curLeafClass in leafClasses) for (int i = 0; i < leafClasses.Count; ++i) { leafClassNames.Add(leafClasses[i].ClassName); } return leafClassNames; } #endregion #region EnumerateClassHierarchy public CimTreeNode EnumerateClassHierarchy() { return EnumerateClassHierarchy(null); } public CimTreeNode EnumerateClassHierarchy(CimName className) { EnumerateClassesOpSettings ec = new EnumerateClassesOpSettings(className); ec.DeepInheritance = true; ec.IncludeClassOrigin = false; ec.IncludeQualifiers = false; ec.LocalOnly = true; CimClassList classList = EnumerateClasses(ec); Dictionary<CimName, CimTreeNode> hash = new Dictionary<CimName, CimTreeNode>(); if (className == null) { className = this.DefaultNamespace; } hash.Add(className, new CimTreeNode(className)); for (int i = 0; i < classList.Count; i++) { CimClass curClass = classList[i]; CimTreeNode curNode = new CimTreeNode(curClass.ClassName); if (!hash.ContainsKey(curClass.ClassName)) hash.Add(curClass.ClassName, curNode); if (curClass.SuperClass != string.Empty) { if (!hash.ContainsKey(curClass.SuperClass)) { hash.Add(curClass.SuperClass, new CimTreeNode(curClass.SuperClass)); } hash[curClass.SuperClass].Children.Add(curNode); } else { hash[className].Children.Add(curNode); } } return hash[className]; } #endregion #region EnumerateNamespaces public string[] EnumerateNamespaces() { List<string> nsStrings = new List<string>(); EnumerateInstanceNamesOpSettings eino = new EnumerateInstanceNamesOpSettings("CIM_NamespaceInManager"); eino.Namespace = "Interop"; CimInstanceNameList cinl = this.EnumerateInstanceNames(eino); //Changed for MONO for (int i = 0; i < cinl.Count; ++i) { CimInstanceName curIN = cinl[i]; CimKeyBinding tmpKB = curIN.KeyBindings["Dependent"]; CimInstanceNamePath tmpCLIP = (CimInstanceNamePath)((CimValueReference)tmpKB.Value).CimObject; CimKeyValue tmpKV = (CimKeyValue)tmpCLIP.InstanceName.KeyBindings["name"].Value; nsStrings.Add(tmpKV.Value); } return nsStrings.ToArray(); } #endregion #region GetBaseKeyClassName /// <summary> /// Gets the base class of the class /// </summary> /// <param name="className"></param> /// <returns>Returns the name of the class</returns> public CimName GetBaseKeyClassName(string className) { return GetBaseKeyClassName(new CimName(className)); } /// <summary> /// Gets the base class of the class /// </summary> /// <param name="className"></param> /// <returns>Returns the name of the class</returns> public CimName GetBaseKeyClassName(CimName className) { GetClassOpSettings gcop = new GetClassOpSettings(className); gcop.LocalOnly = false; CimClass curClass = this.GetClass(gcop); CimClass startClass = curClass; CimName lastClassName = null; // default value if className doesn't have a BKC while (curClass.HasKeyProperty == true) { lastClassName = curClass.ClassName; if (curClass.SuperClass != string.Empty) { gcop.ClassName = curClass.SuperClass; curClass = this.GetClass(gcop); } else break; } return lastClassName; } #endregion #region CreateTemplateInstance public CimInstance CreateTemplateInstance(CimName className) { GetClassOpSettings gcos = new GetClassOpSettings(className); gcos.IncludeQualifiers = false; gcos.LocalOnly = false; gcos.IncludeClassOrigin = false; CimClass tmpClass = this.GetClass(gcos); CimInstance retVal = new CimInstance(className); retVal.Properties = tmpClass.Properties; return retVal; } #endregion #region ExecuteBatchRequest public BatchResponse ExecuteBatchRequest(BatchRequest request) { ParseResponse pr = new ParseResponse(); string opXml = CimXml.CreateRequest.ToXml(request); string respXml = ExecuteRequest("BatchRequest", opXml); return pr.ParseXml(respXml); } #endregion #region InvokeMethod public CimMethodResponse InvokeMethod(CimName className, CimName methodName, CimParameterValueList parameterList) { return InvokeMethod(new InvokeMethodOpSettings(className, methodName, parameterList)); } public CimMethodResponse InvokeMethod(CimInstanceName instanceName, CimName methodName, CimParameterValueList parameterList) { return InvokeMethod(new InvokeMethodOpSettings(instanceName, methodName, parameterList)); } public CimMethodResponse InvokeMethod(InvokeMethodOpSettings settings) { SingleResponse response = MakeSingleRequest("InvokeMethod", settings); if (response.Value == null) { return new CimMethodResponse(); // return an empty list } CheckSingleResponse(response, typeof(CimMethodResponse)); return (CimMethodResponse)response.Value; } #endregion #endregion #region Helpers private string ExecuteRequest(string cimOperation, string cimMessage) { string response = string.Empty; if (FakeCimom != null) { // Use the fake cimom for unit testing response = FakeCimom(cimMessage); } else { CimomResponse cimResp = null; CimomRequest cimReq; cimReq = new CimomRequest(this.Url, this.CertificatePolicy); cimReq.Credentials = this.Credentials; // Optional cimReq.Headers.Add(cimReq.NameSpaceValue.ToString() + "-CIMOperation", "MethodCall"); cimReq.Headers.Add(cimReq.NameSpaceValue.ToString() + "-CIMMethod", cimOperation); cimReq.Headers.Add(cimReq.NameSpaceValue.ToString() + "-CIMObject", this.DefaultNamespace.ToString()); // Put the message in the send buffer. cimReq.Message = cimMessage; // Send the buffer, and get the response. cimResp = cimReq.GetResponse(); // Grab the message from the response buffer. response = cimResp.Message; // See if an error occurred if ((int)cimResp.StatusCode != 200) return null; } return response; } private SingleResponse MakeSingleRequest(string cimOperation, SingleRequest operation) { ParseResponse pr = new ParseResponse(); string reqXml = CimXml.CreateRequest.ToXml(operation, this.DefaultNamespace); string respXml = ExecuteRequest(cimOperation, reqXml); BatchResponse responses = pr.ParseXml(respXml); if (responses == null) { return new SingleResponse(); } if (responses.Count != 1) throw (new Exception("Not a single response to a single request")); return responses[0]; } private void CheckSingleResponse(SingleResponse response, Type expectedType) { if (response.Value.GetType() == typeof(CimomError)) { string desc = ((CimomError)response.Value).Description; if (desc == string.Empty) desc = ((CimomError)response.Value).DescriptionFromSpec; // We might want to create a CimomError Exception that incorporates the CimomError object throw (new Exception("Cimom Error [" + ((CimomError)response.Value).ErrorCode + "]: " + desc)); } if (response.Value.GetType() != expectedType) throw (new Exception("Response didn't match a " + expectedType.ToString())); } private CimInstance CombineInstanceAndInstanceName(CimInstance instance, CimInstanceName instanceName) { if (instance.ClassName != instanceName.ClassName) throw new Exception("InstanceName.ClassName != Instance.ClassName"); instance.InstanceName = instanceName; return instance; } #endregion #endregion } }
#region License /* * NReco Data library (http://www.nrecosite.com/) * Copyright 2016 Vitaliy Fedorchenko * Distributed under the MIT license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Text; using System.Globalization; namespace NReco.Data.Relex { /// <summary> /// Parses relex expression to <see cref="Query"/> structure. /// </summary> public class RelexParser { /// <summary> /// Allows raw sql constants like "select 1":sql. True by default. /// </summary> public bool AllowRawSql { get; set; } = true; static readonly string[] nameGroups = new string[] { "and", "or"}; static readonly string[] delimiterGroups = new string[] { "&&", "||"}; static readonly QGroupType[] enumGroups = new QGroupType[] { QGroupType.And, QGroupType.Or }; static readonly string[] delimiterConds = new string[] { "==", "=", "<>", "!=", ">", ">=", "<", "<="}; static readonly string[] nameConds = new string[] { "in", "like" }; static readonly string nullField = "null"; static readonly Conditions[] enumDelimConds = new Conditions[] { Conditions.Equal, Conditions.Equal, Conditions.Not|Conditions.Equal, Conditions.Not|Conditions.Equal, Conditions.GreaterThan, Conditions.GreaterThan|Conditions.Equal, Conditions.LessThan, Conditions.LessThan|Conditions.Equal }; static readonly Conditions[] enumNameConds = new Conditions[] { Conditions.In, Conditions.Like }; static readonly char[] delimiters = new char[] { '(', ')', '[', ']', ';', ':', ',', '=', '<', '>', '!', '&', '|', '*', '{', '}'}; static readonly char charQuote = '"'; static readonly char[] specialNameChars = new char[] { '.', '-', '_' }; static readonly char[] arrayValuesSeparators = new char[] { '\0', ';', ',', '\t' }; // order is important! static readonly string[] typeNames; static readonly string[] arrayTypeNames; public enum LexemType { Unknown, Name, Delimiter, QuotedConstant, Constant, Stop } static RelexParser() { typeNames = Enum.GetNames(typeof(TypeCode)); arrayTypeNames = new string[typeNames.Length]; for (int i=0; i<typeNames.Length; i++) { typeNames[i] = typeNames[i].ToLower(); arrayTypeNames[i] = typeNames[i] + "[]"; } } public RelexParser() { } protected LexemType GetLexemType(string s, int startIdx, out int endIdx) { LexemType lexemType = LexemType.Unknown; endIdx = startIdx; while (endIdx<s.Length) { if (Array.IndexOf(delimiters,s[endIdx])>=0) { if (lexemType==LexemType.Unknown) { endIdx++; return LexemType.Delimiter; } if (lexemType!=LexemType.QuotedConstant) return lexemType; } else if (Char.IsSeparator(s[endIdx])) { if (lexemType!=LexemType.QuotedConstant && lexemType!=LexemType.Unknown) return lexemType; // done } else if (Char.IsLetter(s[endIdx])) { if (lexemType==LexemType.Unknown) lexemType=LexemType.Name; } else if (Char.IsDigit(s[endIdx])) { if (lexemType==LexemType.Unknown) lexemType=LexemType.Constant; } else if (Array.IndexOf(specialNameChars,s[endIdx])>=0) { if (lexemType==LexemType.Unknown) lexemType=LexemType.Constant; if (lexemType!=LexemType.Name && lexemType!=LexemType.Constant && lexemType!=LexemType.QuotedConstant) throw new RelexParseException( String.Format("Invalid syntax (position: {0}, expression: {1}", startIdx, s ) ); } else if (s[endIdx]==charQuote) { if (lexemType==LexemType.Unknown) lexemType = LexemType.QuotedConstant; else { if (lexemType==LexemType.QuotedConstant) { // check for "" combination if ( ( (endIdx+1)<s.Length && s[endIdx+1]!=charQuote) ) { endIdx++; return lexemType; } else if ((endIdx+1)<s.Length) endIdx++; // skip next quote } } } else if (Char.IsControl(s[endIdx]) && lexemType!=LexemType.Unknown && lexemType!=LexemType.QuotedConstant) return lexemType; // goto next char endIdx++; } if (lexemType==LexemType.Unknown) return LexemType.Stop; if (lexemType==LexemType.Constant) throw new RelexParseException( String.Format("Unterminated constant (position: {0}, expression: {1}", startIdx, s ) ); return lexemType; } protected string GetLexem(string s, int startIdx, int endIdx, LexemType lexemType) { string lexem = GetLexem(s, startIdx, endIdx); if (lexemType!=LexemType.QuotedConstant) return lexem; // remove first and last chars string constant = lexem.Substring(1, lexem.Length-2); // replace "" with " return constant.Replace( "\"\"", "\"" ); } protected string GetLexem(string s, int startIdx, int endIdx) { return s.Substring(startIdx, endIdx-startIdx).Trim(); } protected void GetAllDelimiters(string s, int startIdx, out int endIdx) { endIdx = startIdx; while ((endIdx+1)<s.Length && Array.IndexOf(delimiters, s[endIdx])>=0 ) endIdx++; } protected bool GetGroupType(LexemType lexemType, string s, int startIdx, ref int endIdx, ref QGroupType groupType) { string lexem = GetLexem(s, startIdx, endIdx).ToLower(); if (lexemType==LexemType.Name) { int idx = Array.IndexOf(nameGroups, lexem); if (idx<0) return false; groupType = enumGroups[idx]; return true; } if (lexemType==LexemType.Delimiter) { // read all available delimiters... GetAllDelimiters(s, endIdx, out endIdx); lexem = GetLexem(s, startIdx, endIdx); int idx = Array.IndexOf(delimiterGroups, lexem); if (idx<0) return false; groupType = enumGroups[idx]; return true; } return false; } protected bool GetCondition(LexemType lexemType, string s, int startIdx, ref int endIdx, ref Conditions conditions) { string lexem = GetLexem(s, startIdx, endIdx).ToLower(); if (lexemType==LexemType.Name) { int idx = Array.IndexOf(nameConds, lexem); if (idx>=0) { conditions = enumNameConds[idx]; return true; } } if (lexemType==LexemType.Delimiter) { // read all available delimiters... GetAllDelimiters(s, endIdx, out endIdx); lexem = GetLexem(s, startIdx, endIdx); int idx = Array.IndexOf(delimiterConds, lexem); if (idx<0) { if (lexem=="!") { int newEndIdx; Conditions innerConditions = Conditions.Equal; LexemType newLexemType = GetLexemType(s, endIdx, out newEndIdx); if (GetCondition(newLexemType, s, endIdx, ref newEndIdx, ref innerConditions)) { endIdx = newEndIdx; conditions = innerConditions|Conditions.Not; return true; } } return false; } conditions = enumDelimConds[idx]; return true; } return false; } public virtual Query Parse(string relEx) { int endIdx; IQueryValue qValue = ParseInternal(relEx, 0, out endIdx ); if (!(qValue is Query)) throw new RelexParseException("Invalid expression: result is not a query"); Query q = (Query)qValue; return q; } public virtual QNode ParseCondition(string relExCondition) { int endIdx; if (String.IsNullOrEmpty(relExCondition)) return null; QNode node = ParseConditionGroup(relExCondition, 0, out endIdx); return node; } protected virtual IQueryValue ParseTypedConstant(string typeCodeString, string constant) { typeCodeString = typeCodeString.ToLower(); // sql type if (typeCodeString == "sql") { if (!AllowRawSql) throw new RelexParseException("Raw sql constants are not allowed"); return new QRawSql(constant); } // var type if (typeCodeString == "var") return new QVar(constant); // var type if (typeCodeString == "field") return new QField(constant); // simple type int typeNameIdx = Array.IndexOf(typeNames, typeCodeString); if (typeNameIdx>=0) { TypeCode typeCode = (TypeCode)Enum.Parse(typeof(TypeCode), typeCodeString, true); try { object typedConstant = Convert.ChangeType(constant, typeCode, CultureInfo.InvariantCulture); return new QConst(typedConstant); } catch (Exception ex) { throw new InvalidCastException( String.Format("Cannot parse typed constant \"{0}\":{1}",constant, typeCodeString),ex); } } // array typeNameIdx = Array.IndexOf(arrayTypeNames, typeCodeString); if (typeNameIdx>=0) { TypeCode typeCode = (TypeCode)Enum.Parse(typeof(TypeCode), typeNames[typeNameIdx], true); string[] arrayValues = SplitArrayValues(constant); object[] array = new object[arrayValues.Length]; for (int i=0; i<array.Length; i++) array[i] = Convert.ChangeType(arrayValues[i], typeCode, CultureInfo.InvariantCulture); return new QConst(array); } throw new InvalidCastException( String.Format("Cannot parse typed constant \"{0}\":{1}", constant, typeCodeString) ); } protected string[] SplitArrayValues(string str) { for (int i=0; i<arrayValuesSeparators.Length; i++) if (str.IndexOf(arrayValuesSeparators[i])>=0) return str.Split(arrayValuesSeparators[i]); return str.Split( arrayValuesSeparators ); } protected virtual IQueryValue ParseInternal(string input, int startIdx, out int endIdx) { LexemType lexemType = GetLexemType(input, startIdx, out endIdx); string lexem = GetLexem(input, startIdx, endIdx); if (lexemType==LexemType.Constant) return (QConst)lexem; if (lexemType==LexemType.QuotedConstant) { // remove first and last chars string constant = lexem.Substring(1, lexem.Length-2); // replace "" with " constant = constant.Replace( "\"\"", "\"" ); // typed? int newEndIdx; if ( GetLexemType(input, endIdx, out newEndIdx)==LexemType.Delimiter && GetLexem(input, endIdx, newEndIdx)==":" ) { int typeEndIdx; if (GetLexemType(input, newEndIdx, out typeEndIdx)==LexemType.Name) { string typeCodeString = GetLexem(input, newEndIdx, typeEndIdx); endIdx = typeEndIdx; // read [] at the end if specified if (GetLexemType(input, endIdx, out newEndIdx)==LexemType.Delimiter && GetLexem(input, endIdx, newEndIdx)=="[") if (GetLexemType(input, newEndIdx, out typeEndIdx)==LexemType.Delimiter && GetLexem(input, newEndIdx, typeEndIdx)=="]") { endIdx = typeEndIdx; typeCodeString += "[]"; } if (typeCodeString!="table") { return ParseTypedConstant(typeCodeString, constant); } else { lexem = constant; lexemType = LexemType.Name; } } } else { return (QConst)constant; } } if (lexemType==LexemType.Name) { int nextEndIdx; // query string tableName = lexem; QNode rootCondition = null; QField[] fields = null; QSort[] sort = null; LexemType nextLexemType = GetLexemType(input, endIdx, out nextEndIdx); string nextLexem = GetLexem(input, endIdx, nextEndIdx); if (nextLexemType==LexemType.Delimiter && nextLexem=="(") { // compose conditions rootCondition = ParseConditionGroup(input, nextEndIdx, out endIdx); // read ')' nextLexemType = GetLexemType(input, endIdx, out nextEndIdx); if (nextLexemType!=LexemType.Delimiter || GetLexem(input, endIdx,nextEndIdx)!=")") throw new RelexParseException( String.Format("Invalid syntax (position: {0}, expression: {1})", endIdx, input ) ); // read next lexem nextLexemType = GetLexemType(input, nextEndIdx, out endIdx); nextLexem = GetLexem(input, nextEndIdx, endIdx); nextEndIdx = endIdx; } if (nextLexemType==LexemType.Delimiter && nextLexem=="[") { nextLexemType = GetLexemType(input, nextEndIdx, out endIdx); nextLexem = GetLexem(input, nextEndIdx, endIdx, nextLexemType); nextEndIdx = endIdx; var fieldsList = new List<QField>(); var sortList = new List<QSort>(); var curFldBuilder = new StringBuilder(); curFldBuilder.Append(nextLexem); bool sortPart = false; Action pushFld = () => { if (curFldBuilder.Length > 0) { if (sortPart) { sortList.Add(curFldBuilder.ToString()); } else { fieldsList.Add(curFldBuilder.ToString()); } curFldBuilder.Clear(); } }; do { LexemType prevLexemType = nextLexemType; nextLexemType = GetLexemType(input, endIdx, out nextEndIdx); nextLexem = GetLexem(input, endIdx, nextEndIdx, nextLexemType); endIdx = nextEndIdx; if (nextLexemType == LexemType.Delimiter && nextLexem == "]") { pushFld(); break; } if (nextLexemType == LexemType.Stop) { throw new RelexParseException( String.Format("Invalid syntax - unclosed bracket (position: {0}, expression: {1})", endIdx, input)); } // handle sort separator if (nextLexemType == LexemType.Delimiter && nextLexem == ";") { pushFld(); sortPart = true; } else if (nextLexemType == LexemType.Delimiter && nextLexem == ",") { pushFld(); } else { if (prevLexemType != LexemType.Delimiter && (nextLexem.Equals(QSort.Asc,StringComparison.OrdinalIgnoreCase) || nextLexem.Equals(QSort.Desc, StringComparison.OrdinalIgnoreCase))) { curFldBuilder.Append(' '); } curFldBuilder.Append(nextLexem); } } while (true); if (fieldsList.Count != 1 || fieldsList[0] != "*") fields = fieldsList.ToArray(); if (sortList.Count > 0) sort = sortList.ToArray(); } else { return (QField)lexem; } endIdx = nextEndIdx; Query q = new Query( tableName, rootCondition); // limits? nextLexemType = GetLexemType(input, endIdx, out nextEndIdx); nextLexem = GetLexem(input, endIdx, nextEndIdx); if (nextLexemType==LexemType.Delimiter && nextLexem=="{") { // read start record endIdx = nextEndIdx; nextLexemType = GetLexemType(input, endIdx, out nextEndIdx); nextLexem = GetLexem(input, endIdx, nextEndIdx); if (nextLexemType!=LexemType.Constant) throw new RelexParseException( String.Format("Invalid syntax (position: {0}, expression: {1})", endIdx, input ) ); q.RecordOffset = Int32.Parse(nextLexem); // read comma endIdx = nextEndIdx; nextLexemType = GetLexemType(input, endIdx, out nextEndIdx); nextLexem = GetLexem(input, endIdx, nextEndIdx); if (nextLexemType!=LexemType.Delimiter || nextLexem!=",") throw new RelexParseException( String.Format("Invalid syntax (position: {0}, expression: {1})", endIdx, input ) ); // read record count endIdx = nextEndIdx; nextLexemType = GetLexemType(input, endIdx, out nextEndIdx); nextLexem = GetLexem(input, endIdx, nextEndIdx); if (nextLexemType!=LexemType.Constant) throw new RelexParseException( String.Format("Invalid syntax (position: {0}, expression: {1})", endIdx, input ) ); q.RecordCount = Int32.Parse(nextLexem); // read close part '}' endIdx = nextEndIdx; nextLexemType = GetLexemType(input, endIdx, out nextEndIdx); nextLexem = GetLexem(input, endIdx, nextEndIdx); if (nextLexemType!=LexemType.Delimiter || nextLexem!="}") throw new RelexParseException( String.Format("Invalid syntax (position: {0}, expression: {1})", endIdx, input ) ); endIdx = nextEndIdx; } q.Select(fields); if (sort != null) q.OrderBy(sort); return q; } throw new RelexParseException( String.Format("Invalid syntax (position: {0}, expression: {1})", endIdx, input ) ); } protected string ParseNodeName(string input, int startIdx, out int endIdx) { string nodeName = null; // check for node name - starts with '<' LexemType lexemType = GetLexemType(input, startIdx, out endIdx); string lexem = GetLexem(input, startIdx, endIdx); if (lexemType==LexemType.Delimiter && lexem=="<") { startIdx = endIdx; lexemType = GetLexemType(input, startIdx, out endIdx); if (lexemType!=LexemType.Name && lexemType!=LexemType.Constant && lexemType!=LexemType.QuotedConstant) throw new RelexParseException( String.Format("Invalid syntax - node name expected (position: {0}, expression: {1})", startIdx, input ) ); nodeName = GetLexem(input, startIdx, endIdx); startIdx = endIdx; // read closing delimiter '>' lexemType = GetLexemType(input, startIdx, out endIdx); lexem = GetLexem(input, startIdx, endIdx); if (lexemType!=LexemType.Delimiter || lexem!=">") throw new RelexParseException( String.Format("Invalid syntax (position: {0}, expression: {1})", startIdx, input ) ); } else { endIdx = startIdx; } return nodeName; } protected QNode ParseConditionGroup(string input, int startIdx, out int endIdx) { int nextEndIdx; LexemType lexemType = GetLexemType(input, startIdx, out nextEndIdx); string lexem = GetLexem(input, startIdx, nextEndIdx); // handle not var isNot = false; if (lexemType==LexemType.Name && lexem.Equals("not", StringComparison.OrdinalIgnoreCase)) { isNot = true; startIdx = nextEndIdx; lexemType = GetLexemType(input, startIdx, out nextEndIdx); lexem = GetLexem(input, startIdx, nextEndIdx); } QNode node; if (lexemType==LexemType.Delimiter && lexem=="(") { string nodeName = ParseNodeName(input, nextEndIdx, out endIdx); nextEndIdx = endIdx; // check for empty group lexemType = GetLexemType(input, nextEndIdx, out endIdx); if (lexemType==LexemType.Delimiter && GetLexem(input,nextEndIdx,endIdx)==")") { node = null; // push back endIdx = nextEndIdx; } else node = ParseConditionGroup(input, nextEndIdx, out endIdx); if (nodeName!=null) { if (node==null) node = new QGroupNode(QGroupType.And); if (node is QNode) ((QNode)node).Name = nodeName; } // read ')' lexemType = GetLexemType(input, endIdx, out nextEndIdx); if (lexemType!=LexemType.Delimiter || GetLexem(input,endIdx,nextEndIdx)!=")") throw new RelexParseException( String.Format("Invalid syntax (position: {0}, expression: {1})", endIdx, input ) ); endIdx = nextEndIdx; } else { node = ParseCondition(input, startIdx, out nextEndIdx); endIdx = nextEndIdx; } if (isNot) node = new QNegationNode(node); // check for group lexemType = GetLexemType(input, endIdx, out nextEndIdx); QGroupType groupType = QGroupType.And; if (GetGroupType(lexemType, input, endIdx, ref nextEndIdx, ref groupType)) return ComposeGroupNode(node, ParseConditionGroup(input, nextEndIdx, out endIdx), groupType); return node; } protected QGroupNode ComposeGroupNode(QNode node1, QNode node2, QGroupType groupType) { QGroupNode group1 = node1 as QGroupNode, group2 = node2 as QGroupNode; if (group1 != null && group1.GroupType != groupType) group1 = null; if (group2 != null && group2.GroupType != groupType) group2 = null; // don't corrupt named groups if (group1 != null && group1.Name != null || group2 != null && group2.Name != null) group1 = group2 = null; if (group1 == null) { if (group2 == null) { QGroupNode group = new QGroupNode(groupType); group.Nodes.Add(node1); group.Nodes.Add(node2); return group; } else { group2.Nodes.Insert(0, node1); return group2; } } else { if (group2 == null) group1.Nodes.Add(node2); else foreach (QNode qn in group2.Nodes) group1.Nodes.Add(qn); return group1; } } protected QNode ParseCondition(string input, int startIdx, out int endIdx) { IQueryValue leftValue = ParseInternal(input, startIdx, out endIdx); int nextEndIdx; Conditions conditions = Conditions.Equal; LexemType nextLexemType = GetLexemType(input, endIdx, out nextEndIdx); if (!GetCondition(nextLexemType, input, endIdx, ref nextEndIdx, ref conditions)) throw new RelexParseException( String.Format("Invalid syntax (position: {0}, expression: {1})", startIdx, input ) ); IQueryValue rightValue = ParseInternal(input, nextEndIdx, out endIdx); QNode node; if (IsNullValue(rightValue)) { if ( (conditions & Conditions.Equal)!=0 ) node = new QConditionNode( leftValue, Conditions.Null | (conditions & ~Conditions.Equal), null); else throw new RelexParseException( String.Format("Invalid syntax - such condition cannot be used with 'null' (position: {0}, expression: {1})", startIdx, input ) ); } else node = new QConditionNode( leftValue, conditions, rightValue); return node; } protected bool IsNullValue(IQueryValue value) { return ((value is QField) && ((QField)value).Name.ToLower()==nullField); } } /// <summary> /// </summary> public class RelexParseException : Exception { public RelexParseException() : base() {} public RelexParseException(string message) : base(message) {} public RelexParseException(string message, Exception innerException) : base(message, innerException) {} } }
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.RDS.Model { /// <summary> /// <para> </para> /// </summary> public class OptionGroup { private string optionGroupName; private string optionGroupDescription; private string engineName; private string majorEngineVersion; private List<Option> options = new List<Option>(); private bool? allowsVpcAndNonVpcInstanceMemberships; private string vpcId; /// <summary> /// Specifies the name of the option group. /// /// </summary> public string OptionGroupName { get { return this.optionGroupName; } set { this.optionGroupName = value; } } /// <summary> /// Sets the OptionGroupName property /// </summary> /// <param name="optionGroupName">The value to set for the OptionGroupName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroup WithOptionGroupName(string optionGroupName) { this.optionGroupName = optionGroupName; return this; } // Check to see if OptionGroupName property is set internal bool IsSetOptionGroupName() { return this.optionGroupName != null; } /// <summary> /// Provides the description of the option group. /// /// </summary> public string OptionGroupDescription { get { return this.optionGroupDescription; } set { this.optionGroupDescription = value; } } /// <summary> /// Sets the OptionGroupDescription property /// </summary> /// <param name="optionGroupDescription">The value to set for the OptionGroupDescription property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroup WithOptionGroupDescription(string optionGroupDescription) { this.optionGroupDescription = optionGroupDescription; return this; } // Check to see if OptionGroupDescription property is set internal bool IsSetOptionGroupDescription() { return this.optionGroupDescription != null; } /// <summary> /// Engine name that this option group can be applied to. /// /// </summary> public string EngineName { get { return this.engineName; } set { this.engineName = value; } } /// <summary> /// Sets the EngineName property /// </summary> /// <param name="engineName">The value to set for the EngineName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroup WithEngineName(string engineName) { this.engineName = engineName; return this; } // Check to see if EngineName property is set internal bool IsSetEngineName() { return this.engineName != null; } /// <summary> /// Indicates the major engine version associated with this option group. /// /// </summary> public string MajorEngineVersion { get { return this.majorEngineVersion; } set { this.majorEngineVersion = value; } } /// <summary> /// Sets the MajorEngineVersion property /// </summary> /// <param name="majorEngineVersion">The value to set for the MajorEngineVersion property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroup WithMajorEngineVersion(string majorEngineVersion) { this.majorEngineVersion = majorEngineVersion; return this; } // Check to see if MajorEngineVersion property is set internal bool IsSetMajorEngineVersion() { return this.majorEngineVersion != null; } /// <summary> /// Indicates what options are available in the option group. /// /// </summary> public List<Option> Options { get { return this.options; } set { this.options = value; } } /// <summary> /// Adds elements to the Options collection /// </summary> /// <param name="options">The values to add to the Options collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroup WithOptions(params Option[] options) { foreach (Option element in options) { this.options.Add(element); } return this; } /// <summary> /// Adds elements to the Options collection /// </summary> /// <param name="options">The values to add to the Options collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroup WithOptions(IEnumerable<Option> options) { foreach (Option element in options) { this.options.Add(element); } return this; } // Check to see if Options property is set internal bool IsSetOptions() { return this.options.Count > 0; } /// <summary> /// Indicates whether this option group can be applied to both VPC and non-VPC instances. The value 'true' indicates the option group can be /// applied to both VPC and non-VPC instances. /// /// </summary> public bool AllowsVpcAndNonVpcInstanceMemberships { get { return this.allowsVpcAndNonVpcInstanceMemberships ?? default(bool); } set { this.allowsVpcAndNonVpcInstanceMemberships = value; } } /// <summary> /// Sets the AllowsVpcAndNonVpcInstanceMemberships property /// </summary> /// <param name="allowsVpcAndNonVpcInstanceMemberships">The value to set for the AllowsVpcAndNonVpcInstanceMemberships property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroup WithAllowsVpcAndNonVpcInstanceMemberships(bool allowsVpcAndNonVpcInstanceMemberships) { this.allowsVpcAndNonVpcInstanceMemberships = allowsVpcAndNonVpcInstanceMemberships; return this; } // Check to see if AllowsVpcAndNonVpcInstanceMemberships property is set internal bool IsSetAllowsVpcAndNonVpcInstanceMemberships() { return this.allowsVpcAndNonVpcInstanceMemberships.HasValue; } /// <summary> /// If AllowsVpcAndNonVpcInstanceMemberships is 'false', this field is blank. If AllowsVpcAndNonVpcInstanceMemberships is 'true' and this field /// is blank, then this option group can be applied to both VPC and non-VPC instances. If this field contains a value, then this option group /// can only be applied to instances that are in the VPC indicated by this field. /// /// </summary> public string VpcId { get { return this.vpcId; } set { this.vpcId = value; } } /// <summary> /// Sets the VpcId property /// </summary> /// <param name="vpcId">The value to set for the VpcId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroup WithVpcId(string vpcId) { this.vpcId = vpcId; return this; } // Check to see if VpcId property is set internal bool IsSetVpcId() { return this.vpcId != null; } } }
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 TerribleWebApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Linq; using Baseline; using Marten.Events; using Marten.Schema; using Marten.Testing.Documents; using Marten.Testing.Events; using Shouldly; using Xunit; using Issue = Marten.Testing.Documents.Issue; namespace Marten.Testing.Schema { public class DocumentSchemaOnOtherSchemaTests : IntegratedFixture { private readonly string _binAllsql = AppContext.BaseDirectory.AppendPath("bin", "allsql"); private readonly string _binAllsql2 = AppContext.BaseDirectory.AppendPath("bin", "allsql2"); private IDocumentSchema theSchema => theStore.Schema; public DocumentSchemaOnOtherSchemaTests() { StoreOptions(_ => _.DatabaseSchemaName = "other"); } [Fact] public void generate_ddl() { theStore.Tenancy.Default.StorageFor(typeof(User)); theStore.Tenancy.Default.StorageFor(typeof(Issue)); theStore.Tenancy.Default.StorageFor(typeof(Company)); var sql = theSchema.ToDDL(); sql.ShouldContain("CREATE OR REPLACE FUNCTION other.mt_upsert_user"); sql.ShouldContain("CREATE OR REPLACE FUNCTION other.mt_upsert_issue"); sql.ShouldContain("CREATE OR REPLACE FUNCTION other.mt_upsert_company"); sql.ShouldContain("CREATE TABLE other.mt_doc_user"); sql.ShouldContain("CREATE TABLE other.mt_doc_issue"); sql.ShouldContain("CREATE TABLE other.mt_doc_company"); } [Fact] public void do_not_write_event_sql_if_the_event_graph_is_not_active() { theStore.Events.IsActive(null).ShouldBeFalse(); theSchema.ToDDL().ShouldNotContain("other.mt_streams"); } [Fact] public void do_write_the_event_sql_if_the_event_graph_is_active() { theStore.Events.AddEventType(typeof(MembersJoined)); theStore.Events.IsActive(null).ShouldBeTrue(); theSchema.ToDDL().ShouldContain("other.mt_streams"); } [Fact] public void builds_schema_objects_on_the_fly_as_needed() { theStore.Tenancy.Default.StorageFor(typeof(User)).ShouldNotBeNull(); theStore.Tenancy.Default.StorageFor(typeof(Issue)).ShouldNotBeNull(); theStore.Tenancy.Default.StorageFor(typeof(Company)).ShouldNotBeNull(); var tables = theStore.Tenancy.Default.DbObjects.SchemaTables(); tables.ShouldContain("other.mt_doc_user"); tables.ShouldContain("other.mt_doc_issue"); tables.ShouldContain("other.mt_doc_company"); var functions = theStore.Tenancy.Default.DbObjects.Functions(); functions.ShouldContain("other.mt_upsert_user"); functions.ShouldContain("other.mt_upsert_issue"); functions.ShouldContain("other.mt_upsert_company"); } [Fact] public void do_not_rebuild_a_table_that_already_exists() { using (var store = TestingDocumentStore.Basic()) { using (var session = store.LightweightSession()) { session.Store(new User()); session.Store(new User()); session.Store(new User()); session.SaveChanges(); } } using (var store = DocumentStore.For(_ => { _.Connection(ConnectionSource.ConnectionString); })) { using (var session = store.LightweightSession()) { session.Query<User>().Count().ShouldBeGreaterThanOrEqualTo(3); } } } [Fact] public void throw_ambigous_alias_exception_when_you_have_duplicate_document_aliases() { using (var store = TestingDocumentStore.Basic()) { var storage = store.Storage; storage.StorageFor(typeof(Examples.User)).ShouldNotBeNull(); Exception<AmbiguousDocumentTypeAliasesException>.ShouldBeThrownBy(() => { storage.StorageFor(typeof(User)); }); } } [Fact] public void can_write_ddl_by_type_with_schema_creation() { using (var store = DocumentStore.For(_ => { _.DatabaseSchemaName = "yet_another"; _.RegisterDocumentType<Company>(); _.Schema.For<User>().DatabaseSchemaName("other"); _.Events.DatabaseSchemaName = "event_store"; _.Events.EventMappingFor<MembersJoined>(); _.Connection(ConnectionSource.ConnectionString); })) { store.Schema.WriteDDLByType(_binAllsql); } string filename = _binAllsql.AppendPath("all.sql"); var fileSystem = new FileSystem(); fileSystem.FileExists(filename).ShouldBeTrue(); var contents = fileSystem.ReadStringFromFile(filename); contents.ShouldContain("CREATE SCHEMA event_store"); contents.ShouldContain("CREATE SCHEMA other"); contents.ShouldContain("CREATE SCHEMA yet_another"); } [Fact] public void write_ddl_by_type_generates_the_all_sql_script() { using (var store = DocumentStore.For(_ => { _.RegisterDocumentType<User>(); _.RegisterDocumentType<Company>(); _.RegisterDocumentType<Issue>(); _.DatabaseSchemaName = "yet_another"; _.Schema.For<User>().DatabaseSchemaName("other"); _.Events.AddEventType(typeof(MembersJoined)); _.Connection(ConnectionSource.ConnectionString); })) { store.Schema.WriteDDLByType(_binAllsql); } var filename = _binAllsql.AppendPath("all.sql"); var lines = new FileSystem().ReadStringFromFile(filename).ReadLines().Select(x => x.Trim()).ToArray(); // should create the schemas too lines.ShouldContain("EXECUTE 'CREATE SCHEMA yet_another';"); lines.ShouldContain("EXECUTE 'CREATE SCHEMA other';"); lines.ShouldContain("\\i user.sql"); lines.ShouldContain("\\i company.sql"); lines.ShouldContain("\\i issue.sql"); lines.ShouldContain("\\i eventstore.sql"); } [Fact] public void write_ddl_by_type_with_no_events() { using (var store = DocumentStore.For(_ => { _.RegisterDocumentType<User>(); _.RegisterDocumentType<Company>(); _.RegisterDocumentType<Issue>(); _.Connection(ConnectionSource.ConnectionString); })) { store.Events.IsActive(null).ShouldBeFalse(); store.Schema.WriteDDLByType(_binAllsql); } var fileSystem = new FileSystem(); fileSystem.FindFiles(_binAllsql, FileSet.Shallow("*mt_streams.sql")) .Any().ShouldBeFalse(); } [Fact] public void write_ddl_by_type_with_events() { using (var store = DocumentStore.For(_ => { _.RegisterDocumentType<User>(); _.RegisterDocumentType<Company>(); _.RegisterDocumentType<Issue>(); _.Events.AddEventType(typeof(MembersJoined)); _.Connection(ConnectionSource.ConnectionString); })) { store.Events.IsActive(null).ShouldBeTrue(); store.Schema.WriteDDLByType(_binAllsql); } var fileSystem = new FileSystem(); fileSystem.FindFiles(_binAllsql, FileSet.Shallow("eventstore.sql")) .Any().ShouldBeTrue(); fileSystem.FindFiles(_binAllsql, FileSet.Shallow(".sql")) .Any().ShouldBeFalse(); } [Fact] public void fixing_bug_343_double_export_of_events() { using (var store = DocumentStore.For(_ => { _.RegisterDocumentType<User>(); _.RegisterDocumentType<Company>(); _.RegisterDocumentType<Issue>(); _.Events.AddEventType(typeof(MembersJoined)); _.Connection(ConnectionSource.ConnectionString); })) { store.Events.IsActive(null).ShouldBeTrue(); store.Schema.WriteDDLByType(_binAllsql); } var fileSystem = new FileSystem(); fileSystem.FindFiles(_binAllsql, FileSet.Shallow(".sql")) .Any().ShouldBeFalse(); } [Fact] public void resolve_a_document_mapping_for_an_event_type() { StoreOptions(_ => { _.Events.AddEventType(typeof(RaceStarted)); }); theStore.Tenancy.Default.MappingFor(typeof(RaceStarted)).ShouldBeOfType<EventMapping<RaceStarted>>() .DocumentType.ShouldBe(typeof(RaceStarted)); } [Fact] public void resolve_storage_for_event_type() { theStore.Events.AddEventType(typeof(RaceStarted)); theStore.Tenancy.Default.StorageFor(typeof(RaceStarted)).ShouldBeOfType<EventMapping<RaceStarted>>() .DocumentType.ShouldBe(typeof(RaceStarted)); } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using NUnit.Framework.Interfaces; using NUnit.TestData.OneTimeSetUpTearDownData; using NUnit.TestUtilities; using NUnit.TestData.TestFixtureTests; namespace NUnit.Framework.Internal { /// <summary> /// Tests of the NUnitTestFixture class /// </summary> [TestFixture] public class TestFixtureTests { private static string dataAssembly = "nunit.testdata"; private static void CanConstructFrom(Type fixtureType) { CanConstructFrom(fixtureType, fixtureType.Name); } private static void CanConstructFrom(Type fixtureType, string expectedName) { TestSuite fixture = TestBuilder.MakeFixture(fixtureType); Assert.AreEqual(expectedName, fixture.Name); Assert.AreEqual(fixtureType.FullName, fixture.FullName); } private static Type GetTestDataType(string typeName) { string qualifiedName = string.Format("{0},{1}", typeName, dataAssembly); Type type = Type.GetType(qualifiedName); return type; } [Test] public void ConstructFromType() { CanConstructFrom(typeof(FixtureWithTestFixtureAttribute)); } [Test] public void ConstructFromNestedType() { CanConstructFrom(typeof(OuterClass.NestedTestFixture), "OuterClass+NestedTestFixture"); } [Test] public void ConstructFromDoublyNestedType() { CanConstructFrom(typeof(OuterClass.NestedTestFixture.DoublyNestedTestFixture), "OuterClass+NestedTestFixture+DoublyNestedTestFixture"); } public void ConstructFromTypeWithoutTestFixtureAttributeContainingTest() { CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTest)); } [Test] public void ConstructFromTypeWithoutTestFixtureAttributeContainingTestCase() { CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTestCase)); } [Test] public void ConstructFromTypeWithoutTestFixtureAttributeContainingTestCaseSource() { CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTestCaseSource)); } #if !NETCF && !SILVERLIGHT && !PORTABLE [Test] public void ConstructFromTypeWithoutTestFixtureAttributeContainingTheory() { CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTheory)); } #endif [Test] public void CannotRunConstructorWithArgsNotSupplied() { TestAssert.IsNotRunnable(typeof(NoDefaultCtorFixture)); } [Test] public void CanRunConstructorWithArgsSupplied() { TestAssert.IsRunnable(typeof(FixtureWithArgsSupplied)); } [Test] public void BadConstructorRunsWithSetUpError() { var result = TestBuilder.RunTestFixture(typeof(BadCtorFixture)); Assert.That(result.ResultState, Is.EqualTo(ResultState.SetUpError)); } [Test] public void CanRunMultipleSetUp() { TestAssert.IsRunnable(typeof(MultipleSetUpAttributes)); } [Test] public void CanRunMultipleTearDown() { TestAssert.IsRunnable(typeof(MultipleTearDownAttributes)); } [Test] public void FixtureUsingIgnoreAttributeIsIgnored() { TestSuite suite = TestBuilder.MakeFixture(typeof(FixtureUsingIgnoreAttribute)); Assert.AreEqual(RunState.Ignored, suite.RunState); Assert.AreEqual("testing ignore a fixture", suite.Properties.Get(PropertyNames.SkipReason)); } [Test] public void FixtureUsingIgnorePropertyIsIgnored() { TestSuite suite = TestBuilder.MakeFixture(typeof(FixtureUsingIgnoreProperty)); Assert.AreEqual(RunState.Ignored, suite.RunState); Assert.AreEqual("testing ignore a fixture", suite.Properties.Get(PropertyNames.SkipReason)); } [Test] public void FixtureUsingIgnoreReasonPropertyIsIgnored() { TestSuite suite = TestBuilder.MakeFixture(typeof(FixtureUsingIgnoreReasonProperty)); Assert.AreEqual(RunState.Ignored, suite.RunState); Assert.AreEqual("testing ignore a fixture", suite.Properties.Get(PropertyNames.SkipReason)); } // [Test] // public void CannotRunAbstractFixture() // { // TestAssert.IsNotRunnable(typeof(AbstractTestFixture)); // } [Test] public void CanRunFixtureDerivedFromAbstractTestFixture() { TestAssert.IsRunnable(typeof(DerivedFromAbstractTestFixture)); } [Test] public void CanRunFixtureDerivedFromAbstractDerivedTestFixture() { TestAssert.IsRunnable(typeof(DerivedFromAbstractDerivedTestFixture)); } // [Test] // public void CannotRunAbstractDerivedFixture() // { // TestAssert.IsNotRunnable(typeof(AbstractDerivedTestFixture)); // } [Test] public void FixtureInheritingTwoTestFixtureAttributesIsLoadedOnlyOnce() { TestSuite suite = TestBuilder.MakeFixture(typeof(DoubleDerivedClassWithTwoInheritedAttributes)); Assert.That(suite, Is.TypeOf(typeof(TestFixture))); Assert.That(suite.Tests.Count, Is.EqualTo(0)); } [Test] public void CanRunMultipleTestFixtureSetUp() { TestAssert.IsRunnable(typeof(MultipleFixtureSetUpAttributes)); } [Test] public void CanRunMultipleTestFixtureTearDown() { TestAssert.IsRunnable(typeof(MultipleFixtureTearDownAttributes)); } [Test] public void CanRunTestFixtureWithNoTests() { TestAssert.IsRunnable(typeof(FixtureWithNoTests)); } [Test] public void ConstructFromStaticTypeWithoutTestFixtureAttribute() { CanConstructFrom(typeof(StaticFixtureWithoutTestFixtureAttribute)); } [Test] public void CanRunStaticFixture() { TestAssert.IsRunnable(typeof(StaticFixtureWithoutTestFixtureAttribute)); } [Test] public void CanRunGenericFixtureWithProperArgsProvided() { TestSuite suite = TestBuilder.MakeFixture(typeof(GenericFixtureWithProperArgsProvided<>)); // GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureWithProperArgsProvided`1")); Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(suite is ParameterizedFixtureSuite); Assert.That(suite.Tests.Count, Is.EqualTo(2)); } // [Test] // public void CannotRunGenericFixtureWithNoTestFixtureAttribute() // { // TestSuite suite = TestBuilder.MakeFixture( // GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureWithNoTestFixtureAttribute`1")); // // Assert.That(suite.RunState, Is.EqualTo(RunState.NotRunnable)); // Assert.That(suite.Properties.Get(PropertyNames.SkipReason), // Does.StartWith("Fixture type contains generic parameters")); // } [Test] public void CannotRunGenericFixtureWithNoArgsProvided() { TestSuite suite = TestBuilder.MakeFixture(typeof(GenericFixtureWithNoArgsProvided<>)); // GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureWithNoArgsProvided`1")); Test fixture = (Test)suite.Tests[0]; Assert.That(fixture.RunState, Is.EqualTo(RunState.NotRunnable)); Assert.That((string)fixture.Properties.Get(PropertyNames.SkipReason), Does.StartWith("Fixture type contains generic parameters")); } [Test] public void CannotRunGenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided() { TestSuite suite = TestBuilder.MakeFixture(typeof(GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided<>)); // GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided`1")); TestAssert.IsNotRunnable((Test)suite.Tests[0]); } [Test] public void CanRunGenericFixtureDerivedFromAbstractFixtureWithArgsProvided() { TestSuite suite = TestBuilder.MakeFixture(typeof(GenericFixtureDerivedFromAbstractFixtureWithArgsProvided<>)); // GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureDerivedFromAbstractFixtureWithArgsProvided`1")); Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(suite is ParameterizedFixtureSuite); Assert.That(suite.Tests.Count, Is.EqualTo(2)); } #region SetUp Signature [Test] public void CannotRunPrivateSetUp() { TestAssert.IsNotRunnable(typeof(PrivateSetUp)); } [Test] public void CanRunProtectedSetUp() { TestAssert.IsRunnable(typeof(ProtectedSetUp)); } /// <summary> /// Determines whether this instance [can run static set up]. /// </summary> [Test] public void CanRunStaticSetUp() { TestAssert.IsRunnable(typeof(StaticSetUp)); } [Test] public void CannotRunSetupWithReturnValue() { TestAssert.IsNotRunnable(typeof(SetUpWithReturnValue)); } [Test] public void CannotRunSetupWithParameters() { TestAssert.IsNotRunnable(typeof(SetUpWithParameters)); } #endregion #region TearDown Signature [Test] public void CannotRunPrivateTearDown() { TestAssert.IsNotRunnable(typeof(PrivateTearDown)); } [Test] public void CanRunProtectedTearDown() { TestAssert.IsRunnable(typeof(ProtectedTearDown)); } [Test] public void CanRunStaticTearDown() { TestAssert.IsRunnable(typeof(StaticTearDown)); } [Test] public void CannotRunTearDownWithReturnValue() { TestAssert.IsNotRunnable(typeof(TearDownWithReturnValue)); } [Test] public void CannotRunTearDownWithParameters() { TestAssert.IsNotRunnable(typeof(TearDownWithParameters)); } #endregion #region TestFixtureSetUp Signature [Test] public void CannotRunPrivateFixtureSetUp() { TestAssert.IsNotRunnable(typeof(PrivateFixtureSetUp)); } [Test] public void CanRunProtectedFixtureSetUp() { TestAssert.IsRunnable(typeof(ProtectedFixtureSetUp)); } [Test] public void CanRunStaticFixtureSetUp() { TestAssert.IsRunnable(typeof(StaticFixtureSetUp)); } [Test] public void CannotRunFixtureSetupWithReturnValue() { TestAssert.IsNotRunnable(typeof(FixtureSetUpWithReturnValue)); } [Test] public void CannotRunFixtureSetupWithParameters() { TestAssert.IsNotRunnable(typeof(FixtureSetUpWithParameters)); } #endregion #region TestFixtureTearDown Signature [Test] public void CannotRunPrivateFixtureTearDown() { TestAssert.IsNotRunnable(typeof(PrivateFixtureTearDown)); } [Test] public void CanRunProtectedFixtureTearDown() { TestAssert.IsRunnable(typeof(ProtectedFixtureTearDown)); } [Test] public void CanRunStaticFixtureTearDown() { TestAssert.IsRunnable(typeof(StaticFixtureTearDown)); } // [TestFixture] // [Category("fixture category")] // [Category("second")] // private class HasCategories // { // [Test] public void OneTest() // {} // } // // [Test] // public void LoadCategories() // { // TestSuite fixture = LoadFixture("NUnit.Core.Tests.TestFixtureBuilderTests+HasCategories"); // Assert.IsNotNull(fixture); // Assert.AreEqual(2, fixture.Categories.Count); // } [Test] public void CannotRunFixtureTearDownWithReturnValue() { TestAssert.IsNotRunnable(typeof(FixtureTearDownWithReturnValue)); } [Test] public void CannotRunFixtureTearDownWithParameters() { TestAssert.IsNotRunnable(typeof(FixtureTearDownWithParameters)); } #endregion #region Issue 318 - Test Fixture is null on ITest objects public class FixtureNotNullTestAttribute : TestActionAttribute { private readonly string _location; public FixtureNotNullTestAttribute(string location) { _location = location; } public override void BeforeTest(ITest test) { Assert.That(test, Is.Not.Null, "ITest is null on a " + _location); Assert.That(test.Fixture, Is.Not.Null, "ITest.Fixture is null on a " + _location); Assert.That(test.Fixture.GetType(), Is.EqualTo(test.FixtureType), "ITest.Fixture is not the correct type on a " + _location); } } [FixtureNotNullTest("TestFixture class")] [TestFixture] public class FixtureIsNotNullForTests { [FixtureNotNullTest("Test method")] [Test] public void TestMethod() { } [FixtureNotNullTest("TestCase method")] [TestCase(1)] public void TestCaseMethod(int i) { } } #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. //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // RuntimeHelpers // This class defines a set of static methods that provide support for compilers. // // namespace System.Runtime.CompilerServices { using System; using System.Security; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Security.Permissions; using System.Threading; using System.Runtime.Versioning; using System.Diagnostics.Contracts; public static class RuntimeHelpers { [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void InitializeArray(Array array,RuntimeFieldHandle fldHandle); // GetObjectValue is intended to allow value classes to be manipulated as 'Object' // but have aliasing behavior of a value class. The intent is that you would use // this function just before an assignment to a variable of type 'Object'. If the // value being assigned is a mutable value class, then a shallow copy is returned // (because value classes have copy semantics), but otherwise the object itself // is returned. // // Note: VB calls this method when they're about to assign to an Object // or pass it as a parameter. The goal is to make sure that boxed // value types work identical to unboxed value types - ie, they get // cloned when you pass them around, and are always passed by value. // Of course, reference types are not cloned. // [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern Object GetObjectValue(Object obj); // RunClassConstructor causes the class constructor for the given type to be triggered // in the current domain. After this call returns, the class constructor is guaranteed to // have at least been started by some thread. In the absence of class constructor // deadlock conditions, the call is further guaranteed to have completed. // // This call will generate an exception if the specified class constructor threw an // exception when it ran. [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _RunClassConstructor(RuntimeType type); public static void RunClassConstructor(RuntimeTypeHandle type) { _RunClassConstructor(type.GetRuntimeType()); } // RunModuleConstructor causes the module constructor for the given type to be triggered // in the current domain. After this call returns, the module constructor is guaranteed to // have at least been started by some thread. In the absence of module constructor // deadlock conditions, the call is further guaranteed to have completed. // // This call will generate an exception if the specified module constructor threw an // exception when it ran. [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _RunModuleConstructor(System.Reflection.RuntimeModule module); public static void RunModuleConstructor(ModuleHandle module) { _RunModuleConstructor(module.GetRuntimeModule()); } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern void _PrepareMethod(IRuntimeMethodInfo method, IntPtr* pInstantiation, int cInstantiation); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern void _CompileMethod(IRuntimeMethodInfo method); // Simple (instantiation not required) method. [System.Security.SecurityCritical] // auto-generated_required public static void PrepareMethod(RuntimeMethodHandle method) { unsafe { _PrepareMethod(method.GetMethodInfo(), null, 0); } } // Generic method or method with generic class with specific instantiation. [System.Security.SecurityCritical] // auto-generated_required public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation) { unsafe { int length; IntPtr[] instantiationHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(instantiation, out length); fixed (IntPtr* pInstantiation = instantiationHandles) { _PrepareMethod(method.GetMethodInfo(), pInstantiation, length); GC.KeepAlive(instantiation); } } } // This method triggers a given delegate to be prepared. This involves preparing the // delegate's Invoke method and preparing the target of that Invoke. In the case of // a multi-cast delegate, we rely on the fact that each individual component was prepared // prior to the Combine. In other words, this service does not navigate through the // entire multicasting list. // If our own reliable event sinks perform the Combine (for example AppDomain.DomainUnload), // then the result is fully prepared. But if a client calls Combine himself and then // then adds that combination to e.g. AppDomain.DomainUnload, then the client is responsible // for his own preparation. [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void PrepareDelegate(Delegate d); // See comment above for PrepareDelegate // // PrepareContractedDelegate weakens this a bit by only assuring that we prepare // delegates which also have a ReliabilityContract. This is useful for services that // want to provide opt-in reliability, generally some random event sink providing // always reliable semantics to random event handlers that are likely to have not // been written with relability in mind is a lost cause anyway. // // NOTE: that for the NGen case you can sidestep the required ReliabilityContract // by using the [PrePrepareMethod] attribute. [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void PrepareContractedDelegate(Delegate d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int GetHashCode(Object o); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public new static extern bool Equals(Object o1, Object o2); public static int OffsetToStringData { // This offset is baked in by string indexer intrinsic, so there is no harm // in getting it baked in here as well. [System.Runtime.Versioning.NonVersionable] get { // Number of bytes from the address pointed to by a reference to // a String to the first 16-bit character in the String. Skip // over the MethodTable pointer, & String // length. Of course, the String reference points to the memory // after the sync block, so don't count that. // This property allows C#'s fixed statement to work on Strings. // On 64 bit platforms, this should be 12 (8+4) and on 32 bit 8 (4+4). #if WIN32 return 8; #else return 12; #endif // WIN32 } } // This method ensures that there is sufficient stack to execute the average Framework function. // If there is not enough stack, then it throws System.InsufficientExecutionStackException. // Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack // below. [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static extern void EnsureSufficientExecutionStack(); #if FEATURE_CORECLR // This method ensures that there is sufficient stack to execute the average Framework function. // If there is not enough stack, then it return false. // Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack // below. [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static extern bool TryEnsureSufficientExecutionStack(); #endif [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static extern void ProbeForSufficientStack(); // This method is a marker placed immediately before a try clause to mark the corresponding catch and finally blocks as // constrained. There's no code here other than the probe because most of the work is done at JIT time when we spot a call to this routine. [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static void PrepareConstrainedRegions() { ProbeForSufficientStack(); } // When we detect a CER with no calls, we can point the JIT to this non-probing version instead // as we don't need to probe. [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static void PrepareConstrainedRegionsNoOP() { } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public delegate void TryCode(Object userData); #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public delegate void CleanupCode(Object userData, bool exceptionThrown); [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData); #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif [PrePrepareMethod] internal static void ExecuteBackoutCodeHelper(Object backoutCode, Object userData, bool exceptionThrown) { ((CleanupCode)backoutCode)(userData, exceptionThrown); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: BinaryReader ** ** <OWNER>gpaperin</OWNER> ** ** ** Purpose: Wraps a stream and provides convenient read functionality ** for strings and primitive types. ** ** ============================================================*/ /* * https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/io/binaryreader.cs */ using System; using System.Runtime; using System.Text; using System.Globalization; using System.Diagnostics.Contracts; using System.Security; namespace System.IO { public class BinaryReader : IDisposable { private const int MaxCharBytesSize = 128; private Stream m_stream; private byte[] m_buffer; private Encoding m_encoding; private byte[] m_charBytes; private char[] m_singleChar; private char[] m_charBuffer; private int m_maxCharsSize; // From MaxCharBytesSize & Encoding // Performance optimization for Read() w/ Unicode. Speeds us up by ~40% private bool m_2BytesPerChar; private bool m_isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf private bool m_leaveOpen; public BinaryReader(Stream input) : this(input, new UTF8Encoding(), false) { } public BinaryReader(Stream input, Encoding encoding) : this(input, encoding, false) { } public BinaryReader(Stream input, Encoding encoding, bool leaveOpen) { if (input == null) { throw new ArgumentNullException("input"); } if (encoding == null) { throw new ArgumentNullException("encoding"); } if (!input.CanRead) throw new ArgumentException("Argument_StreamNotReadable"); Contract.EndContractBlock(); m_stream = input; m_encoding = encoding; m_maxCharsSize = encoding.GetMaxCharCount(MaxCharBytesSize); int minBufferSize = encoding.GetMaxByteCount(1); // max bytes per one char if (minBufferSize < 23) minBufferSize = 23; m_buffer = new byte[minBufferSize]; // m_charBuffer and m_charBytes will be left null. // For Encodings that always use 2 bytes per char (or more), // special case them here to make Read() & Peek() faster. m_2BytesPerChar = encoding is UnicodeEncoding; // check if BinaryReader is based on MemoryStream, and keep this for it's life // we cannot use "as" operator, since derived classes are not allowed m_isMemoryStream = (m_stream.GetType() == typeof(MemoryStream)); m_leaveOpen = leaveOpen; Contract.Assert(m_encoding != null, "[BinaryReader.ctor]m_encoding!=null"); } public virtual Stream BaseStream { get { return m_stream; } } public virtual void Close() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { Stream copyOfStream = m_stream; m_stream = null; if (copyOfStream != null && !m_leaveOpen) copyOfStream.Close(); } m_stream = null; m_buffer = null; m_encoding = null; m_charBytes = null; m_singleChar = null; m_charBuffer = null; } public void Dispose() { Dispose(true); } public virtual int PeekChar() { Contract.Ensures(Contract.Result<int>() >= -1); if (m_stream == null) __Error.FileNotOpen(); if (!m_stream.CanSeek) return -1; long origPos = m_stream.Position; int ch = Read(); m_stream.Position = origPos; return ch; } public virtual int Read() { Contract.Ensures(Contract.Result<int>() >= -1); if (m_stream == null) { __Error.FileNotOpen(); } return InternalReadOneChar(); } public virtual bool ReadBoolean() { FillBuffer(1); return (m_buffer[0] != 0); } public virtual byte ReadByte() { // Inlined to avoid some method call overhead with FillBuffer. if (m_stream == null) __Error.FileNotOpen(); int b = m_stream.ReadByte(); if (b == -1) __Error.EndOfFile(); return (byte)b; } [CLSCompliant(false)] public virtual sbyte ReadSByte() { FillBuffer(1); return (sbyte)(m_buffer[0]); } public virtual char ReadChar() { int value = Read(); if (value == -1) { __Error.EndOfFile(); } return (char)value; } public virtual short ReadInt16() { FillBuffer(2); return (short)(m_buffer[0] | m_buffer[1] << 8); } [CLSCompliant(false)] public virtual ushort ReadUInt16() { FillBuffer(2); return (ushort)(m_buffer[0] | m_buffer[1] << 8); } public virtual int ReadInt32() { if (m_isMemoryStream) { if (m_stream == null) __Error.FileNotOpen(); // read directly from MemoryStream buffer MemoryStream mStream = m_stream as MemoryStream; Contract.Assert(mStream != null, "m_stream as MemoryStream != null"); return mStream.InternalReadInt32(); } else { FillBuffer(4); return (int)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); } } [CLSCompliant(false)] public virtual uint ReadUInt32() { FillBuffer(4); return (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); } public virtual long ReadInt64() { FillBuffer(8); uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 | m_buffer[6] << 16 | m_buffer[7] << 24); return (long)((ulong)hi) << 32 | lo; } [CLSCompliant(false)] public virtual ulong ReadUInt64() { FillBuffer(8); uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 | m_buffer[6] << 16 | m_buffer[7] << 24); return ((ulong)hi) << 32 | lo; } public virtual float ReadSingle() { FillBuffer(4); uint tmpBuffer = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); return BitConverter.ToSingle(BitConverter.GetBytes(tmpBuffer), 0); } public virtual double ReadDouble() { FillBuffer(8); uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 | m_buffer[6] << 16 | m_buffer[7] << 24); ulong tmpBuffer = ((ulong)hi) << 32 | lo; return BitConverter.ToDouble(BitConverter.GetBytes(tmpBuffer), 0); } public virtual decimal ReadDecimal() { FillBuffer(23); try { return Decimal.FromBytes(m_buffer); } catch (ArgumentException e) { // ReadDecimal cannot leak out ArgumentException throw new IOException("Arg_DecBitCtor", e); } } public virtual String ReadString() { Contract.Ensures(Contract.Result<String>() != null); if (m_stream == null) __Error.FileNotOpen(); int currPos = 0; int n; int stringLength; int readLength; int charsRead; // Length of the string in bytes, not chars stringLength = Read7BitEncodedInt(); if (stringLength < 0) { throw new IOException("IO.IO_InvalidStringLen_Len"); } if (stringLength == 0) { return String.Empty; } if (m_charBytes == null) { m_charBytes = new byte[MaxCharBytesSize]; } if (m_charBuffer == null) { m_charBuffer = new char[m_maxCharsSize]; } StringBuilder sb = null; do { readLength = ((stringLength - currPos) > MaxCharBytesSize) ? MaxCharBytesSize : (stringLength - currPos); n = m_stream.Read(m_charBytes, 0, readLength); if (n == 0) { __Error.EndOfFile(); } charsRead = m_encoding.GetChars(m_charBytes, 0, n, m_charBuffer, 0); if (currPos == 0 && n == stringLength) return new String(m_charBuffer, 0, charsRead); if (sb == null) { sb = new StringBuilder(stringLength); } for (int i = 0; i < charsRead; i++) { sb.Append(m_charBuffer[i]); } currPos += n; } while (currPos < stringLength); return sb.ToString(); } public virtual int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer", "ArgumentNull_Buffer"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", "ArgumentOutOfRange_NeedNonNegNum"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", "ArgumentOutOfRange_NeedNonNegNum"); } if (buffer.Length - index < count) { throw new ArgumentException("Argument_InvalidOffLen"); } Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= count); Contract.EndContractBlock(); if (m_stream == null) __Error.FileNotOpen(); // SafeCritical: index and count have already been verified to be a valid range for the buffer return InternalReadChars(buffer, index, count); } private int InternalReadChars(char[] buffer, int index, int count) { Contract.Requires(buffer != null); Contract.Requires(index >= 0 && count >= 0); Contract.Assert(m_stream != null); int charsRemaining = count; if (m_charBytes == null) { m_charBytes = new byte[MaxCharBytesSize]; } if (index < 0 || charsRemaining < 0 || index + charsRemaining > buffer.Length) { throw new ArgumentOutOfRangeException("charsRemaining"); } while (charsRemaining > 0) { var ch = this.InternalReadOneChar(true); if (ch == -1) { break; } buffer[index] = (char)ch; if (lastCharsRead == 2) { buffer[++index] = m_singleChar[1]; charsRemaining--; } charsRemaining--; index++; } // this should never fail Contract.Assert(charsRemaining >= 0, "We read too many characters."); // we may have read fewer than the number of characters requested if end of stream reached // or if the encoding makes the char count too big for the buffer (e.g. fallback sequence) return (count - charsRemaining); } private int lastCharsRead = 0; private int InternalReadOneChar(bool allowSurrogate = false) { // I know having a separate InternalReadOneChar method seems a little // redundant, but this makes a scenario like the security parser code // 20% faster, in addition to the optimizations for UnicodeEncoding I // put in InternalReadChars. int charsRead = 0; int numBytes = 0; long posSav = 0; if (m_stream.CanSeek) posSav = m_stream.Position; if (m_charBytes == null) { m_charBytes = new byte[MaxCharBytesSize]; // } if (m_singleChar == null) { m_singleChar = new char[2]; } var addByte = false; var internalPos = 0; while (charsRead == 0) { numBytes = m_2BytesPerChar ? 2 : 1; if (m_encoding is UTF32Encoding) { numBytes = 4; } if (addByte) { int r = m_stream.ReadByte(); m_charBytes[++internalPos] = (byte)r; if (r == -1) numBytes = 0; if (numBytes == 2) { r = m_stream.ReadByte(); m_charBytes[++internalPos] = (byte)r; if (r == -1) numBytes = 1; } } else { int r = m_stream.ReadByte(); m_charBytes[0] = (byte)r; internalPos = 0; if (r == -1) numBytes = 0; if (numBytes == 2) { r = m_stream.ReadByte(); m_charBytes[1] = (byte)r; if (r == -1) numBytes = 1; internalPos = 1; } else if (numBytes == 4) { r = m_stream.ReadByte(); m_charBytes[1] = (byte)r; if (r == -1) { return -1; } r = m_stream.ReadByte(); m_charBytes[2] = (byte)r; if (r == -1) { return -1; } r = m_stream.ReadByte(); m_charBytes[3] = (byte)r; if (r == -1) { return -1; } internalPos = 3; } } if (numBytes == 0) { return -1; } addByte = false; try { charsRead = m_encoding.GetChars(m_charBytes, 0, internalPos + 1, m_singleChar, 0); if (!allowSurrogate && charsRead == 2) { throw new ArgumentException(); } } catch { // Handle surrogate char if (m_stream.CanSeek) m_stream.Seek((posSav - m_stream.Position), SeekOrigin.Current); // else - we can't do much here throw; } if (m_encoding._hasError) { charsRead = 0; addByte = true; } if (!allowSurrogate) { Contract.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!"); } } lastCharsRead = charsRead; if (charsRead == 0) { return -1; } return m_singleChar[0]; } public virtual char[] ReadChars(int count) { if (count < 0) { throw new ArgumentOutOfRangeException("count", "ArgumentOutOfRange_NeedNonNegNum"); } Contract.Ensures(Contract.Result<char[]>() != null); Contract.Ensures(Contract.Result<char[]>().Length <= count); Contract.EndContractBlock(); if (m_stream == null) { __Error.FileNotOpen(); } if (count == 0) { return new char[0]; } // SafeCritical: we own the chars buffer, and therefore can guarantee that the index and count are valid char[] chars = new char[count]; int n = InternalReadChars(chars, 0, count); if (n != count) { char[] copy = new char[n]; Array.Copy(chars, 0, copy, 0, 2 * n); // sizeof(char) chars = copy; } return chars; } public virtual int Read(byte[] buffer, int index, int count) { if (buffer == null) throw new ArgumentNullException("buffer", "ArgumentNull_Buffer"); if (index < 0) throw new ArgumentOutOfRangeException("index", "ArgumentOutOfRange_NeedNonNegNum"); if (count < 0) throw new ArgumentOutOfRangeException("count", "ArgumentOutOfRange_NeedNonNegNum"); if (buffer.Length - index < count) throw new ArgumentException("Argument_InvalidOffLen"); Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= count); Contract.EndContractBlock(); if (m_stream == null) __Error.FileNotOpen(); return m_stream.Read(buffer, index, count); } public virtual byte[] ReadBytes(int count) { if (count < 0) throw new ArgumentOutOfRangeException("count", "ArgumentOutOfRange_NeedNonNegNum"); Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length <= Contract.OldValue(count)); Contract.EndContractBlock(); if (m_stream == null) __Error.FileNotOpen(); if (count == 0) { return new byte[0]; } byte[] result = new byte[count]; int numRead = 0; do { int n = m_stream.Read(result, numRead, count); if (n == 0) break; numRead += n; count -= n; } while (count > 0); if (numRead != result.Length) { // Trim array. This should happen on EOF & possibly net streams. byte[] copy = new byte[numRead]; Array.Copy(result, 0, copy, 0, numRead); result = copy; } return result; } protected virtual void FillBuffer(int numBytes) { if (m_buffer != null && (numBytes < 0 || numBytes > m_buffer.Length)) { throw new ArgumentOutOfRangeException("numBytes", "ArgumentOutOfRange_BinaryReaderFillBuffer"); } int bytesRead = 0; int n = 0; if (m_stream == null) __Error.FileNotOpen(); // Need to find a good threshold for calling ReadByte() repeatedly // vs. calling Read(byte[], int, int) for both buffered & unbuffered // streams. if (numBytes == 1) { n = m_stream.ReadByte(); if (n == -1) __Error.EndOfFile(); m_buffer[0] = (byte)n; return; } do { n = m_stream.Read(m_buffer, bytesRead, numBytes - bytesRead); if (n == 0) { __Error.EndOfFile(); } bytesRead += n; } while (bytesRead < numBytes); } internal protected int Read7BitEncodedInt() { // Read out an Int32 7 bits at a time. The high bit // of the byte when on means to continue reading more bytes. int count = 0; int shift = 0; byte b; do { // Check for a corrupted stream. Read a max of 5 bytes. // In a future version, add a DataFormatException. if (shift == 5 * 7) // 5 bytes max per Int32, shift += 7 throw new FormatException("Format_Bad7BitInt32"); // ReadByte handles end of stream cases for us. b = ReadByte(); count |= (b & 0x7F) << shift; shift += 7; } while ((b & 0x80) != 0); return count; } } }
using System; using System.Globalization; using System.Xml; using JetBrains.Annotations; using Orchard.Comments.Models; using Orchard.ContentManagement; using Orchard.ContentManagement.Drivers; using Orchard.ContentManagement.Aspects; using Orchard.Services; using Orchard.Localization; using Orchard.Comments.Services; using Orchard.UI.Notify; namespace Orchard.Comments.Drivers { [UsedImplicitly] public class CommentPartDriver : ContentPartDriver<CommentPart> { private readonly IContentManager _contentManager; private readonly IWorkContextAccessor _workContextAccessor; private readonly IClock _clock; private readonly ICommentService _commentService; private readonly IOrchardServices _orchardServices; protected override string Prefix { get { return "Comments"; } } public Localizer T { get; set; } public CommentPartDriver( IContentManager contentManager, IWorkContextAccessor workContextAccessor, IClock clock, ICommentService commentService, IOrchardServices orchardServices) { _contentManager = contentManager; _workContextAccessor = workContextAccessor; _clock = clock; _commentService = commentService; _orchardServices = orchardServices; T = NullLocalizer.Instance; } protected override DriverResult Display(CommentPart part, string displayType, dynamic shapeHelper) { return Combined( ContentShape("Parts_Comment", () => shapeHelper.Parts_Comment()), ContentShape("Parts_Comment_SummaryAdmin", () => shapeHelper.Parts_Comment_SummaryAdmin()) ); } // GET protected override DriverResult Editor(CommentPart part, dynamic shapeHelper) { if (UI.Admin.AdminFilter.IsApplied(_workContextAccessor.GetContext().HttpContext.Request.RequestContext)) { return ContentShape("Parts_Comment_AdminEdit", () => shapeHelper.EditorTemplate(TemplateName: "Parts.Comment.AdminEdit", Model: part, Prefix: Prefix)); } else { return ContentShape("Parts_Comment_Edit", () => shapeHelper.EditorTemplate(TemplateName: "Parts.Comment", Model: part, Prefix: Prefix)); } } // POST protected override DriverResult Editor(CommentPart part, IUpdateModel updater, dynamic shapeHelper) { updater.TryUpdateModel(part, Prefix, null, null); var workContext = _workContextAccessor.GetContext(); // applying moderate/approve actions var httpContext = workContext.HttpContext; var name = httpContext.Request.Form["submit.Save"]; if (!string.IsNullOrEmpty(name) && String.Equals(name, "moderate", StringComparison.OrdinalIgnoreCase)) { if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) { _commentService.UnapproveComment(part.Id); _orchardServices.Notifier.Information(T("Comment successfully moderated.")); return Editor(part, shapeHelper); } } if (!string.IsNullOrEmpty(name) && String.Equals(name, "approve", StringComparison.OrdinalIgnoreCase)) { if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't approve comment"))) { _commentService.ApproveComment(part.Id); _orchardServices.Notifier.Information(T("Comment approved.")); return Editor(part, shapeHelper); } } if (!string.IsNullOrEmpty(name) && String.Equals(name, "delete", StringComparison.OrdinalIgnoreCase)) { if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment"))) { _commentService.DeleteComment(part.Id); _orchardServices.Notifier.Information(T("Comment successfully deleted.")); return Editor(part, shapeHelper); } } // if editing from the admin, don't update the owner or the status if (!string.IsNullOrEmpty(name) && String.Equals(name, "save", StringComparison.OrdinalIgnoreCase)) { _orchardServices.Notifier.Information(T("Comment saved.")); return Editor(part, shapeHelper); } part.CommentDateUtc = _clock.UtcNow; if (!String.IsNullOrEmpty(part.SiteName) && !part.SiteName.StartsWith("http://") && !part.SiteName.StartsWith("https://")) { part.SiteName = "http://" + part.SiteName; } var currentUser = workContext.CurrentUser; part.UserName = (currentUser != null ? currentUser.UserName : null); if (currentUser != null) part.Author = currentUser.UserName; var moderateComments = workContext.CurrentSite.As<CommentSettingsPart>().Record.ModerateComments; part.Status = moderateComments ? CommentStatus.Pending : CommentStatus.Approved; var commentedOn = _contentManager.Get<ICommonPart>(part.CommentedOn); // prevent users from commenting on a closed thread by hijacking the commentedOn property var commentsPart = commentedOn.As<CommentsPart>(); if (!commentsPart.CommentsActive) { _orchardServices.TransactionManager.Cancel(); return Editor(part, shapeHelper); } if (commentedOn != null && commentedOn.Container != null) { part.CommentedOnContainer = commentedOn.Container.ContentItem.Id; } commentsPart.Record.CommentPartRecords.Add(part.Record); return Editor(part, shapeHelper); } protected override void Importing(CommentPart part, ContentManagement.Handlers.ImportContentContext context) { var author = context.Attribute(part.PartDefinition.Name, "Author"); if (author != null) { part.Record.Author = author; } var siteName = context.Attribute(part.PartDefinition.Name, "SiteName"); if (siteName != null) { part.Record.SiteName = siteName; } var userName = context.Attribute(part.PartDefinition.Name, "UserName"); if (userName != null) { part.Record.UserName = userName; } var email = context.Attribute(part.PartDefinition.Name, "Email"); if (email != null) { part.Record.Email = email; } var position = context.Attribute(part.PartDefinition.Name, "Position"); if (position != null) { part.Record.Position = decimal.Parse(position, CultureInfo.InvariantCulture); } var status = context.Attribute(part.PartDefinition.Name, "Status"); if (status != null) { part.Record.Status = (CommentStatus)Enum.Parse(typeof(CommentStatus), status); } var commentDate = context.Attribute(part.PartDefinition.Name, "CommentDateUtc"); if (commentDate != null) { part.Record.CommentDateUtc = XmlConvert.ToDateTime(commentDate, XmlDateTimeSerializationMode.Utc); } var text = context.Attribute(part.PartDefinition.Name, "CommentText"); if (text != null) { part.Record.CommentText = text; } var commentedOn = context.Attribute(part.PartDefinition.Name, "CommentedOn"); if (commentedOn != null) { var contentItem = context.GetItemFromSession(commentedOn); if (contentItem != null) { part.Record.CommentedOn = contentItem.Id; } contentItem.As<CommentsPart>().Record.CommentPartRecords.Add(part.Record); } var repliedOn = context.Attribute(part.PartDefinition.Name, "RepliedOn"); if (repliedOn != null) { var contentItem = context.GetItemFromSession(repliedOn); if (contentItem != null) { part.Record.RepliedOn = contentItem.Id; } } var commentedOnContainer = context.Attribute(part.PartDefinition.Name, "CommentedOnContainer"); if (commentedOnContainer != null) { var container = context.GetItemFromSession(commentedOnContainer); if (container != null) { part.Record.CommentedOnContainer = container.Id; } } } protected override void Exporting(CommentPart part, ContentManagement.Handlers.ExportContentContext context) { context.Element(part.PartDefinition.Name).SetAttributeValue("Author", part.Record.Author); context.Element(part.PartDefinition.Name).SetAttributeValue("SiteName", part.Record.SiteName); context.Element(part.PartDefinition.Name).SetAttributeValue("UserName", part.Record.UserName); context.Element(part.PartDefinition.Name).SetAttributeValue("Email", part.Record.Email); context.Element(part.PartDefinition.Name).SetAttributeValue("Position", part.Record.Position.ToString(CultureInfo.InvariantCulture)); context.Element(part.PartDefinition.Name).SetAttributeValue("Status", part.Record.Status.ToString()); if (part.Record.CommentDateUtc != null) { context.Element(part.PartDefinition.Name) .SetAttributeValue("CommentDateUtc", XmlConvert.ToString(part.Record.CommentDateUtc.Value, XmlDateTimeSerializationMode.Utc)); } context.Element(part.PartDefinition.Name).SetAttributeValue("CommentText", part.Record.CommentText); var commentedOn = _contentManager.Get(part.Record.CommentedOn); if (commentedOn != null) { var commentedOnIdentity = _contentManager.GetItemMetadata(commentedOn).Identity; context.Element(part.PartDefinition.Name).SetAttributeValue("CommentedOn", commentedOnIdentity.ToString()); } var commentedOnContainer = _contentManager.Get(part.Record.CommentedOnContainer); if (commentedOnContainer != null) { var commentedOnContainerIdentity = _contentManager.GetItemMetadata(commentedOnContainer).Identity; context.Element(part.PartDefinition.Name).SetAttributeValue("CommentedOnContainer", commentedOnContainerIdentity.ToString()); } if (part.Record.RepliedOn.HasValue) { var repliedOn = _contentManager.Get(part.Record.RepliedOn.Value); if (repliedOn != null) { var repliedOnIdentity = _contentManager.GetItemMetadata(repliedOn).Identity; context.Element(part.PartDefinition.Name).SetAttributeValue("RepliedOn", repliedOnIdentity.ToString()); } } } } }
using System; using System.ComponentModel.Design; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Input; using System.Windows.Threading; using Microsoft.VisualStudio; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using NuGetConsole.Implementation.Console; using NuGetConsole.Implementation.PowerConsole; using NuGet.PackageManagement; using NuGet.PackageManagement.VisualStudio; namespace NuGetConsole.Implementation { /// <summary> /// This class implements the tool window. /// </summary> [Guid("0AD07096-BBA9-4900-A651-0598D26F6D24")] public sealed class PowerConsoleToolWindow : ToolWindowPane, IOleCommandTarget, IPowerConsoleService { /// <summary> /// Get VS IComponentModel service. /// </summary> private IComponentModel ComponentModel { get { return this.GetService<IComponentModel>(typeof(SComponentModel)); } } private IProductUpdateService ProductUpdateService { get { return ComponentModel.GetService<IProductUpdateService>(); } } private IPackageRestoreManager PackageRestoreManager { get { return ComponentModel.GetService<IPackageRestoreManager>(); } } private PowerConsoleWindow PowerConsoleWindow { get { return ComponentModel.GetService<IPowerConsoleWindow>() as PowerConsoleWindow; } } private IVsUIShell VsUIShell { get { return this.GetService<IVsUIShell>(typeof(SVsUIShell)); } } private bool IsToolbarEnabled { get { return _wpfConsole != null && _wpfConsole.Dispatcher.IsStartCompleted && _wpfConsole.Host != null && _wpfConsole.Host.IsCommandEnabled; } } /// <summary> /// Standard constructor for the tool window. /// </summary> public PowerConsoleToolWindow() : base(null) { this.Caption = Resources.ToolWindowTitle; this.BitmapResourceID = 301; this.BitmapIndex = 0; this.ToolBar = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.idToolbar); } protected override void Initialize() { base.Initialize(); OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (mcs != null) { // Get list command for the Feed combo CommandID sourcesListCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidSourcesList); mcs.AddCommand(new OleMenuCommand(SourcesList_Exec, sourcesListCommandID)); // invoke command for the Feed combo CommandID sourcesCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidSources); mcs.AddCommand(new OleMenuCommand(Sources_Exec, sourcesCommandID)); // get default project command CommandID projectsListCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidProjectsList); mcs.AddCommand(new OleMenuCommand(ProjectsList_Exec, projectsListCommandID)); // invoke command for the Default project combo CommandID projectsCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidProjects); mcs.AddCommand(new OleMenuCommand(Projects_Exec, projectsCommandID)); // clear console command CommandID clearHostCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidClearHost); mcs.AddCommand(new OleMenuCommand(ClearHost_Exec, clearHostCommandID)); // terminate command execution command CommandID stopHostCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidStopHost); mcs.AddCommand(new OleMenuCommand(StopHost_Exec, stopHostCommandID)); } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We really don't want exceptions from the console to bring down VS")] public override void OnToolWindowCreated() { // Register key bindings to use in the editor var windowFrame = (IVsWindowFrame)Frame; Guid cmdUi = VSConstants.GUID_TextEditorFactory; windowFrame.SetGuidProperty((int)__VSFPROPID.VSFPROPID_InheritKeyBindings, ref cmdUi); // pause for a tiny moment to let the tool window open before initializing the host var timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromMilliseconds(10); timer.Tick += (o, e) => { // all exceptions from the timer thread should be caught to avoid crashing VS try { LoadConsoleEditor(); timer.Stop(); } catch (Exception x) { ExceptionHelper.WriteToActivityLog(x); } }; timer.Start(); base.OnToolWindowCreated(); } protected override void OnClose() { base.OnClose(); if (_wpfConsole != null) { _wpfConsole.Dispose(); } } /// <summary> /// This override allows us to forward these messages to the editor instance as well /// </summary> /// <param name="m"></param> /// <returns></returns> protected override bool PreProcessMessage(ref System.Windows.Forms.Message m) { IVsWindowPane vsWindowPane = this.VsTextView as IVsWindowPane; if (vsWindowPane != null) { MSG[] pMsg = new MSG[1]; pMsg[0].hwnd = m.HWnd; pMsg[0].message = (uint)m.Msg; pMsg[0].wParam = m.WParam; pMsg[0].lParam = m.LParam; return vsWindowPane.TranslateAccelerator(pMsg) == 0; } return base.PreProcessMessage(ref m); } /// <summary> /// Override to forward to editor or handle accordingly if supported by this tool window. /// </summary> int IOleCommandTarget.QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { // examine buttons within our toolbar if (pguidCmdGroup == GuidList.guidNuGetCmdSet) { bool isEnabled = IsToolbarEnabled; if (isEnabled) { bool isStopButton = (prgCmds[0].cmdID == 0x0600); // 0x0600 is the Command ID of the Stop button, defined in .vsct // when command is executing: enable stop button and disable the rest // when command is not executing: disable the stop button and enable the rest isEnabled = !isStopButton ^ WpfConsole.Dispatcher.IsExecutingCommand; } if (isEnabled) { prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED); } else { prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED); } return VSConstants.S_OK; } int hr = OleCommandFilter.OLECMDERR_E_NOTSUPPORTED; if (this.VsTextView != null) { IOleCommandTarget cmdTarget = (IOleCommandTarget)VsTextView; hr = cmdTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } if (hr == OleCommandFilter.OLECMDERR_E_NOTSUPPORTED || hr == OleCommandFilter.OLECMDERR_E_UNKNOWNGROUP) { IOleCommandTarget target = this.GetService(typeof(IOleCommandTarget)) as IOleCommandTarget; if (target != null) { hr = target.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } } return hr; } /// <summary> /// Override to forward to editor or handle accordingly if supported by this tool window. /// </summary> int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { int hr = OleCommandFilter.OLECMDERR_E_NOTSUPPORTED; if (this.VsTextView != null) { IOleCommandTarget cmdTarget = (IOleCommandTarget)VsTextView; hr = cmdTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } if (hr == OleCommandFilter.OLECMDERR_E_NOTSUPPORTED || hr == OleCommandFilter.OLECMDERR_E_UNKNOWNGROUP) { IOleCommandTarget target = this.GetService(typeof(IOleCommandTarget)) as IOleCommandTarget; if (target != null) { hr = target.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } } return hr; } private void SourcesList_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null || args.OutValue == IntPtr.Zero) { throw new ArgumentException("Invalid argument", "e"); } Marshal.GetNativeVariantForObject(PowerConsoleWindow.PackageSources, args.OutValue); } } /// <summary> /// Called to retrieve current combo item name or to select a new item. /// </summary> private void Sources_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null && args.InValue is int) // Selected a feed { int index = (int)args.InValue; if (index >= 0 && index < PowerConsoleWindow.PackageSources.Length) { PowerConsoleWindow.ActivePackageSource = PowerConsoleWindow.PackageSources[index]; } } else if (args.OutValue != IntPtr.Zero) // Query selected feed name { string displayName = PowerConsoleWindow.ActivePackageSource ?? string.Empty; Marshal.GetNativeVariantForObject(displayName, args.OutValue); } } } private void ProjectsList_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null || args.OutValue == IntPtr.Zero) { throw new ArgumentException("Invalid argument", "e"); } // get project list here Marshal.GetNativeVariantForObject(PowerConsoleWindow.AvailableProjects, args.OutValue); } } /// <summary> /// Called to retrieve current combo item name or to select a new item. /// </summary> private void Projects_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null && args.InValue is int) { // Selected a default projects int index = (int)args.InValue; if (index >= 0 && index < PowerConsoleWindow.AvailableProjects.Length) { PowerConsoleWindow.SetDefaultProjectIndex(index); } } else if (args.OutValue != IntPtr.Zero) { string displayName = PowerConsoleWindow.DefaultProject ?? string.Empty; Marshal.GetNativeVariantForObject(displayName, args.OutValue); } } } /// <summary> /// ClearHost command handler. /// </summary> private void ClearHost_Exec(object sender, EventArgs e) { if (WpfConsole != null) { WpfConsole.Dispatcher.ClearConsole(); } } private void StopHost_Exec(object sender, EventArgs e) { if (WpfConsole != null) { WpfConsole.Host.Abort(); } } private HostInfo ActiveHostInfo { get { return PowerConsoleWindow.ActiveHostInfo; } } private void LoadConsoleEditor() { if (WpfConsole != null) { // allow the console to start writing output WpfConsole.StartWritingOutput(); FrameworkElement consolePane = WpfConsole.Content as FrameworkElement; ConsoleParentPane.AddConsoleEditor(consolePane); // WPF doesn't handle input focus automatically in this scenario. We // have to set the focus manually, otherwise the editor is displayed but // not focused and not receiving keyboard inputs until clicked. if (consolePane != null) { PendingMoveFocus(consolePane); } } } /// <summary> /// Set pending focus to a console pane. At the time of setting active host, /// the pane (UIElement) is usually not loaded yet and can't receive focus. /// In this case, we need to set focus in its Loaded event. /// </summary> /// <param name="consolePane"></param> private void PendingMoveFocus(FrameworkElement consolePane) { if (consolePane.IsLoaded && PresentationSource.FromDependencyObject(consolePane) != null) { PendingFocusPane = null; MoveFocus(consolePane); } else { PendingFocusPane = consolePane; } } private FrameworkElement _pendingFocusPane; private FrameworkElement PendingFocusPane { get { return _pendingFocusPane; } set { if (_pendingFocusPane != null) { _pendingFocusPane.Loaded -= PendingFocusPane_Loaded; } _pendingFocusPane = value; if (_pendingFocusPane != null) { _pendingFocusPane.Loaded += PendingFocusPane_Loaded; } } } private void PendingFocusPane_Loaded(object sender, RoutedEventArgs e) { MoveFocus(PendingFocusPane); PendingFocusPane = null; } private void MoveFocus(FrameworkElement consolePane) { // TAB focus into editor (consolePane.Focus() does not work due to editor layouts) consolePane.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); // Try start the console session now. This needs to be after the console // pane getting focus to avoid incorrect initial editor layout. StartConsoleSession(consolePane); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We really don't want exceptions from the console to bring down VS")] private void StartConsoleSession(FrameworkElement consolePane) { if (WpfConsole != null && WpfConsole.Content == consolePane && WpfConsole.Host != null) { try { if (WpfConsole.Dispatcher.IsStartCompleted) { OnDispatcherStartCompleted(); // if the dispatcher was started before we reach here, // it means the dispatcher has been in read-only mode (due to _startedWritingOutput = false). // enable key input now. WpfConsole.Dispatcher.AcceptKeyInput(); } else { WpfConsole.Dispatcher.StartCompleted += (sender, args) => OnDispatcherStartCompleted(); WpfConsole.Dispatcher.StartWaitingKey += OnDispatcherStartWaitingKey; WpfConsole.Dispatcher.Start(); } } catch (Exception x) { // hide the text "initialize host" when an error occurs. ConsoleParentPane.NotifyInitializationCompleted(); WpfConsole.WriteLine(x.GetBaseException().ToString()); ExceptionHelper.WriteToActivityLog(x); } } else { ConsoleParentPane.NotifyInitializationCompleted(); } } private void OnDispatcherStartWaitingKey(object sender, EventArgs args) { WpfConsole.Dispatcher.StartWaitingKey -= OnDispatcherStartWaitingKey; // we want to hide the text "initialize host..." when waiting for key input ConsoleParentPane.NotifyInitializationCompleted(); } private void OnDispatcherStartCompleted() { WpfConsole.Dispatcher.StartWaitingKey -= OnDispatcherStartWaitingKey; ConsoleParentPane.NotifyInitializationCompleted(); // force the UI to update the toolbar VsUIShell.UpdateCommandUI(0 /* false = update UI asynchronously */); NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageManagerConsoleLoaded); } private IWpfConsole _wpfConsole; /// <summary> /// Get the WpfConsole of the active host. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private IWpfConsole WpfConsole { get { if (_wpfConsole == null) { _wpfConsole = ActiveHostInfo.WpfConsole; } return _wpfConsole; } } private IVsTextView _vsTextView; /// <summary> /// Get the VsTextView of current WpfConsole if exists. /// </summary> private IVsTextView VsTextView { get { if (_vsTextView == null && _wpfConsole != null) { _vsTextView = (IVsTextView)(WpfConsole.VsTextView); } return _vsTextView; } } private ConsoleContainer _consoleParentPane; /// <summary> /// Get the parent pane of console panes. This serves as the Content of this tool window. /// </summary> private ConsoleContainer ConsoleParentPane { get { if (_consoleParentPane == null) { _consoleParentPane = new ConsoleContainer(ProductUpdateService, PackageRestoreManager); } return _consoleParentPane; } } public override object Content { get { return this.ConsoleParentPane; } set { base.Content = value; } } #region IPowerConsoleService Region public event EventHandler ExecuteEnd; private ITextSnapshot _snapshot; private int _previousPosition; public bool Execute(string command, object[] inputs) { if (ConsoleStatus.IsBusy) { VSOutputConsole.WriteLine(Resources.PackageManagerConsoleBusy); throw new NotSupportedException(Resources.PackageManagerConsoleBusy); } if (!String.IsNullOrEmpty(command)) { WpfConsole.SetExecutionMode(true); // Cast the ToolWindowPane to PowerConsoleToolWindow // Access the IHost from PowerConsoleToolWindow as follows PowerConsoleToolWindow.WpfConsole.Host // Cast IHost to IAsyncHost // Also, register for IAsyncHost.ExecutedEnd and return only when the command is completed IPrivateWpfConsole powerShellConsole = (IPrivateWpfConsole)WpfConsole; IHost host = powerShellConsole.Host; var asynchost = host as IAsyncHost; if (asynchost != null) { asynchost.ExecuteEnd += PowerConsoleCommand_ExecuteEnd; } // Here, we store the snapshot of the powershell Console output text buffer // Snapshot has reference to the buffer and the current length of the buffer // And, upon execution of the command, (check the commandexecuted handler) // the changes to the buffer is identified and copied over to the VS output window if (powerShellConsole.InputLineStart != null && powerShellConsole.InputLineStart.Value.Snapshot != null) { _snapshot = powerShellConsole.InputLineStart.Value.Snapshot; } // We should write the command to the console just to imitate typical user action before executing it // Asserts get fired otherwise. Also, the log is displayed in a disorderly fashion powerShellConsole.WriteLine(command); return host.Execute(powerShellConsole, command, null); } return false; } private void PowerConsoleCommand_ExecuteEnd(object sender, EventArgs e) { // Flush the change in console text buffer onto the output window for testability // If the VSOutputConsole could not be obtained, just ignore if (VSOutputConsole != null && _snapshot != null) { if (_previousPosition < _snapshot.Length) { VSOutputConsole.WriteLine(_snapshot.GetText(_previousPosition, (_snapshot.Length - _previousPosition))); } _previousPosition = _snapshot.Length; } (sender as IAsyncHost).ExecuteEnd -= PowerConsoleCommand_ExecuteEnd; WpfConsole.SetExecutionMode(false); // This does NOT imply that the command succeeded. It just indicates that the console is ready for input now VSOutputConsole.WriteLine(Resources.PackageManagerConsoleCommandExecuted); ExecuteEnd.Raise(this, EventArgs.Empty); } private IConsole _vsOutputConsole = null; private IConsole VSOutputConsole { get { if (_vsOutputConsole == null) { IOutputConsoleProvider outputConsoleProvider = ServiceLocator.GetInstance<IOutputConsoleProvider>(); if (null != outputConsoleProvider) { _vsOutputConsole = outputConsoleProvider.CreateOutputConsole(requirePowerShellHost: false); } } return _vsOutputConsole; } } private IConsoleStatus _consoleStatus; private IConsoleStatus ConsoleStatus { get { if (_consoleStatus == null) { _consoleStatus = ServiceLocator.GetInstance<IConsoleStatus>(); Debug.Assert(_consoleStatus != null); } return _consoleStatus; } } #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; namespace UMA { /// <summary> /// Utility class for generating texture atlases /// </summary> [Serializable] public class UMAGeneratorCoroutine : WorkerCoroutine { TextureProcessBaseCoroutine textureProcessCoroutine; MaxRectsBinPack packTexture; UMAGeneratorBase umaGenerator; UMAData umaData; Texture[] backUpTexture; bool updateMaterialList; int scaleFactor; MaterialDefinitionComparer comparer = new MaterialDefinitionComparer(); List<UMAData.GeneratedMaterial> generatedMaterials; int rendererCount; List<UMAData.GeneratedMaterial> atlassedMaterials = new List<UMAData.GeneratedMaterial>(20); Dictionary<List<OverlayData>, UMAData.GeneratedMaterial> generatedMaterialLookup; public void Prepare(UMAGeneratorBase _umaGenerator, UMAData _umaData, TextureProcessBaseCoroutine textureProcessCoroutine, bool updateMaterialList, int InitialScaleFactor) { umaGenerator = _umaGenerator; umaData = _umaData; this.textureProcessCoroutine = textureProcessCoroutine; this.updateMaterialList = updateMaterialList; scaleFactor = InitialScaleFactor; } private UMAData.GeneratedMaterial FindOrCreateGeneratedMaterial(UMAMaterial umaMaterial) { if (umaMaterial.materialType == UMAMaterial.MaterialType.Atlas) { foreach (var atlassedMaterial in atlassedMaterials) { if (atlassedMaterial.umaMaterial == umaMaterial) { return atlassedMaterial; } else { if (atlassedMaterial.umaMaterial.Equals(umaMaterial)) { return atlassedMaterial; } } } } var res = new UMAData.GeneratedMaterial(); if (umaMaterial.RequireSeperateRenderer) { res.renderer = rendererCount++; } res.umaMaterial = umaMaterial; res.material = UnityEngine.Object.Instantiate(umaMaterial.material) as Material; res.material.name = umaMaterial.material.name; atlassedMaterials.Add(res); generatedMaterials.Add(res); return res; } protected override void Start() { if (generatedMaterialLookup == null) { generatedMaterialLookup = new Dictionary<List<OverlayData>, UMAData.GeneratedMaterial>(20); } else { generatedMaterialLookup.Clear(); } backUpTexture = umaData.backUpTextures(); umaData.CleanTextures(); generatedMaterials = new List<UMAData.GeneratedMaterial>(20); atlassedMaterials.Clear(); rendererCount = 0; SlotData[] slots = umaData.umaRecipe.slotDataList; for (int i = 0; i < slots.Length; i++) { var slot = slots[i]; if (slot == null) continue; if ((slot.asset.material != null) && (slot.GetOverlay(0) != null)) { if (!slot.asset.material.RequireSeperateRenderer) { // At least one slot that doesn't require a seperate renderer, so we reserve renderer 0 for those. rendererCount = 1; break; } } } for (int i = 0; i < slots.Length; i++) { SlotData slot = slots[i]; if (slot == null) continue; // Let's only add the default overlay if the slot has overlays and NO meshData if ((slot.asset.meshData != null) && (slot.OverlayCount == 0)) { if (umaGenerator.defaultOverlaydata != null) slot.AddOverlay(umaGenerator.defaultOverlaydata); } OverlayData overlay0 = slot.GetOverlay(0); if ((slot.asset.material != null) && (overlay0 != null)) { List<OverlayData> overlayList = slot.GetOverlayList(); UMAData.GeneratedMaterial generatedMaterial; if (!generatedMaterialLookup.TryGetValue(overlayList, out generatedMaterial)) { generatedMaterial = FindOrCreateGeneratedMaterial(slot.asset.material); generatedMaterialLookup.Add(overlayList, generatedMaterial); } int validOverlayCount = 0; for (int j = 0; j < slot.OverlayCount; j++) { var overlay = slot.GetOverlay(j); if (overlay != null) { validOverlayCount++; #if UNITY_STANDALONE || UNITY_IOS || UNITY_ANDROID || UNITY_PS4 || UNITY_XBOXONE //supported platforms for procedural materials if (overlay.isProcedural) overlay.GenerateProceduralTextures(); #endif } } UMAData.MaterialFragment tempMaterialDefinition = new UMAData.MaterialFragment(); tempMaterialDefinition.baseOverlay = new UMAData.textureData(); tempMaterialDefinition.baseOverlay.textureList = overlay0.textureArray; tempMaterialDefinition.baseOverlay.alphaTexture = overlay0.alphaMask; tempMaterialDefinition.baseOverlay.overlayType = overlay0.overlayType; tempMaterialDefinition.umaMaterial = slot.asset.material; tempMaterialDefinition.baseColor = overlay0.colorData.color; tempMaterialDefinition.size = overlay0.pixelCount; tempMaterialDefinition.overlays = new UMAData.textureData[validOverlayCount - 1]; tempMaterialDefinition.overlayColors = new Color32[validOverlayCount - 1]; tempMaterialDefinition.rects = new Rect[validOverlayCount - 1]; tempMaterialDefinition.overlayData = new OverlayData[validOverlayCount]; tempMaterialDefinition.channelMask = new Color[validOverlayCount][]; tempMaterialDefinition.channelAdditiveMask = new Color[validOverlayCount][]; tempMaterialDefinition.overlayData[0] = slot.GetOverlay(0); tempMaterialDefinition.channelMask[0] = slot.GetOverlay(0).colorData.channelMask; tempMaterialDefinition.channelAdditiveMask[0] = slot.GetOverlay(0).colorData.channelAdditiveMask; tempMaterialDefinition.slotData = slot; int overlayID = 0; for (int j = 1; j < slot.OverlayCount; j++) { OverlayData overlay = slot.GetOverlay(j); if (overlay == null) continue; tempMaterialDefinition.rects[overlayID] = overlay.rect; tempMaterialDefinition.overlays[overlayID] = new UMAData.textureData(); tempMaterialDefinition.overlays[overlayID].textureList = overlay.textureArray; tempMaterialDefinition.overlays[overlayID].alphaTexture = overlay.alphaMask; tempMaterialDefinition.overlays[overlayID].overlayType = overlay.overlayType; tempMaterialDefinition.overlayColors[overlayID] = overlay.colorData.color; overlayID++; tempMaterialDefinition.overlayData[overlayID] = overlay; tempMaterialDefinition.channelMask[overlayID] = overlay.colorData.channelMask; tempMaterialDefinition.channelAdditiveMask[overlayID] = overlay.colorData.channelAdditiveMask; } tempMaterialDefinition.overlayList = overlayList; tempMaterialDefinition.isRectShared = false; for (int j = 0; j < generatedMaterial.materialFragments.Count; j++) { if (tempMaterialDefinition.overlayList == generatedMaterial.materialFragments[j].overlayList) { tempMaterialDefinition.isRectShared = true; tempMaterialDefinition.rectFragment = generatedMaterial.materialFragments[j]; break; } } generatedMaterial.materialFragments.Add(tempMaterialDefinition); } } packTexture = new MaxRectsBinPack(umaGenerator.atlasResolution, umaGenerator.atlasResolution, false); } public class MaterialDefinitionComparer : IComparer<UMAData.MaterialFragment> { public int Compare(UMAData.MaterialFragment x, UMAData.MaterialFragment y) { return y.size - x.size; } } protected override IEnumerator workerMethod() { umaData.generatedMaterials.rendererCount = rendererCount; umaData.generatedMaterials.materials = generatedMaterials; GenerateAtlasData(); OptimizeAtlas(); textureProcessCoroutine.Prepare(umaData, umaGenerator); yield return textureProcessCoroutine; CleanBackUpTextures(); UpdateUV(); // HACK - is this the right place? SlotData[] slots = umaData.umaRecipe.slotDataList; for (int i = 0; i < slots.Length; i++) { var slot = slots[i]; if (slot == null) continue; for (int j = 1; j < slot.OverlayCount; j++) { OverlayData overlay = slot.GetOverlay(j); #if UNITY_STANDALONE || UNITY_IOS || UNITY_ANDROID || UNITY_PS4 || UNITY_XBOXONE //supported platforms for procedural materials if ((overlay != null) && (overlay.isProcedural)) overlay.ReleaseProceduralTextures(); #endif } } if (updateMaterialList) { for (int j = 0; j < umaData.rendererCount; j++) { var renderer = umaData.GetRenderer(j); var mats = renderer.sharedMaterials; var newMats = new Material[mats.Length]; var atlasses = umaData.generatedMaterials.materials; int materialIndex = 0; for (int i = 0; i < atlasses.Count; i++) { if (atlasses[i].renderer == j) { UMAUtils.DestroySceneObject(mats[materialIndex]); newMats[materialIndex] = atlasses[i].material; materialIndex++; } } renderer.sharedMaterials = newMats; } } } protected override void Stop() { } private void CleanBackUpTextures() { for (int textureIndex = 0; textureIndex < backUpTexture.Length; textureIndex++) { if (backUpTexture[textureIndex] != null) { Texture tempTexture = backUpTexture[textureIndex]; if (tempTexture is RenderTexture) { RenderTexture tempRenderTexture = tempTexture as RenderTexture; tempRenderTexture.Release(); UMAUtils.DestroySceneObject(tempRenderTexture); tempRenderTexture = null; } else { UMAUtils.DestroySceneObject(tempTexture); } backUpTexture[textureIndex] = null; } } } private void GenerateAtlasData() { float StartScale = 1.0f / (float)scaleFactor; for (int i = 0; i < atlassedMaterials.Count; i++) { var generatedMaterial = atlassedMaterials[i]; generatedMaterial.materialFragments.Sort(comparer); generatedMaterial.resolutionScale = StartScale; generatedMaterial.cropResolution = new Vector2(umaGenerator.atlasResolution, umaGenerator.atlasResolution); while (!CalculateRects(generatedMaterial)) { generatedMaterial.resolutionScale = generatedMaterial.resolutionScale * 0.5f; } UpdateSharedRect(generatedMaterial); } } private void UpdateSharedRect(UMAData.GeneratedMaterial generatedMaterial) { for (int i = 0; i < generatedMaterial.materialFragments.Count; i++) { var fragment = generatedMaterial.materialFragments[i]; if (fragment.isRectShared) { fragment.atlasRegion = fragment.rectFragment.atlasRegion; } } } private bool CalculateRects(UMAData.GeneratedMaterial material) { Rect nullRect = new Rect(0, 0, 0, 0); packTexture.Init(umaGenerator.atlasResolution, umaGenerator.atlasResolution, false); for (int atlasElementIndex = 0; atlasElementIndex < material.materialFragments.Count; atlasElementIndex++) { var tempMaterialDef = material.materialFragments[atlasElementIndex]; if (tempMaterialDef.isRectShared) continue; tempMaterialDef.atlasRegion = packTexture.Insert(Mathf.FloorToInt(tempMaterialDef.baseOverlay.textureList[0].width * material.resolutionScale * tempMaterialDef.slotData.overlayScale), Mathf.FloorToInt(tempMaterialDef.baseOverlay.textureList[0].height * material.resolutionScale * tempMaterialDef.slotData.overlayScale), MaxRectsBinPack.FreeRectChoiceHeuristic.RectBestLongSideFit); if (tempMaterialDef.atlasRegion == nullRect) { if (umaGenerator.fitAtlas) { Debug.LogWarning("Atlas resolution is too small, Textures will be reduced.", umaData.gameObject); return false; } else { Debug.LogError("Atlas resolution is too small, not all textures will fit.", umaData.gameObject); } } } return true; } private void OptimizeAtlas() { for (int atlasIndex = 0; atlasIndex < atlassedMaterials.Count; atlasIndex++) { var material = atlassedMaterials[atlasIndex]; Vector2 usedArea = new Vector2(0, 0); for (int atlasElementIndex = 0; atlasElementIndex < material.materialFragments.Count; atlasElementIndex++) { if (material.materialFragments[atlasElementIndex].atlasRegion.xMax > usedArea.x) { usedArea.x = material.materialFragments[atlasElementIndex].atlasRegion.xMax; } if (material.materialFragments[atlasElementIndex].atlasRegion.yMax > usedArea.y) { usedArea.y = material.materialFragments[atlasElementIndex].atlasRegion.yMax; } } Vector2 tempResolution = new Vector2(umaGenerator.atlasResolution, umaGenerator.atlasResolution); bool done = false; while (!done) { if (tempResolution.x * 0.5f >= usedArea.x) { tempResolution = new Vector2(tempResolution.x * 0.5f, tempResolution.y); } else { done = true; } } done = false; while (!done) { if (tempResolution.y * 0.5f >= usedArea.y) { tempResolution = new Vector2(tempResolution.x, tempResolution.y * 0.5f); } else { done = true; } } material.cropResolution = tempResolution; } } private void UpdateUV() { UMAData.GeneratedMaterials umaAtlasList = umaData.generatedMaterials; for (int atlasIndex = 0; atlasIndex < umaAtlasList.materials.Count; atlasIndex++) { var material = umaAtlasList.materials[atlasIndex]; if (material.umaMaterial.materialType == UMAMaterial.MaterialType.NoAtlas) continue; Vector2 finalAtlasAspect = new Vector2(umaGenerator.atlasResolution / material.cropResolution.x, umaGenerator.atlasResolution / material.cropResolution.y); for (int atlasElementIndex = 0; atlasElementIndex < material.materialFragments.Count; atlasElementIndex++) { Rect tempRect = material.materialFragments[atlasElementIndex].atlasRegion; tempRect.xMin = tempRect.xMin * finalAtlasAspect.x; tempRect.xMax = tempRect.xMax * finalAtlasAspect.x; tempRect.yMin = tempRect.yMin * finalAtlasAspect.y; tempRect.yMax = tempRect.yMax * finalAtlasAspect.y; material.materialFragments[atlasElementIndex].atlasRegion = tempRect; } } } } }
/******************************************************************************* * The MIT License (MIT) * Copyright (c) 2015 Frank Benoit, Stuttgart, Germany <[email protected]> * * See the LICENSE.md or the online documentation: * https://docs.google.com/document/d/1Wqa8rDi0QYcqcf0oecD8GW53nMVXj3ZFSmcF81zAa8g/edit#heading=h.2kvlhpr5zi2u * * Contributors: * Frank Benoit - initial API and implementation *******************************************************************************/ namespace Org.Chabu.Prot.V1.Internal { using ByteBuffer = Org.Chabu.Prot.Util.ByteBuffer; using Runnable = global::System.Action; using global::System.Collections.Generic; using global::System; internal abstract class ChabuXmitter { internal delegate LoopCtrl LoopCtrlAction(); private static readonly int SETUP_PROTNAME_MAXLENGTH = 8; private static readonly int SETUP_APPNAME_MAXLENGTH = 56; private static readonly int ABORT_MSG_MAXLENGTH = 56; protected static readonly int PT_MAGIC = 0x77770000; internal enum LoopCtrl { Break, Continue, None } internal abstract List<LoopCtrlAction> getActions(); private readonly Runnable xmitRequestListener; private readonly AbortMessage abortMessage; internal ByteBuffer xmitBuf = new ByteBuffer(Constants.MAX_RECV_LIMIT_LOW); internal PacketType packetType = PacketType.NONE; internal ByteChannel loopByteChannel; internal XmitState xmitAbort = XmitState.IDLE; public ChabuXmitter(AbortMessage abortMessage, Runnable xmitRequestListener) { this.abortMessage = abortMessage; this.xmitRequestListener = xmitRequestListener; } protected void runActionsUntilBreak() { List<LoopCtrlAction> loopActions = getActions(); Lwhile: while( true ) { foreach (LoopCtrlAction action in loopActions) { LoopCtrl loopCtrl = action.Invoke(); if (loopCtrl == LoopCtrl.Break) return; if (loopCtrl == LoopCtrl.Continue) goto Lwhile; } } } protected void processXmitNop() { checkXmitBufEmptyOrThrow("Cannot xmit NOP, buffer is not empty"); xmitFillStart(PacketType.NOP); xmitFillComplete(); } public void xmit(ByteChannel byteChannel) { this.loopByteChannel = byteChannel; try{ runActionsUntilBreak(); } finally { this.loopByteChannel = null; } } protected LoopCtrl xmitAction_EvalAbort() { if( abortMessage.isPending() ){ prepareAbort(); return LoopCtrl.Continue; } return LoopCtrl.None; } protected LoopCtrl xmitAction_RemainingXmitBuf() { if( xmitBuf.hasRemaining() ){ loopByteChannel.write(xmitBuf); } if( !xmitBuf.hasRemaining() && packetType != PacketType.SEQ ){ handleNonSeqCompletion(); packetType = PacketType.NONE; } if( xmitBuf.hasRemaining() ){ callXmitRequestListener(); } return xmitBuf.hasRemaining() ? LoopCtrl.Break : LoopCtrl.None; } protected abstract void handleNonSeqCompletion(); protected void xmitFillSetupPacket(ChabuSetupInfo setupInfo) { xmitFillStart(PacketType.SETUP); xmitFillAddstring(SETUP_PROTNAME_MAXLENGTH, Constants.PROTOCOL_NAME); xmitFillAddInt(Constants.PROTOCOL_VERSION); xmitFillAddInt(setupInfo.recvPacketSize); xmitFillAddInt(setupInfo.applicationVersion); xmitFillAddstring(SETUP_APPNAME_MAXLENGTH, setupInfo.applicationProtocolName); xmitFillComplete(); } protected virtual void prepareXmitAccept() { checkXmitBufEmptyOrThrow("Cannot xmit ACCEPT, buffer is not empty"); xmitFillStart(PacketType.ACCEPT); xmitFillComplete(); } protected void xmitFillAddInt(int value) { xmitBuf.putInt(value); } protected void xmitFillAddstring(int maxLength, string str) { byte[] bytes = str.getBytes(StandardCharsets.UTF_8); if (bytes.Length > maxLength) { byte[] bytes2 = new byte[maxLength]; System.arraycopy(bytes, 0, bytes2, 0, maxLength); bytes = bytes2; } xmitFillAddstring(bytes); } protected void xmitFillAddstring(byte[] bytes) { xmitBuf.putInt(bytes.Length); xmitBuf.put(bytes); xmitFillAligned(); } void prepareAbort() { checkXmitBufEmptyOrThrow("Cannot xmit ABORT, buffer is not empty"); xmitFillStart(PacketType.ABORT); xmitFillAddInt(abortMessage.getCode()); xmitFillAddstring(ABORT_MSG_MAXLENGTH, abortMessage.getMessage()); xmitFillComplete(); xmitAbort = XmitState.PREPARED; } internal void xmitFillArmPacket(int channelId, int arm) { checkXmitBufEmptyOrThrow("Cannot xmit ACCEPT, buffer is not empty"); xmitFillStart(PacketType.ARM); xmitBuf.putInt(channelId); xmitBuf.putInt(arm); xmitFillComplete(); } internal void xmitFillStart(PacketType type) { packetType = type; xmitBuf.clear(); xmitBuf.putInt(-1); xmitBuf.putInt(PT_MAGIC | (int)type); } protected void xmitFillComplete() { xmitFillAligned(); xmitBuf.putInt(0, xmitBuf.position()); xmitBuf.flip(); } protected void xmitFillComplete(int packetSize) { xmitFillAligned(); xmitBuf.putInt(0, packetSize); xmitBuf.flip(); } private void xmitFillAligned() { while (xmitBuf.position() % 4 != 0) { xmitBuf.put((byte)0); } } protected void checkXmitBufEmptyOrThrow(string message) { if (xmitBuf.hasRemaining()) { throw new ChabuException(message); } } public void delayedAbort(int code, string message, params object[] args) { Utils.ensure(xmitAbort == XmitState.IDLE, ChabuErrorCode.ASSERT, "Abort is already pending while generating Abort from Validator"); abortMessage.setPending(code, string.Format(message, args)); xmitAbort = XmitState.PENDING; callXmitRequestListener(); } protected void throwAbort() { int code = abortMessage.getCode(); string msg = abortMessage.getMessage(); abortMessage.setXmitted(); throw new ChabuException(ChabuErrorCode.REMOTE_ABORT, code, string.Format("Remote Abort: Code:0x{0:X8} ({1}) {2}", code, code, msg)); } public void delayedAbort(ChabuErrorCode ec, string message, params object[] args) { delayedAbort(ec, message, args); } protected void callXmitRequestListener() { if (xmitRequestListener != null) { xmitRequestListener.Invoke(); } } public virtual void channelXmitRequestArm(int channelId) { throw new Exception("Xmit request for ARM before activation, channel: " + channelId); } public virtual void channelXmitRequestData(int channelId) { throw new Exception("Xmit request for data before activation, channel: " + channelId); } } }
// 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.12.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.PetstoreV2 { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class SwaggerPetstoreV2Extensions { /// <summary> /// Add a new pet to the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static Pet AddPet(this ISwaggerPetstoreV2 operations, Pet body) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).AddPetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Add a new pet to the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Pet> AddPetAsync( this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Pet> result = await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static void UpdatePet(this ISwaggerPetstoreV2 operations, Pet body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePetAsync( this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Finds Pets by status /// </summary> /// Multiple status values can be provided with comma seperated strings /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> public static IList<Pet> FindPetsByStatus(this ISwaggerPetstoreV2 operations, IList<string> status) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByStatusAsync(status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by status /// </summary> /// Multiple status values can be provided with comma seperated strings /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Pet>> FindPetsByStatusAsync( this ISwaggerPetstoreV2 operations, IList<string> status, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<IList<Pet>> result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Finds Pets by tags /// </summary> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> public static IList<Pet> FindPetsByTags(this ISwaggerPetstoreV2 operations, IList<string> tags) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByTagsAsync(tags), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by tags /// </summary> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Pet>> FindPetsByTagsAsync( this ISwaggerPetstoreV2 operations, IList<string> tags, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<IList<Pet>> result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Find pet by Id /// </summary> /// Returns a single pet /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet to return /// </param> public static Pet GetPetById(this ISwaggerPetstoreV2 operations, long? petId) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetPetByIdAsync(petId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Find pet by Id /// </summary> /// Returns a single pet /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet to return /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Pet> GetPetByIdAsync( this ISwaggerPetstoreV2 operations, long? petId, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Pet> result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='name'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> public static void UpdatePetWithForm(this ISwaggerPetstoreV2 operations, long? petId, string name = default(string), string status = default(string)) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetWithFormAsync(petId, name, status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='name'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePetWithFormAsync( this ISwaggerPetstoreV2 operations, long? petId, string name = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, name, status, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> public static void DeletePet(this ISwaggerPetstoreV2 operations, long? petId, string apiKey = "") { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeletePetAsync(petId, apiKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeletePetAsync( this ISwaggerPetstoreV2 operations, long? petId, string apiKey = "", CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Returns pet inventories by status /// </summary> /// Returns a map of status codes to quantities /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IDictionary<string, int?> GetInventory(this ISwaggerPetstoreV2 operations) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetInventoryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns pet inventories by status /// </summary> /// Returns a map of status codes to quantities /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IDictionary<string, int?>> GetInventoryAsync( this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<IDictionary<string, int?>> result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> public static Order PlaceOrder(this ISwaggerPetstoreV2 operations, Order body) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).PlaceOrderAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Order> PlaceOrderAsync( this ISwaggerPetstoreV2 operations, Order body, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Order> result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Find purchase order by Id /// </summary> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> public static Order GetOrderById(this ISwaggerPetstoreV2 operations, string orderId) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetOrderByIdAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Find purchase order by Id /// </summary> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Order> GetOrderByIdAsync( this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Order> result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Delete purchase order by Id /// </summary> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> public static void DeleteOrder(this ISwaggerPetstoreV2 operations, string orderId) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteOrderAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete purchase order by Id /// </summary> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteOrderAsync( this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Create user /// </summary> /// This can only be done by the logged in user. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> public static void CreateUser(this ISwaggerPetstoreV2 operations, User body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUserAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create user /// </summary> /// This can only be done by the logged in user. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUserAsync( this ISwaggerPetstoreV2 operations, User body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithArrayInput(this ISwaggerPetstoreV2 operations, IList<User> body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithArrayInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUsersWithArrayInputAsync( this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithListInput(this ISwaggerPetstoreV2 operations, IList<User> body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithListInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUsersWithListInputAsync( this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> public static string LoginUser(this ISwaggerPetstoreV2 operations, string username, string password) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LoginUserAsync(username, password), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> LoginUserAsync( this ISwaggerPetstoreV2 operations, string username, string password, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<string> result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void LogoutUser(this ISwaggerPetstoreV2 operations) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LogoutUserAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task LogoutUserAsync( this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> public static User GetUserByName(this ISwaggerPetstoreV2 operations, string username) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetUserByNameAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<User> GetUserByNameAsync( this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<User> result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Updated user /// </summary> /// This can only be done by the logged in user. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> public static void UpdateUser(this ISwaggerPetstoreV2 operations, string username, User body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdateUserAsync(username, body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updated user /// </summary> /// This can only be done by the logged in user. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateUserAsync( this ISwaggerPetstoreV2 operations, string username, User body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete user /// </summary> /// This can only be done by the logged in user. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> public static void DeleteUser(this ISwaggerPetstoreV2 operations, string username) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteUserAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete user /// </summary> /// This can only be done by the logged in user. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteUserAsync( this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false); } } }
using System; using System.Web; using System.Web.Compilation; using System.Web.Security; using System.Web.SessionState; using System.Web.UI; using Carrotware.CMS.DBUpdater; /* * CarrotCake CMS * http://www.carrotware.com/ * * Copyright 2011, Samantha Copeland * Dual licensed under the MIT or GPL Version 3 licenses. * * Date: October 2011 */ namespace Carrotware.CMS.Core { public class VirtualFileSystem : IHttpHandler, IRequiresSessionState { private const string REQ_PATH = "RewriteOrigPath"; private const string REQ_QUERY = "RewriteOrigQuery"; public bool IsReusable { get { return false; } } private string sVirtualReqFile = String.Empty; private string sRequestedURL = String.Empty; private bool bAlreadyDone = false; private bool bURLOverride = false; public void ProcessRequest(HttpContext context) { using (ISiteNavHelper navHelper = SiteNavFactory.GetSiteNavHelper()) { SiteNav navData = null; string sFileRequested = context.Request.Path; sRequestedURL = sFileRequested; string sScrubbedURL = sFileRequested; sRequestedURL = SiteData.AppendDefaultPath(sRequestedURL); try { sScrubbedURL = SiteData.AlternateCurrentScriptName; if (sScrubbedURL.ToLowerInvariant() != sRequestedURL.ToLowerInvariant()) { sFileRequested = sScrubbedURL; bURLOverride = true; } VirtualDirectory.RegisterRoutes(); } catch (Exception ex) { //assumption is database is probably empty / needs updating, so trigger the under construction view if (DatabaseUpdate.SystemNeedsChecking(ex) || DatabaseUpdate.AreCMSTablesIncomplete()) { if (navData == null) { navData = SiteNavHelper.GetEmptyHome(); } } else { //something bad has gone down, toss back the error throw; } } sFileRequested = SiteData.AppendDefaultPath(sFileRequested); if (SecurityData.IsAuthenticated) { try { if (context.Request.UrlReferrer != null && !string.IsNullOrEmpty(context.Request.UrlReferrer.AbsolutePath)) { if (context.Request.UrlReferrer.AbsolutePath.ToLowerInvariant().Contains(FormsAuthentication.LoginUrl.ToLowerInvariant()) || FormsAuthentication.LoginUrl.ToLowerInvariant() == sFileRequested.ToLowerInvariant()) { if (SiteFilename.DashboardURL.ToLowerInvariant() != sFileRequested.ToLowerInvariant() && SiteFilename.SiteInfoURL.ToLowerInvariant() != sFileRequested.ToLowerInvariant()) { sFileRequested = SiteData.AdminDefaultFile; } } } } catch (Exception ex) { } } if (sFileRequested.ToLowerInvariant().EndsWith(".aspx") || SiteData.IsLikelyHomePage(sFileRequested)) { bool bIgnorePublishState = SecurityData.AdvancedEditMode || SecurityData.IsAdmin || SecurityData.IsSiteEditor; string queryString = String.Empty; queryString = context.Request.QueryString.ToString(); if (string.IsNullOrEmpty(queryString)) { queryString = String.Empty; } if (!CMSConfigHelper.CheckRequestedFileExistence(sFileRequested, SiteData.CurrentSiteID) || SiteData.IsLikelyHomePage(sFileRequested)) { context.Items[REQ_PATH] = context.Request.PathInfo; context.Items[REQ_QUERY] = context.Request.QueryString.ToString(); // handle a case where this site was migrated from a format where all pages varied on a consistent querystring // allow this QS parm to be set in a config file. if (SiteData.IsLikelyHomePage(sFileRequested)) { string sParm = String.Empty; if (SiteData.OldSiteQuerystring != string.Empty) { if (context.Request.QueryString[SiteData.OldSiteQuerystring] != null) { sParm = context.Request.QueryString[SiteData.OldSiteQuerystring].ToString(); } } if (!string.IsNullOrEmpty(sParm)) { sFileRequested = "/" + sParm + ".aspx"; SiteData.Show301Message(sFileRequested); context.Response.Redirect(sFileRequested); context.Items[REQ_PATH] = sFileRequested; context.Items[REQ_QUERY] = String.Empty; } } try { //periodic test of database up-to-dated-ness if (DatabaseUpdate.TablesIncomplete) { navData = SiteNavHelper.GetEmptyHome(); } else { bool bIsHomePage = false; if (SiteData.IsLikelyHomePage(sFileRequested)) { navData = navHelper.FindHome(SiteData.CurrentSiteID, !bIgnorePublishState); if (SiteData.IsLikelyHomePage(sFileRequested) && navData != null) { sFileRequested = navData.FileName; bIsHomePage = true; } } if (!bIsHomePage) { string pageName = sFileRequested; navData = navHelper.GetLatestVersion(SiteData.CurrentSiteID, !bIgnorePublishState, pageName); } if (SiteData.IsLikelyHomePage(sFileRequested) && navData == null) { navData = SiteNavHelper.GetEmptyHome(); } } } catch (Exception ex) { //assumption is database is probably empty / needs updating, so trigger the under construction view if (DatabaseUpdate.SystemNeedsChecking(ex) || DatabaseUpdate.AreCMSTablesIncomplete()) { if (navData == null) { navData = SiteNavHelper.GetEmptyHome(); } } else { //something bad has gone down, toss back the error throw; } } if (navData != null) { string sSelectedTemplate = navData.TemplateFile; // selectivly engage the cms helper only if in advance mode if (SecurityData.AdvancedEditMode) { using (CMSConfigHelper cmsHelper = new CMSConfigHelper()) { if (cmsHelper.cmsAdminContent != null) { try { sSelectedTemplate = cmsHelper.cmsAdminContent.TemplateFile.ToLowerInvariant(); } catch { } } } } if (!CMSConfigHelper.CheckFileExistence(sSelectedTemplate)) { sSelectedTemplate = SiteData.DefaultTemplateFilename; } sVirtualReqFile = sFileRequested; if (bURLOverride) { sVirtualReqFile = sRequestedURL; sFileRequested = sRequestedURL; } RewriteCMSPath(context, sSelectedTemplate, queryString); } else { SiteData.PerformRedirectToErrorPage(404, sFileRequested); //SiteData.Show404MessageFull(true); SiteData.Show404MessageShort(); } } else { sVirtualReqFile = sFileRequested; RewriteCMSPath(context, sVirtualReqFile, queryString); } } context.ApplicationInstance.CompleteRequest(); } } private void RewriteCMSPath(HttpContext context, string sTmplateFile, string sQuery) { try { if (string.IsNullOrEmpty(sVirtualReqFile)) { sVirtualReqFile = SiteData.DefaultDirectoryFilename; } if (string.IsNullOrEmpty(sTmplateFile)) { sTmplateFile = SiteData.DefaultTemplateFilename; } context.RewritePath(sVirtualReqFile, string.Empty, sQuery); //cannot work in med trust //Page hand = (Page)PageParser.GetCompiledPageInstance(sFileRequested, context.Server.MapPath(sRealFile), context); Page hand = (Page)BuildManager.CreateInstanceFromVirtualPath(sTmplateFile, typeof(Page)); hand.PreRenderComplete += new EventHandler(hand_PreRenderComplete); hand.ProcessRequest(context); } catch (Exception ex) { //assumption is database is probably empty / needs updating, so trigger the under construction view if (DatabaseUpdate.SystemNeedsChecking(ex) || DatabaseUpdate.AreCMSTablesIncomplete()) { SiteData.ManuallyWriteDefaultFile(context, ex); } else { //something bad has gone down, toss back the error throw; } } } protected void hand_PreRenderComplete(object sender, EventArgs e) { if (!bAlreadyDone) { try { if (HttpContext.Current.Items[REQ_PATH] != null && HttpContext.Current.Items[REQ_QUERY] != null) { HttpContext.Current.RewritePath(sVirtualReqFile, HttpContext.Current.Items[REQ_PATH].ToString(), HttpContext.Current.Items[REQ_QUERY].ToString()); } } catch (Exception ex) { } bAlreadyDone = true; } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class SeedizenComponent : MonoBehaviour { public static bool flingWithMouse = false; public PlanetComponent currentPlanet; public PlanetComponent destinationPlanet; public PlanetComponent startPlanet; public VineComponent currentVine; public ParticleSystem pollenParticles; public bool hasPollen = false; public bool inTransit = true; public float speed = 3.2f; // float flightSpeed = 8f; bool inFling = false; float flingTime = float.MaxValue; float flingDur = .3f; bool flying = false; Vector3 mousePosAtStartOfFling; //Vector3 flightDir; public float idealAngle = 0f; public string type = ""; public BoxCollider2D col; // Use this for initialization void Start () { /*if (!flingWithMouse) { gameObject.GetComponent <Collider2D> ().enabled = false; }*/ var pp = transform.FindChild ("Particle System"); if (pollenParticles == null && pp != null) pollenParticles = pp.GetComponent <ParticleSystem> (); TurnOffPollen (); col = gameObject.GetComponent<BoxCollider2D> (); } // Update is called once per frame void Update () { AnimationHandler(); if (flingWithMouse) { //flinging if (Time.time > flingTime + flingDur) { //CameraPanningScript.EnableControls (); flingTime = float.MaxValue; StartFlight (Camera.main.ScreenToWorldPoint(Input.mousePosition) - mousePosAtStartOfFling); } //ending fling if (inFling && Input.GetKeyUp (KeyCode.Mouse0)) { inFling = false; CameraPanningScript.Enable (); speed = 2f; } } //walking if (inTransit && destinationPlanet != null) { Vector3 dir = destinationPlanet.gameObject.transform.position - gameObject.transform.position; dir.Normalize (); dir = dir * Time.deltaTime * speed; gameObject.transform.position += dir; //facing /*var rot = gameObject.transform.rotation; if (dir.x < 0) rot.y = 0f; else rot.y = 180f; gameObject.transform.rotation = rot;*/ //var angle = Mathf.Atan2(currentVine.dir.y, currentVine.dir.x) * Mathf.Rad2Deg; //gameObject.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward); } if (destinationPlanet != null) { if (Vector3.Distance (destinationPlanet.gameObject.transform.position, gameObject.transform.position) < .5f) { currentPlanet = destinationPlanet; destinationPlanet = null; } } if (currentPlanet != null) { if (gameObject.transform.position.x > currentPlanet.gameObject.transform.position.x) { gameObject.transform.rotation = Quaternion.LookRotation (Vector3.forward, (gameObject.transform.position - currentPlanet.gameObject.transform.position).normalized) * Quaternion.Euler(0,0,90); var rot = gameObject.transform.rotation; rot.y = 180f; gameObject.transform.rotation = rot; } else { gameObject.transform.rotation = Quaternion.LookRotation (Vector3.forward, (currentPlanet.gameObject.transform.position - gameObject.transform.position).normalized) * Quaternion.Euler(0,0,90); var rot = gameObject.transform.rotation; rot.y = 0f; gameObject.transform.rotation = rot; } } //randomly choosing a new destination when it gets to its planet if (currentPlanet != null && destinationPlanet == null) { GoToRandomNeighbor(currentPlanet); } //walk around the currentplanet if (!flying && currentPlanet != null && destinationPlanet == null) { //TODO calculate ideal angle gameObject.transform.up = (gameObject.transform.position - currentPlanet.gameObject.transform.position).normalized; } //try to remain upright /*float angleDif = gameObject.transform.rotation.z - idealAngle; if (angleDif != 0) { angleDif = Mathf.Max (angleDif, angleDif * Time.deltaTime * 3f); var rot = gameObject.transform.rotation; rot.z -= angleDif; //Debug.Log (gameObject.transform.rotation + " " + angleDif + " " + rot); gameObject.transform.rotation = rot; }*/ //catch the fallen ones /*if (gameObject.transform.position.y < CameraPanningScript.minDepth) { AbyssComponent.instance.CaptureSeedizen (this); }*/ } void AnimationHandler() { if (inTransit) { GetComponent<Animator>().SetInteger("Stance", 1); } else { GetComponent<Animator>().SetInteger("Stance", 0); } } public IEnumerator ColliderDisableCoroutine(float t){ col.enabled = false; yield return new WaitForSeconds (t); Debug.Log ("Turning on collision"); col.enabled = true; yield return new WaitForSeconds (20); col.enabled = false; } public void temporarilyDisableCollider(float t){ //col.enabled = false; StartCoroutine (ColliderDisableCoroutine (t)); } public void TurnOffPollen () { hasPollen = false; ParticleSystem.EmissionModule em = pollenParticles.emission; em.enabled = false; } public void TurnOnPollen () { hasPollen = true; ParticleSystem.EmissionModule em = pollenParticles.emission; em.enabled = true; } public void StartFlight (Vector3 dir) { Debug.Log (dir); Vector2 dir2d = dir; flying = true; inTransit = false; if (currentVine != null) currentVine.seedizens.Remove (this); currentPlanet = null; destinationPlanet = null; currentVine = null; //flightDir = dir; //Debug.Log (this); //Debug.Log (gameObject); var rigid = gameObject.GetComponent <Rigidbody2D> (); rigid.gravityScale = 1f; rigid.AddForce (dir2d.normalized * Mathf.Sqrt (dir2d.magnitude) * 500f); } public void EndFlight () { flying = false; inTransit = true; var rigid = gameObject.GetComponent <Rigidbody2D> (); rigid.gravityScale = 0f; rigid.velocity = Vector2.zero; rigid.angularVelocity = 0; var col = gameObject.GetComponent <Collider2D> (); col.enabled = false; } /// <summary> /// It's assumed this will only be called when they're at the planet /// </summary> public void GoToRandomNeighbor (PlanetComponent planet) { if (planet == null) return; planet.ProcessSeedizen (this); // var oldPlanet = planet; /*var options = new List <PlanetComponent> (planet.connectedPlanets); foreach (var p in planet.connectedPlanets) if (planet.vines [p].dispreferred) options.Remove (p); if (options.Count == 0) { destinationPlanet = null; return; } destinationPlanet = options [Random.Range (0, options.Count)];*/ destinationPlanet = PathfindingManager.GetDirection (planet, this); if (destinationPlanet == null) return; var oldVine = currentVine; if (destinationPlanet == null) return; currentVine = destinationPlanet.vines [planet]; if (oldVine != null) oldVine.seedizens.Remove (this); if (!currentVine.seedizens.Contains (this)) currentVine.seedizens.Add (this); idealAngle = 0f; } public void GoToRandomNeighbor (VineComponent vine) { if (vine == null) return; if (vine.ends.Count < 2) { Debug.Log ("Weird vine collision"); return; } PlanetComponent dest; if (Random.Range (0, 2) == 0) dest = vine.ends [0]; else dest = vine.ends [1]; destinationPlanet = dest; } void OnMouseDown () { if (flingWithMouse) { Debug.Log ("Clicked on a seedizen"); flingTime = Time.time; inFling = true; CameraPanningScript.Disable (); speed = 0f; mousePosAtStartOfFling = Camera.main.ScreenToWorldPoint(Input.mousePosition); } } void OnCollisionEnter2D (Collision2D col) { //Debug.Log ("Collided with: " + col.gameObject.name + " at speed: " + col.relativeVelocity); var g = col.gameObject.GetComponent<TheGroundComponent>(); if (g != null) { ResourcesDisplay.instance.Add (1, startPlanet.planetType.produces); Destroy (this.gameObject); } var v = col.gameObject.GetComponent <VineComponent> (); if (v != null) { //Debug.Log ("Velocity colliding with " + col.gameObject + " is " + col.relativeVelocity + " with magnitude: " + col.relativeVelocity.magnitude); if (col.relativeVelocity.magnitude < 6f) AttachToVine (v); else { //BOUNCE! //gameObject.GetComponent <Rigidbody2D> ().AddRelativeForce (col.relativeVelocity * -100f); //TODO fix bouncing gameObject.GetComponent <Rigidbody2D> ().velocity = col.relativeVelocity * -.8f; } } var p = col.gameObject.GetComponent <PlanetComponent> (); if (p != null) { p.ProcessSeedizen (this); //var ccol = col.gameObject.GetComponent<CircleCollider2D>(); //var displ = ccol.radius*(gameObject.transform.position-col.transform.position).normalized; //gameObject.transform.rotation=Quaternion.LookRotation(Vector3.forward,displ.normalized); } } void AttachToVine (VineComponent vc) { EndFlight (); currentVine = vc; if (!vc.seedizens.Contains (this)) vc.seedizens.Add (this); GoToRandomNeighbor (vc); } public void AttachToPlanet (PlanetComponent pc) { EndFlight (); currentPlanet = pc; destinationPlanet = null; GoToRandomNeighbor (pc); } }
// // AddinService.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using System.Xml; using System.Collections; using System.Reflection; using Mono.Addins.Description; using Mono.Addins.Database; using Mono.Addins.Localization; using System.Collections.Generic; namespace Mono.Addins { /// <summary> /// An add-in engine. /// </summary> /// <remarks> /// This class allows hosting several independent add-in engines in a single application domain. /// In general, applications use the AddinManager class to query and manage extensions. This class is static, /// so the API is easily accessible. However, some kind applications may need to use several isolated /// add-in engines, and in this case the AddinManager class can't be used, because it is bound to a single /// add-in engine. Those applications can instead create several instances of the AddinEngine class. Each /// add-in engine can be independently initialized with different add-in registries and extension models. /// </remarks> public class AddinEngine: ExtensionContext { bool initialized; string startupDirectory; AddinRegistry registry; IAddinInstaller installer; bool checkAssemblyLoadConflicts; Hashtable loadedAddins = new Hashtable (); Dictionary<string,ExtensionNodeSet> nodeSets = new Dictionary<string, ExtensionNodeSet> (); Hashtable autoExtensionTypes = new Hashtable (); Hashtable loadedAssemblies = new Hashtable (); AddinLocalizer defaultLocalizer; IProgressStatus defaultProgressStatus = new ConsoleProgressStatus (false); /// <summary> /// Raised when there is an error while loading an add-in /// </summary> public static event AddinErrorEventHandler AddinLoadError; /// <summary> /// Raised when an add-in is loaded /// </summary> public static event AddinEventHandler AddinLoaded; /// <summary> /// Raised when an add-in is unloaded /// </summary> public static event AddinEventHandler AddinUnloaded; /// <summary> /// Initializes a new instance of the <see cref="Mono.Addins.AddinEngine"/> class. /// </summary> public AddinEngine () { } /// <summary> /// Initializes the add-in engine /// </summary> /// <param name="configDir"> /// Location of the add-in registry. /// </param> /// <remarks>The add-in engine needs to be initialized before doing any add-in operation. /// When initialized with this method, it will look for add-in in the add-in registry /// located in the specified path. /// </remarks> public void Initialize (string configDir) { if (initialized) return; Assembly asm = Assembly.GetEntryAssembly (); if (asm == null) asm = Assembly.GetCallingAssembly (); Initialize (asm, configDir, null, null); } /// <summary> /// Initializes the add-in engine. /// </summary> /// <param name='configDir'> /// Location of the add-in registry. /// </param> /// <param name='addinsDir'> /// Add-ins directory. If the path is relative, it is considered to be relative /// to the configDir directory. /// </param> /// <remarks> /// The add-in engine needs to be initialized before doing any add-in operation. /// Configuration information about the add-in registry will be stored in the /// provided location. The add-in engine will look for add-ins in the provided /// 'addinsDir' directory. /// /// When specifying a path, it is possible to use a special folder name as root. /// For example: [Personal]/.config/MyApp. In this case, [Personal] will be replaced /// by the location of the Environment.SpecialFolder.Personal folder. Any value /// of the Environment.SpecialFolder enumeration can be used (always between square /// brackets) /// </remarks> public void Initialize (string configDir, string addinsDir) { if (initialized) return; Assembly asm = Assembly.GetEntryAssembly (); if (asm == null) asm = Assembly.GetCallingAssembly (); Initialize (asm, configDir, addinsDir, null); } /// <summary> /// Initializes the add-in engine. /// </summary> /// <param name='configDir'> /// Location of the add-in registry. /// </param> /// <param name='addinsDir'> /// Add-ins directory. If the path is relative, it is considered to be relative /// to the configDir directory. /// </param> /// <param name='databaseDir'> /// Location of the add-in database. If the path is relative, it is considered to be relative /// to the configDir directory. /// </param> /// <remarks> /// The add-in engine needs to be initialized before doing any add-in operation. /// Configuration information about the add-in registry will be stored in the /// provided location. The add-in engine will look for add-ins in the provided /// 'addinsDir' directory. Cached information about add-ins will be stored in /// the 'databaseDir' directory. /// /// When specifying a path, it is possible to use a special folder name as root. /// For example: [Personal]/.config/MyApp. In this case, [Personal] will be replaced /// by the location of the Environment.SpecialFolder.Personal folder. Any value /// of the Environment.SpecialFolder enumeration can be used (always between square /// brackets) /// </remarks> public void Initialize (string configDir, string addinsDir, string databaseDir) { if (initialized) return; Assembly asm = Assembly.GetEntryAssembly (); if (asm == null) asm = Assembly.GetCallingAssembly (); Initialize (asm, configDir, addinsDir, databaseDir); } internal void Initialize (Assembly startupAsm, string configDir, string addinsDir, string databaseDir) { if (initialized) return; Initialize (this); string asmFile = new Uri (startupAsm.CodeBase).LocalPath; startupDirectory = System.IO.Path.GetDirectoryName (asmFile); string customDir = Environment.GetEnvironmentVariable ("MONO_ADDINS_REGISTRY"); if (customDir != null && customDir.Length > 0) configDir = customDir; if (configDir == null || configDir.Length == 0) registry = AddinRegistry.GetGlobalRegistry (this, startupDirectory); else registry = new AddinRegistry (this, configDir, startupDirectory, addinsDir, databaseDir); if (registry.CreateHostAddinsFile (asmFile) || registry.UnknownDomain) registry.Update (new ConsoleProgressStatus (false)); initialized = true; ActivateRoots (); OnAssemblyLoaded (null, null); AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler (OnAssemblyLoaded); } /// <summary> /// Finalizes the add-in engine. /// </summary> public void Shutdown () { initialized = false; AppDomain.CurrentDomain.AssemblyLoad -= new AssemblyLoadEventHandler (OnAssemblyLoaded); loadedAddins.Clear (); loadedAssemblies.Clear (); registry.Dispose (); registry = null; startupDirectory = null; ClearContext (); } /// <summary> /// Sets the default localizer to be used for this add-in engine /// </summary> /// <param name="localizer"> /// The add-in localizer /// </param> public void InitializeDefaultLocalizer (IAddinLocalizer localizer) { CheckInitialized (); if (localizer != null) defaultLocalizer = new AddinLocalizer (localizer); else defaultLocalizer = null; } internal string StartupDirectory { get { return startupDirectory; } } /// <summary> /// Gets whether the add-in engine has been initialized. /// </summary> public bool IsInitialized { get { return initialized; } } /// <summary> /// Gets the default add-in installer /// </summary> /// <remarks> /// The default installer is used by the CheckInstalled method to request /// the installation of missing add-ins. /// </remarks> public IAddinInstaller DefaultInstaller { get { return installer; } set { installer = value; } } /// <summary> /// Gets the default localizer for this add-in engine /// </summary> public AddinLocalizer DefaultLocalizer { get { CheckInitialized (); if (defaultLocalizer != null) return defaultLocalizer; else return NullLocalizer.Instance; } } internal ExtensionContext DefaultContext { get { return this; } } /// <summary> /// Gets the localizer for the add-in that is invoking this property /// </summary> public AddinLocalizer CurrentLocalizer { get { CheckInitialized (); Assembly asm = Assembly.GetCallingAssembly (); RuntimeAddin addin = GetAddinForAssembly (asm); if (addin != null) return addin.Localizer; else return DefaultLocalizer; } } /// <summary> /// Gets a reference to the RuntimeAddin object for the add-in that is invoking this property /// </summary> public RuntimeAddin CurrentAddin { get { CheckInitialized (); Assembly asm = Assembly.GetCallingAssembly (); return GetAddinForAssembly (asm); } } /// <summary> /// Gets the add-in registry bound to this add-in engine /// </summary> public AddinRegistry Registry { get { CheckInitialized (); return registry; } } internal RuntimeAddin GetAddinForAssembly (Assembly asm) { return (RuntimeAddin) loadedAssemblies [asm]; } /// <summary> /// Checks if the provided add-ins are installed, and requests the installation of those /// which aren't. /// </summary> /// <param name="message"> /// Message to show to the user when new add-ins have to be installed. /// </param> /// <param name="addinIds"> /// List of IDs of the add-ins to be checked. /// </param> /// <remarks> /// This method checks if the specified add-ins are installed. /// If some of the add-ins are not installed, it will use /// the installer assigned to the DefaultAddinInstaller property /// to install them. If the installation fails, or if DefaultAddinInstaller /// is not set, an exception will be thrown. /// </remarks> public void CheckInstalled (string message, params string[] addinIds) { ArrayList notInstalled = new ArrayList (); foreach (string id in addinIds) { Addin addin = Registry.GetAddin (id, false); if (addin != null) { // The add-in is already installed // If the add-in is disabled, enable it now if (!addin.Enabled) addin.Enabled = true; } else { notInstalled.Add (id); } } if (notInstalled.Count == 0) return; if (installer == null) throw new InvalidOperationException ("Add-in installer not set"); // Install the add-ins installer.InstallAddins (Registry, message, (string[]) notInstalled.ToArray (typeof(string))); } // Enables or disables conflict checking while loading assemblies. // Disabling makes loading faster, but less safe. internal bool CheckAssemblyLoadConflicts { get { return checkAssemblyLoadConflicts; } set { checkAssemblyLoadConflicts = value; } } /// <summary> /// Checks if an add-in has been loaded. /// </summary> /// <param name="id"> /// Full identifier of the add-in. /// </param> /// <returns> /// True if the add-in is loaded. /// </returns> public bool IsAddinLoaded (string id) { CheckInitialized (); return loadedAddins.Contains (Addin.GetIdName (id)); } internal RuntimeAddin GetAddin (string id) { return (RuntimeAddin) loadedAddins [Addin.GetIdName (id)]; } internal void ActivateAddin (string id) { ActivateAddinExtensions (id); } internal void UnloadAddin (string id) { RemoveAddinExtensions (id); RuntimeAddin addin = GetAddin (id); if (addin != null) { addin.UnloadExtensions (); loadedAddins.Remove (Addin.GetIdName (id)); if (addin.AssembliesLoaded) { foreach (Assembly asm in addin.Assemblies) loadedAssemblies.Remove (asm); } ReportAddinUnload (id); } } /// <summary> /// Forces the loading of an add-in. /// </summary> /// <param name="statusMonitor"> /// Status monitor to keep track of the loading process. /// </param> /// <param name="id"> /// Full identifier of the add-in to load. /// </param> /// <remarks> /// This method loads all assemblies that belong to an add-in in memory. /// All add-ins on which the specified add-in depends will also be loaded. /// Notice that in general add-ins don't need to be explicitely loaded using /// this method, since the add-in engine will load them on demand. /// </remarks> public void LoadAddin (IProgressStatus statusMonitor, string id) { CheckInitialized (); LoadAddin (statusMonitor, id, true); } internal bool LoadAddin (IProgressStatus statusMonitor, string id, bool throwExceptions) { try { if (IsAddinLoaded (id)) return true; if (!Registry.IsAddinEnabled (id)) { string msg = GettextCatalog.GetString ("Disabled add-ins can't be loaded."); ReportError (msg, id, null, false); if (throwExceptions) throw new InvalidOperationException (msg); return false; } ArrayList addins = new ArrayList (); Stack depCheck = new Stack (); ResolveLoadDependencies (addins, depCheck, id, false); addins.Reverse (); if (statusMonitor != null) statusMonitor.SetMessage ("Loading Addins"); for (int n=0; n<addins.Count; n++) { if (statusMonitor != null) statusMonitor.SetProgress ((double) n / (double)addins.Count); Addin iad = (Addin) addins [n]; if (IsAddinLoaded (iad.Id)) continue; if (statusMonitor != null) statusMonitor.SetMessage (string.Format(GettextCatalog.GetString("Loading {0} add-in"), iad.Id)); if (!InsertAddin (statusMonitor, iad)) return false; } return true; } catch (Exception ex) { ReportError ("Add-in could not be loaded: " + ex.Message, id, ex, false); if (statusMonitor != null) statusMonitor.ReportError ("Add-in '" + id + "' could not be loaded.", ex); if (throwExceptions) throw; return false; } } internal override void ResetCachedData () { foreach (RuntimeAddin ad in loadedAddins.Values) ad.Addin.ResetCachedData (); base.ResetCachedData (); } bool InsertAddin (IProgressStatus statusMonitor, Addin iad) { try { RuntimeAddin p = new RuntimeAddin (this); // Read the config file and load the add-in assemblies AddinDescription description = p.Load (iad); // Register the add-in loadedAddins [Addin.GetIdName (p.Id)] = p; if (!AddinDatabase.RunningSetupProcess) { // Load the extension points and other addin data foreach (ExtensionNodeSet rel in description.ExtensionNodeSets) { RegisterNodeSet (iad.Id, rel); } foreach (ConditionTypeDescription cond in description.ConditionTypes) { Type ctype = p.GetType (cond.TypeName, true); RegisterCondition (cond.Id, ctype); } } foreach (ExtensionPoint ep in description.ExtensionPoints) InsertExtensionPoint (p, ep); // Fire loaded event NotifyAddinLoaded (p); ReportAddinLoad (p.Id); return true; } catch (Exception ex) { ReportError ("Add-in could not be loaded", iad.Id, ex, false); if (statusMonitor != null) statusMonitor.ReportError ("Add-in '" + iad.Id + "' could not be loaded.", ex); return false; } } internal void RegisterAssemblies (RuntimeAddin addin) { foreach (Assembly asm in addin.Assemblies) loadedAssemblies [asm] = addin; } internal void InsertExtensionPoint (RuntimeAddin addin, ExtensionPoint ep) { CreateExtensionPoint (ep); foreach (ExtensionNodeType nt in ep.NodeSet.NodeTypes) { if (nt.ObjectTypeName.Length > 0) { Type ntype = addin.GetType (nt.ObjectTypeName, true); RegisterAutoTypeExtensionPoint (ntype, ep.Path); } } } bool ResolveLoadDependencies (ArrayList addins, Stack depCheck, string id, bool optional) { if (IsAddinLoaded (id)) return true; if (depCheck.Contains (id)) throw new InvalidOperationException ("A cyclic addin dependency has been detected."); depCheck.Push (id); Addin iad = Registry.GetAddin (id); if (iad == null || !iad.Enabled) { if (optional) return false; else if (iad != null && !iad.Enabled) throw new MissingDependencyException (GettextCatalog.GetString ("The required addin '{0}' is disabled.", id)); else throw new MissingDependencyException (GettextCatalog.GetString ("The required addin '{0}' is not installed.", id)); } // If this addin has already been requested, bring it to the head // of the list, so it is loaded earlier than before. addins.Remove (iad); addins.Add (iad); foreach (Dependency dep in iad.AddinInfo.Dependencies) { AddinDependency adep = dep as AddinDependency; if (adep != null) { try { string adepid = Addin.GetFullId (iad.AddinInfo.Namespace, adep.AddinId, adep.Version); ResolveLoadDependencies (addins, depCheck, adepid, false); } catch (MissingDependencyException) { if (optional) return false; else throw; } } } if (iad.AddinInfo.OptionalDependencies != null) { foreach (Dependency dep in iad.AddinInfo.OptionalDependencies) { AddinDependency adep = dep as AddinDependency; if (adep != null) { string adepid = Addin.GetFullId (iad.Namespace, adep.AddinId, adep.Version); if (!ResolveLoadDependencies (addins, depCheck, adepid, true)) return false; } } } depCheck.Pop (); return true; } internal void RegisterNodeSet (string addinId, ExtensionNodeSet nset) { nset.SourceAddinId = addinId; nodeSets [nset.Id] = nset; } internal void UnregisterAddinNodeSets (string addinId) { foreach (var nset in nodeSets.Values.Where (n => n.SourceAddinId == addinId).ToArray ()) nodeSets.Remove (nset.Id); } internal string GetNodeTypeAddin (ExtensionNodeSet nset, string type, string callingAddinId) { ExtensionNodeType nt = FindType (nset, type, callingAddinId); if (nt != null) return nt.AddinId; else return null; } internal ExtensionNodeType FindType (ExtensionNodeSet nset, string name, string callingAddinId) { if (nset == null) return null; foreach (ExtensionNodeType nt in nset.NodeTypes) { if (nt.Id == name) return nt; } foreach (string ns in nset.NodeSets) { ExtensionNodeSet regSet; if (!nodeSets.TryGetValue (ns, out regSet)) { ReportError ("Unknown node set: " + ns, callingAddinId, null, false); return null; } ExtensionNodeType nt = FindType (regSet, name, callingAddinId); if (nt != null) return nt; } return null; } internal void RegisterAutoTypeExtensionPoint (Type type, string path) { autoExtensionTypes [type] = path; } internal void UnregisterAutoTypeExtensionPoint (Type type, string path) { autoExtensionTypes.Remove (type); } internal string GetAutoTypeExtensionPoint (Type type) { return autoExtensionTypes [type] as string; } void OnAssemblyLoaded (object s, AssemblyLoadEventArgs a) { if (a != null) CheckHostAssembly (a.LoadedAssembly); } internal void ActivateRoots () { foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ()) CheckHostAssembly (asm); } void CheckHostAssembly (Assembly asm) { if (AddinDatabase.RunningSetupProcess || asm is System.Reflection.Emit.AssemblyBuilder) return; string codeBase; try { codeBase = asm.CodeBase; } catch { return; } Uri u; if (!Uri.TryCreate (codeBase, UriKind.Absolute, out u)) return; string asmFile = u.LocalPath; Addin ainfo = Registry.GetAddinForHostAssembly (asmFile); if (ainfo != null && !IsAddinLoaded (ainfo.Id)) { AddinDescription adesc = null; try { adesc = ainfo.Description; } catch (Exception ex) { defaultProgressStatus.ReportError ("Add-in description could not be loaded.", ex); } if (adesc == null || adesc.FilesChanged ()) { // If the add-in has changed, update the add-in database. // We do it here because once loaded, add-in roots can't be // reloaded like regular add-ins. Registry.Update (null); ainfo = Registry.GetAddinForHostAssembly (asmFile); if (ainfo == null) return; } LoadAddin (null, ainfo.Id, false); } } /// <summary> /// Creates a new extension context. /// </summary> /// <returns> /// The new extension context. /// </returns> /// <remarks> /// Extension contexts can be used to query the extension model using particular condition values. /// </remarks> public ExtensionContext CreateExtensionContext () { CheckInitialized (); return CreateChildContext (); } internal void CheckInitialized () { if (!initialized) throw new InvalidOperationException ("Add-in engine not initialized."); } internal void ReportError (string message, string addinId, Exception exception, bool fatal) { if (AddinLoadError != null) AddinLoadError (null, new AddinErrorEventArgs (message, addinId, exception)); else { Console.WriteLine (message); if (exception != null) Console.WriteLine (exception); } } internal void ReportAddinLoad (string id) { if (AddinLoaded != null) { try { AddinLoaded (null, new AddinEventArgs (id)); } catch { // Ignore subscriber exceptions } } } internal void ReportAddinUnload (string id) { if (AddinUnloaded != null) { try { AddinUnloaded (null, new AddinEventArgs (id)); } catch { // Ignore subscriber exceptions } } } } }
using System; namespace Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Options { public class SqlOptionIgnore { private Boolean filterIndex = true; private Boolean filterSchema = true; private Boolean filterXMLSchema = true; private Boolean filterTrigger = true; private Boolean filterUserDataType = true; private Boolean filterTableOption = true; private Boolean filterTableLockEscalation = true; private Boolean filterTableChangeTracking = true; private Boolean filterTable = true; private Boolean filterView = true; private Boolean filterStoreProcedure = true; private Boolean filterFunction = true; private Boolean filterTableFileGroup = true; private Boolean filterExtendedPropertys = true; private Boolean filterDDLTriggers = true; private Boolean filterSynonyms = true; private Boolean filterRules = true; private Boolean filterFullText = true; private Boolean filterFullTextPath = false; private Boolean filterConstraint = true; private Boolean filterConstraintPK = true; private Boolean filterConstraintFK = true; private Boolean filterConstraintUK = true; private Boolean filterConstraintCheck = true; private Boolean filterIndexFillFactor = true; private Boolean filterIndexRowLock = true; private Boolean filterIndexIncludeColumns = true; private Boolean filterIndexFilter = true; private Boolean filterColumnOrder = true; private Boolean filterColumnIdentity = true; private Boolean filterColumnCollation = true; private Boolean filterNotForReplication = true; private Boolean filterUsers = true; private Boolean filterRoles = true; private Boolean filterPartitionScheme = true; private Boolean filterPartitionFunction = true; private Boolean filterAssemblies = true; private Boolean filterCLRStoreProcedure = true; private Boolean filterCLRFunction = true; private Boolean filterCLRTrigger = true; private Boolean filterCLRUDT = true; public SqlOptionIgnore(Boolean defaultValue) { FilterConstraint = defaultValue; FilterFunction = defaultValue; FilterStoreProcedure = defaultValue; FilterView = defaultValue; FilterTable = defaultValue; FilterTableOption = defaultValue; FilterUserDataType = defaultValue; FilterTrigger = defaultValue; FilterSchema = defaultValue; FilterXMLSchema = defaultValue; FilterTableFileGroup = defaultValue; FilterExtendedPropertys = defaultValue; FilterDDLTriggers = defaultValue; FilterSynonyms = defaultValue; FilterRules = defaultValue; FilterAssemblies = defaultValue; } public Boolean FilterTableChangeTracking { get { return filterTableChangeTracking; } set { filterTableChangeTracking = value; } } public Boolean FilterTableLockEscalation { get { return filterTableLockEscalation; } set { filterTableLockEscalation = value; } } public Boolean FilterFullTextPath { get { return filterFullTextPath; } set { filterFullTextPath = value; } } public Boolean FilterFullText { get { return filterFullText; } set { filterFullText = value; } } public Boolean FilterCLRStoreProcedure { get { return filterCLRStoreProcedure; } set { filterCLRStoreProcedure = value; } } public Boolean FilterCLRUDT { get { return filterCLRUDT; } set { filterCLRUDT = value; } } public Boolean FilterCLRTrigger { get { return filterCLRTrigger; } set { filterCLRTrigger = value; } } public Boolean FilterCLRFunction { get { return filterCLRFunction; } set { filterCLRFunction = value; } } public Boolean FilterRoles { get { return filterRoles; } set { filterRoles = value; } } public Boolean FilterUsers { get { return filterUsers; } set { filterUsers = value; } } public Boolean FilterNotForReplication { get { return filterNotForReplication; } set { filterNotForReplication = value; } } public Boolean FilterColumnCollation { get { return filterColumnCollation; } set { filterColumnCollation = value; } } public Boolean FilterColumnIdentity { get { return filterColumnIdentity; } set { filterColumnIdentity = value; } } public Boolean FilterColumnOrder { get { return filterColumnOrder; } set { filterColumnOrder = value; } } public Boolean FilterIndexRowLock { get { return filterIndexRowLock; } set { filterIndexRowLock = value; } } public Boolean FilterIndexIncludeColumns { get { return filterIndexIncludeColumns; } set { filterIndexIncludeColumns = value; } } public Boolean FilterIndexFillFactor { get { return filterIndexFillFactor; } set { filterIndexFillFactor = value; } } public Boolean FilterAssemblies { get { return filterAssemblies; } set { filterAssemblies = value; } } public Boolean FilterRules { get { return filterRules; } set { filterRules = value; } } public Boolean FilterSynonyms { get { return filterSynonyms; } set { filterSynonyms = value; } } public Boolean FilterDDLTriggers { get { return filterDDLTriggers; } set { filterDDLTriggers = value; } } public Boolean FilterExtendedPropertys { get { return filterExtendedPropertys; } set { filterExtendedPropertys = value; } } public Boolean FilterTableFileGroup { get { return filterTableFileGroup; } set { filterTableFileGroup = value; } } public Boolean FilterFunction { get { return filterFunction; } set { filterFunction = value; } } public Boolean FilterStoreProcedure { get { return filterStoreProcedure; } set { filterStoreProcedure = value; } } public Boolean FilterView { get { return filterView; } set { filterView = value; } } public Boolean FilterTable { get { return filterTable; } set { filterTable = value; } } public Boolean FilterTableOption { get { return filterTableOption; } set { filterTableOption = value; } } public Boolean FilterUserDataType { get { return filterUserDataType; } set { filterUserDataType = value; } } public Boolean FilterTrigger { get { return filterTrigger; } set { filterTrigger = value; } } public Boolean FilterXMLSchema { get { return filterXMLSchema; } set { filterXMLSchema = value; } } public Boolean FilterSchema { get { return filterSchema; } set { filterSchema = value; } } public Boolean FilterConstraint { get { return filterConstraint; } set { filterConstraint = value; } } public Boolean FilterConstraintCheck { get { return filterConstraintCheck; } set { filterConstraintCheck = value; } } public Boolean FilterConstraintUK { get { return filterConstraintUK; } set { filterConstraintUK = value; } } public Boolean FilterConstraintFK { get { return filterConstraintFK; } set { filterConstraintFK = value; } } public Boolean FilterConstraintPK { get { return filterConstraintPK; } set { filterConstraintPK = value; } } public Boolean FilterIndex { get { return filterIndex; } set { filterIndex = value; } } public Boolean FilterIndexFilter { get { return filterIndexFilter; } set { filterIndexFilter = value; } } public Boolean FilterPartitionScheme { get { return filterPartitionScheme; } set { filterPartitionScheme = value; } } public Boolean FilterPartitionFunction { get { return filterPartitionFunction; } set { filterPartitionFunction = value; } } } }
// 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.Diagnostics.Contracts; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.InteropServices; using System.Runtime.WindowsRuntime.Internal; using System.Threading.Tasks; using System.Threading; using Windows.Foundation; using Windows.Storage.Streams; namespace System.IO { /// <summary> /// A <code>Stream</code> used to wrap a Windows Runtime stream to expose it as a managed steam. /// </summary> internal class WinRtToNetFxStreamAdapter : Stream, IDisposable { #region Construction internal static WinRtToNetFxStreamAdapter Create(Object windowsRuntimeStream) { if (windowsRuntimeStream == null) throw new ArgumentNullException(nameof(windowsRuntimeStream)); bool canRead = windowsRuntimeStream is IInputStream; bool canWrite = windowsRuntimeStream is IOutputStream; bool canSeek = windowsRuntimeStream is IRandomAccessStream; if (!canRead && !canWrite && !canSeek) throw new ArgumentException(SR.Argument_ObjectMustBeWinRtStreamToConvertToNetFxStream); // Proactively guard against a non-conforming curstomer implementations: if (canSeek) { IRandomAccessStream iras = (IRandomAccessStream)windowsRuntimeStream; if (!canRead && iras.CanRead) throw new ArgumentException(SR.Argument_InstancesImplementingIRASThatCanReadMustImplementIIS); if (!canWrite && iras.CanWrite) throw new ArgumentException(SR.Argument_InstancesImplementingIRASThatCanWriteMustImplementIOS); if (!iras.CanRead) canRead = false; if (!iras.CanWrite) canWrite = false; } if (!canRead && !canWrite) throw new ArgumentException(SR.Argument_WinRtStreamCannotReadOrWrite); return new WinRtToNetFxStreamAdapter(windowsRuntimeStream, canRead, canWrite, canSeek); } private WinRtToNetFxStreamAdapter(Object winRtStream, bool canRead, bool canWrite, bool canSeek) { Contract.Requires(winRtStream != null); Contract.Requires(winRtStream is IInputStream || winRtStream is IOutputStream || winRtStream is IRandomAccessStream); Contract.Requires((canSeek && (winRtStream is IRandomAccessStream)) || (!canSeek && !(winRtStream is IRandomAccessStream))); Contract.Requires((canRead && (winRtStream is IInputStream)) || (!canRead && ( !(winRtStream is IInputStream) || (winRtStream is IRandomAccessStream && !((IRandomAccessStream)winRtStream).CanRead) )) ); Contract.Requires((canWrite && (winRtStream is IOutputStream)) || (!canWrite && ( !(winRtStream is IOutputStream) || (winRtStream is IRandomAccessStream && !((IRandomAccessStream)winRtStream).CanWrite) )) ); Contract.EndContractBlock(); _winRtStream = winRtStream; _canRead = canRead; _canWrite = canWrite; _canSeek = canSeek; } #endregion Construction #region Instance variables private Byte[] _oneByteBuffer = null; private bool _leaveUnderlyingStreamOpen = true; private Object _winRtStream; private readonly bool _canRead; private readonly bool _canWrite; private readonly bool _canSeek; #endregion Instance variables #region Tools and Helpers /// <summary> /// We keep tables for mappings between managed and WinRT streams to make sure to always return the same adapter for a given underlying stream. /// However, in order to avoid global locks on those tables, several instances of this type may be created and then can race to be entered /// into the appropriate map table. All except for the winning instances will be thrown away. However, we must ensure that when the losers are /// finalized, the do not dispose the underlying stream. To ensure that, we must call this method on the winner to notify it that it is safe to /// dispose the underlying stream. /// </summary> internal void SetWonInitializationRace() { _leaveUnderlyingStreamOpen = false; } public TWinRtStream GetWindowsRuntimeStream<TWinRtStream>() where TWinRtStream : class { Object wrtStr = _winRtStream; if (wrtStr == null) return null; Debug.Assert(wrtStr is TWinRtStream, String.Format("Attempted to get the underlying WinRT stream typed as \"{0}\"," + " but the underlying WinRT stream cannot be cast to that type. Its actual type is \"{1}\".", typeof(TWinRtStream).ToString(), wrtStr.GetType().ToString())); return wrtStr as TWinRtStream; } private Byte[] OneByteBuffer { get { Byte[] obb = _oneByteBuffer; if (obb == null) // benign race for multiple init _oneByteBuffer = obb = new Byte[1]; return obb; } } #if DEBUG private static void AssertValidStream(Object winRtStream) { Debug.Assert(winRtStream != null, "This to-NetFx Stream adapter must not be disposed and the underlying WinRT stream must be of compatible type for this operation"); } #endif // DEBUG private TWinRtStream EnsureNotDisposed<TWinRtStream>() where TWinRtStream : class { Object wrtStr = _winRtStream; if (wrtStr == null) throw new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation); return (wrtStr as TWinRtStream); } private void EnsureNotDisposed() { if (_winRtStream == null) throw new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation); } private void EnsureCanRead() { if (!_canRead) throw new NotSupportedException(SR.NotSupported_CannotReadFromStream); } private void EnsureCanWrite() { if (!_canWrite) throw new NotSupportedException(SR.NotSupported_CannotWriteToStream); } #endregion Tools and Helpers #region Simple overrides protected override void Dispose(bool disposing) { // WinRT streams should implement IDisposable (IClosable in WinRT), but let's be defensive: if (disposing && _winRtStream != null && !_leaveUnderlyingStreamOpen) { IDisposable disposableWinRtStream = _winRtStream as IDisposable; // benign race on winRtStream if (disposableWinRtStream != null) disposableWinRtStream.Dispose(); } _winRtStream = null; base.Dispose(disposing); } public override bool CanRead { [Pure] get { return (_canRead && _winRtStream != null); } } public override bool CanWrite { [Pure] get { return (_canWrite && _winRtStream != null); } } public override bool CanSeek { [Pure] get { return (_canSeek && _winRtStream != null); } } #endregion Simple overrides #region Length and Position functions public override Int64 Length { get { IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>(); if (!_canSeek) throw new NotSupportedException(SR.NotSupported_CannotUseLength_StreamNotSeekable); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG UInt64 size = wrtStr.Size; // These are over 8000 PetaBytes, we do not expect this to happen. However, let's be defensive: if (size > (UInt64)Int64.MaxValue) throw new IOException(SR.IO_UnderlyingWinRTStreamTooLong_CannotUseLengthOrPosition); return unchecked((Int64)size); } } public override Int64 Position { get { IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>(); if (!_canSeek) throw new NotSupportedException(SR.NotSupported_CannotUsePosition_StreamNotSeekable); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG UInt64 pos = wrtStr.Position; // These are over 8000 PetaBytes, we do not expect this to happen. However, let's be defensive: if (pos > (UInt64)Int64.MaxValue) throw new IOException(SR.IO_UnderlyingWinRTStreamTooLong_CannotUseLengthOrPosition); return unchecked((Int64)pos); } set { if (value < 0) throw new ArgumentOutOfRangeException("Position", SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition); Contract.EndContractBlock(); IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>(); if (!_canSeek) throw new NotSupportedException(SR.NotSupported_CannotUsePosition_StreamNotSeekable); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG wrtStr.Seek(unchecked((UInt64)value)); } } public override Int64 Seek(Int64 offset, SeekOrigin origin) { IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>(); if (!_canSeek) throw new NotSupportedException(SR.NotSupported_CannotSeekInStream); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG switch (origin) { case SeekOrigin.Begin: { Position = offset; return offset; } case SeekOrigin.Current: { Int64 curPos = Position; if (Int64.MaxValue - curPos < offset) throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue); Int64 newPos = curPos + offset; if (newPos < 0) throw new IOException(SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition); Position = newPos; return newPos; } case SeekOrigin.End: { UInt64 size = wrtStr.Size; Int64 newPos; if (size > (UInt64)Int64.MaxValue) { if (offset >= 0) throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue); Debug.Assert(offset < 0); UInt64 absOffset = (offset == Int64.MinValue) ? ((UInt64)Int64.MaxValue) + 1 : (UInt64)(-offset); Debug.Assert(absOffset <= size); UInt64 np = size - absOffset; if (np > (UInt64)Int64.MaxValue) throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue); newPos = (Int64)np; } else { Debug.Assert(size <= (UInt64)Int64.MaxValue); Int64 s = unchecked((Int64)size); if (Int64.MaxValue - s < offset) throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue); newPos = s + offset; if (newPos < 0) throw new IOException(SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition); } Position = newPos; return newPos; } default: { throw new ArgumentException(nameof(origin)); } } } public override void SetLength(Int64 value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_CannotResizeStreamToNegative); Contract.EndContractBlock(); IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>(); if (!_canSeek) throw new NotSupportedException(SR.NotSupported_CannotSeekInStream); EnsureCanWrite(); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG wrtStr.Size = unchecked((UInt64)value); // If the length is set to a value < that the current position, then we need to set the position to that value // Because we can't directly set the position, we are going to seek to it. if (wrtStr.Size < wrtStr.Position) wrtStr.Seek(unchecked((UInt64)value)); } #endregion Length and Position functions #region Reading private IAsyncResult BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state, bool usedByBlockingWrapper) { // This method is somewhat tricky: We could consider just calling ReadAsync (recall that Task implements IAsyncResult). // It would be OK for cases where BeginRead is invoked directly by the public user. // However, in cases where it is invoked by Read to achieve a blocking (synchronous) IO operation, the ReadAsync-approach may deadlock: // // The sync-over-async IO operation will be doing a blocking wait on the completion of the async IO operation assuming that // a wait handle would be signalled by the completion handler. Recall that the IAsyncInfo representing the IO operation may // not be free-threaded and not "free-marshalled"; it may also belong to an ASTA compartment because the underlying WinRT // stream lives in an ASTA compartment. The completion handler is invoked on a pool thread, i.e. in MTA. // That handler needs to fetch the results from the async IO operation, which requires a cross-compartment call from MTA into ASTA. // But because the ASTA thread is busy waiting this call will deadlock. // (Recall that although WaitOne pumps COM, ASTA specifically schedules calls on the outermost ?idle? pump only.) // // The solution is to make sure that: // - In cases where main thread is waiting for the async IO to complete: // Fetch results on the main thread after it has been signalled by the completion callback. // - In cases where main thread is not waiting for the async IO to complete: // Fetch results in the completion callback. // // But the Task-plumbing around IAsyncInfo.AsTask *always* fetches results in the completion handler because it has // no way of knowing whether or not someone is waiting. So, instead of using ReadAsync here we implement our own IAsyncResult // and our own completion handler which can behave differently according to whether it is being used by a blocking IO // operation wrapping a BeginRead/EndRead pair, or by an actual async operation based on the old Begin/End pattern. if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer); Contract.EndContractBlock(); IInputStream wrtStr = EnsureNotDisposed<IInputStream>(); EnsureCanRead(); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG IBuffer userBuffer = buffer.AsBuffer(offset, count); IAsyncOperationWithProgress<IBuffer, UInt32> asyncReadOperation = wrtStr.ReadAsync(userBuffer, unchecked((UInt32)count), InputStreamOptions.Partial); StreamReadAsyncResult asyncResult = new StreamReadAsyncResult(asyncReadOperation, userBuffer, callback, state, processCompletedOperationInCallback: !usedByBlockingWrapper); // The StreamReadAsyncResult will set a private instance method to act as a Completed handler for asyncOperation. // This will cause a CCW to be created for the delegate and the delegate has a reference to its target, i.e. to // asyncResult, so asyncResult will not be collected. If we loose the entire AppDomain, then asyncResult and its CCW // will be collected but the stub will remain and the callback will fail gracefully. The underlying buffer is the only // item to whcih we expose a direct pointer and this is properly pinned using a mechanism similar to Overlapped. return asyncResult; } #if dotnet53 public override Int32 EndRead(IAsyncResult asyncResult) #else public Int32 EndRead(IAsyncResult asyncResult) #endif { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); Contract.EndContractBlock(); EnsureNotDisposed(); EnsureCanRead(); StreamOperationAsyncResult streamAsyncResult = asyncResult as StreamOperationAsyncResult; if (streamAsyncResult == null) throw new ArgumentException(SR.Argument_UnexpectedAsyncResult, nameof(asyncResult)); streamAsyncResult.Wait(); try { // If the async result did NOT process the async IO operation in its completion handler (i.e. check for errors, // cache results etc), then we need to do that processing now. This is to allow blocking-over-async IO operations. // See the big comment in BeginRead for details. if (!streamAsyncResult.ProcessCompletedOperationInCallback) streamAsyncResult.ProcessCompletedOperation(); // Rethrow errors caught in the completion callback, if any: if (streamAsyncResult.HasError) { streamAsyncResult.CloseStreamOperation(); streamAsyncResult.ThrowCachedError(); } // Done: Int64 bytesCompleted = streamAsyncResult.BytesCompleted; Debug.Assert(bytesCompleted <= unchecked((Int64)Int32.MaxValue)); return (Int32)bytesCompleted; } finally { // Closing multiple times is Ok. streamAsyncResult.CloseStreamOperation(); } } public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer); Contract.EndContractBlock(); EnsureNotDisposed(); EnsureCanRead(); // If already cancelled, bail early: cancellationToken.ThrowIfCancellationRequested(); // State is Ok. Do the actual read: return ReadAsyncInternal(buffer, offset, count, cancellationToken); } public override Int32 Read([In, Out] Byte[] buffer, Int32 offset, Int32 count) { // Arguments validation and not-disposed validation are done in BeginRead. IAsyncResult asyncResult = BeginRead(buffer, offset, count, null, null, usedByBlockingWrapper: true); Int32 bytesRead = EndRead(asyncResult); return bytesRead; } public override Int32 ReadByte() { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < 256); Contract.EndContractBlock(); // EnsureNotDisposed will be called in Read->BeginRead. Byte[] oneByteArray = OneByteBuffer; if (0 == Read(oneByteArray, 0, 1)) return -1; Int32 value = oneByteArray[0]; return value; } #endregion Reading #region Writing #if dotnet53 public override IAsyncResult BeginWrite(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state) #else public IAsyncResult BeginWrite(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state) #endif { return BeginWrite(buffer, offset, count, callback, state, usedByBlockingWrapper: false); } private IAsyncResult BeginWrite(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state, bool usedByBlockingWrapper) { // See the large comment in BeginRead about why we are not using this.WriteAsync, // and instead using a custom implementation of IAsyncResult. if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); Contract.EndContractBlock(); IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>(); EnsureCanWrite(); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG IBuffer asyncWriteBuffer = buffer.AsBuffer(offset, count); IAsyncOperationWithProgress<UInt32, UInt32> asyncWriteOperation = wrtStr.WriteAsync(asyncWriteBuffer); StreamWriteAsyncResult asyncResult = new StreamWriteAsyncResult(asyncWriteOperation, callback, state, processCompletedOperationInCallback: !usedByBlockingWrapper); // The StreamReadAsyncResult will set a private instance method to act as a Completed handler for asyncOperation. // This will cause a CCW to be created for the delegate and the delegate has a reference to its target, i.e. to // asyncResult, so asyncResult will not be collected. If we loose the entire AppDomain, then asyncResult and its CCW // will be collected but the stub will remain and the callback will fail gracefully. The underlying buffer if the only // item to which we expose a direct pointer and this is properly pinned using a mechanism similar to Overlapped. return asyncResult; } #if dotnet53 public override void EndWrite(IAsyncResult asyncResult) #else public void EndWrite(IAsyncResult asyncResult) #endif { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); Contract.EndContractBlock(); EnsureNotDisposed(); EnsureCanWrite(); StreamOperationAsyncResult streamAsyncResult = asyncResult as StreamOperationAsyncResult; if (streamAsyncResult == null) throw new ArgumentException(SR.Argument_UnexpectedAsyncResult, nameof(asyncResult)); streamAsyncResult.Wait(); try { // If the async result did NOT process the async IO operation in its completion handler (i.e. check for errors, // cache results etc), then we need to do that processing now. This is to allow blocking-over-async IO operations. // See the big comment in BeginWrite for details. if (!streamAsyncResult.ProcessCompletedOperationInCallback) streamAsyncResult.ProcessCompletedOperation(); // Rethrow errors caught in the completion callback, if any: if (streamAsyncResult.HasError) { streamAsyncResult.CloseStreamOperation(); streamAsyncResult.ThrowCachedError(); } } finally { // Closing multiple times is Ok. streamAsyncResult.CloseStreamOperation(); } } public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); Contract.EndContractBlock(); IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>(); EnsureCanWrite(); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG // If already cancelled, bail early: cancellationToken.ThrowIfCancellationRequested(); IBuffer asyncWriteBuffer = buffer.AsBuffer(offset, count); IAsyncOperationWithProgress<UInt32, UInt32> asyncWriteOperation = wrtStr.WriteAsync(asyncWriteBuffer); Task asyncWriteTask = asyncWriteOperation.AsTask(cancellationToken); // The underlying IBuffer is the only object to which we expose a direct pointer to native, // and that is properly pinned using a mechanism similar to Overlapped. return asyncWriteTask; } public override void Write(Byte[] buffer, Int32 offset, Int32 count) { // Arguments validation and not-disposed validation are done in BeginWrite. IAsyncResult asyncResult = BeginWrite(buffer, offset, count, null, null, usedByBlockingWrapper: true); EndWrite(asyncResult); } public override void WriteByte(Byte value) { // EnsureNotDisposed will be called in Write->BeginWrite. Byte[] oneByteArray = OneByteBuffer; oneByteArray[0] = value; Write(oneByteArray, 0, 1); } #endregion Writing #region Flushing public override void Flush() { // See the large comment in BeginRead about why we are not using this.FlushAsync, // and instead using a custom implementation of IAsyncResult. IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>(); // Calling Flush in a non-writable stream is a no-op, not an error: if (!_canWrite) return; #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG IAsyncOperation<Boolean> asyncFlushOperation = wrtStr.FlushAsync(); StreamFlushAsyncResult asyncResult = new StreamFlushAsyncResult(asyncFlushOperation, processCompletedOperationInCallback: false); asyncResult.Wait(); try { // We got signaled, so process the async Flush operation back on this thread: // (This is to allow blocking-over-async IO operations. See the big comment in BeginRead for details.) asyncResult.ProcessCompletedOperation(); // Rethrow errors cached by the async result, if any: if (asyncResult.HasError) { asyncResult.CloseStreamOperation(); asyncResult.ThrowCachedError(); } } finally { // Closing multiple times is Ok. asyncResult.CloseStreamOperation(); } } public override Task FlushAsync(CancellationToken cancellationToken) { IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>(); // Calling Flush in a non-writable stream is a no-op, not an error: if (!_canWrite) return Helpers.CompletedTask; #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG cancellationToken.ThrowIfCancellationRequested(); IAsyncOperation<Boolean> asyncFlushOperation = wrtStr.FlushAsync(); Task asyncFlushTask = asyncFlushOperation.AsTask(cancellationToken); return asyncFlushTask; } #endregion Flushing #region ReadAsyncInternal implementation // Moved it to the end while using Dev10 VS because it does not understand async and everything that follows looses intellisense. // Should move this code into the Reading regios once using Dev11 VS becomes the norm. private async Task<Int32> ReadAsyncInternal(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { Contract.Requires(buffer != null); Contract.Requires(offset >= 0); Contract.Requires(count >= 0); Contract.Requires(buffer.Length - offset >= count); Contract.Requires(_canRead); IInputStream wrtStr = EnsureNotDisposed<IInputStream>(); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG try { IBuffer userBuffer = buffer.AsBuffer(offset, count); IAsyncOperationWithProgress<IBuffer, UInt32> asyncReadOperation = wrtStr.ReadAsync(userBuffer, unchecked((UInt32)count), InputStreamOptions.Partial); IBuffer resultBuffer = await asyncReadOperation.AsTask(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); // If cancellationToken was cancelled until now, then we are currently propagating the corresponding cancellation exception. // (It will be correctly rethrown by the catch block below and overall we will return a cancelled task.) // But if the underlying operation managed to complete before it was cancelled, we want // the entire task to complete as well. This is ok as the continuation is very lightweight: if (resultBuffer == null) return 0; WinRtIOHelper.EnsureResultsInUserBuffer(userBuffer, resultBuffer); Debug.Assert(resultBuffer.Length <= unchecked((UInt32)Int32.MaxValue)); return (Int32)resultBuffer.Length; } catch (Exception ex) { // If the interop layer gave us an Exception, we assume that it hit a general/unknown case and wrap it into // an IOException as this is what Stream users expect. WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw(); return 0; } } #endregion ReadAsyncInternal implementation } // class WinRtToNetFxStreamAdapter } // namespace // WinRtToNetFxStreamAdapter.cs
using System; using System.Text; namespace org.javarosa.core.util { /* * A Java implementation of the Secure Hash Algorithm, SHA-1, as defined * in FIPS PUB 180-1 * Copyright (C) Sam Ruby 2004 * All rights reserved * * Based on code Copyright (C) Paul Johnston 2000 - 2002. * See http://pajhome.org.uk/site/legal.html for details. * * Converted to Java by Russell Beattie 2004 * Base64 logic and inlining by Sam Ruby 2004 * Bug fix correcting single bit error in base64 code by John Wilson * * BSD License * * 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 author 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. */ public class SHA1 { /* * Bitwise rotate a 32-bit number to the left */ private static int rol(int num, int cnt) { return (num << cnt) | (num >> (32 - cnt)); } /* * Take a string and return the base64 representation of its SHA-1. */ public static String encodeBase64(String str) { // Convert a string to a sequence of 16-word blocks, stored as an array. // Append padding bits and the Length, as described in the SHA1 standard byte[] x = Encoding.UTF8.GetBytes(str); int[] blks = new int[(((x.Length + 8) >> 6) + 1) * 16]; int i; for (i = 0; i < x.Length; i++) { blks[i >> 2] |= x[i] << (24 - (i % 4) * 8); } blks[i >> 2] |= 0x80 << (24 - (i % 4) * 8); blks[blks.Length - 1] = x.Length * 8; // calculate 160 bit SHA1 hash of the sequence of blocks int[] w = new int[80]; int a = 1732584193; int b = -271733879; int c = -1732584194; int d = 271733878; int e = -1009589776; for (i = 0; i < blks.Length; i += 16) { int olda = a; int oldb = b; int oldc = c; int oldd = d; int olde = e; for (int j = 0; j < 80; j++) { w[j] = (j < 16) ? blks[i + j] : (rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1)); int t = rol(a, 5) + e + w[j] + ((j < 20) ? 1518500249 + ((b & c) | ((~b) & d)) : (j < 40) ? 1859775393 + (b ^ c ^ d) : (j < 60) ? -1894007588 + ((b & c) | (b & d) | (c & d)) : -899497514 + (b ^ c ^ d)); e = d; d = c; c = rol(b, 30); b = a; a = t; } a = a + olda; b = b + oldb; c = c + oldc; d = d + oldd; e = e + olde; } // Convert 160 bit hash to base64 int[] words = { a, b, c, d, e, 0 }; byte[] base64 = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"); byte[] result = new byte[28]; for (i = 0; i < 27; i++) { int start = i * 6; int word = start >> 5; int offset = start & 0x1f; if (offset <= 26) { result[i] = base64[(words[word] >> (26 - offset)) & 0x3F]; } else if (offset == 28) { result[i] = base64[(((words[word] & 0x0F) << 2) | ((words[word + 1] >> 30) & 0x03)) & 0x3F]; } else { result[i] = base64[(((words[word] & 0x03) << 4) | ((words[word + 1] >> 28) & 0x0F)) & 0x3F]; } } result[27] = (byte)'='; return result.ToString(); } /* * Take a string and return the base64 representation of its SHA-1. */ public static String encodeHex(String str) { // Convert a string to a sequence of 16-word blocks, stored as an array. // Append padding bits and the Length, as described in the SHA1 standard byte[] x = Encoding.UTF8.GetBytes(str); int[] blks = new int[(((x.Length + 8) >> 6) + 1) * 16]; int i; for (i = 0; i < x.Length; i++) { blks[i >> 2] |= x[i] << (24 - (i % 4) * 8); } blks[i >> 2] |= 0x80 << (24 - (i % 4) * 8); blks[blks.Length - 1] = x.Length * 8; // calculate 160 bit SHA1 hash of the sequence of blocks int[] w = new int[80]; int a = 1732584193; int b = -271733879; int c = -1732584194; int d = 271733878; int e = -1009589776; for (i = 0; i < blks.Length; i += 16) { int olda = a; int oldb = b; int oldc = c; int oldd = d; int olde = e; for (int j = 0; j < 80; j++) { w[j] = (j < 16) ? blks[i + j] : (rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1)); int t = rol(a, 5) + e + w[j] + ((j < 20) ? 1518500249 + ((b & c) | ((~b) & d)) : (j < 40) ? 1859775393 + (b ^ c ^ d) : (j < 60) ? -1894007588 + ((b & c) | (b & d) | (c & d)) : -899497514 + (b ^ c ^ d)); e = d; d = c; c = rol(b, 30); b = a; a = t; } a = a + olda; b = b + oldb; c = c + oldc; d = d + oldd; e = e + olde; } // Convert 160 bit hash to base64 int[] words = { a, b, c, d, e }; String encoded = ""; foreach (int word in words) { //String hexWord = Integer.toHexString(word); String hexWord = word.ToString("X8"); //Because to hexstring apparently doesn't pad? while (hexWord.Length < 8) { hexWord = "0" + hexWord; } encoded += hexWord; } return encoded; } } }
// 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.IO; using System.Linq; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Net.Http.Tests { public class HttpContentHeadersTest { private HttpContentHeaders _headers; public HttpContentHeadersTest() { _headers = new HttpContentHeaders(null); } [Fact] public void ContentLength_AddInvalidValueUsingUnusualCasing_ParserRetrievedUsingCaseInsensitiveComparison() { _headers = new HttpContentHeaders(new ComputeLengthHttpContent(() => 15)); // Use uppercase header name to make sure the parser gets retrieved using case-insensitive comparison. Assert.Throws<FormatException>(() => { _headers.Add("CoNtEnT-LeNgTh", "this is invalid"); }); } [Fact] public void ContentLength_ReadValue_TryComputeLengthInvoked() { _headers = new HttpContentHeaders(new ComputeLengthHttpContent(() => 15)); // The delegate is invoked to return the length. Assert.Equal(15, _headers.ContentLength); Assert.Equal((long)15, _headers.GetParsedValues(KnownHeaders.ContentLength.Descriptor)); // After getting the calculated content length, set it to null. _headers.ContentLength = null; Assert.Null(_headers.ContentLength); Assert.False(_headers.Contains(KnownHeaders.ContentLength.Name)); _headers.ContentLength = 27; Assert.Equal((long)27, _headers.ContentLength); Assert.Equal((long)27, _headers.GetParsedValues(KnownHeaders.ContentLength.Descriptor)); } [Fact] public void ContentLength_SetCustomValue_TryComputeLengthNotInvoked() { _headers = new HttpContentHeaders(new ComputeLengthHttpContent(() => { throw new ShouldNotBeInvokedException(); })); _headers.ContentLength = 27; Assert.Equal((long)27, _headers.ContentLength); Assert.Equal((long)27, _headers.GetParsedValues(KnownHeaders.ContentLength.Descriptor)); // After explicitly setting the content length, set it to null. _headers.ContentLength = null; Assert.Null(_headers.ContentLength); Assert.False(_headers.Contains(KnownHeaders.ContentLength.Name)); // Make sure the header gets serialized correctly _headers.ContentLength = 12345; Assert.Equal("12345", _headers.GetValues("Content-Length").First()); } [Fact] public void ContentLength_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers = new HttpContentHeaders(new ComputeLengthHttpContent(() => { throw new ShouldNotBeInvokedException(); })); _headers.TryAddWithoutValidation(HttpKnownHeaderNames.ContentLength, " 68 \r\n "); Assert.Equal(68, _headers.ContentLength); } [Fact] public void ContentType_ReadAndWriteProperty_ValueMatchesPriorSetValue() { MediaTypeHeaderValue value = new MediaTypeHeaderValue("text/plain"); value.CharSet = "utf-8"; value.Parameters.Add(new NameValueHeaderValue("custom", "value")); Assert.Null(_headers.ContentType); _headers.ContentType = value; Assert.Same(value, _headers.ContentType); _headers.ContentType = null; Assert.Null(_headers.ContentType); } [Fact] public void ContentType_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Content-Type", "text/plain; charset=utf-8; custom=value"); MediaTypeHeaderValue value = new MediaTypeHeaderValue("text/plain"); value.CharSet = "utf-8"; value.Parameters.Add(new NameValueHeaderValue("custom", "value")); Assert.Equal(value, _headers.ContentType); } [Fact] public void ContentType_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Content-Type", "text/plain; charset=utf-8; custom=value, other/type"); Assert.Null(_headers.ContentType); Assert.Equal(1, _headers.GetValues("Content-Type").Count()); Assert.Equal("text/plain; charset=utf-8; custom=value, other/type", _headers.GetValues("Content-Type").First()); _headers.Clear(); _headers.TryAddWithoutValidation("Content-Type", ",text/plain"); // leading separator Assert.Null(_headers.ContentType); Assert.Equal(1, _headers.GetValues("Content-Type").Count()); Assert.Equal(",text/plain", _headers.GetValues("Content-Type").First()); _headers.Clear(); _headers.TryAddWithoutValidation("Content-Type", "text/plain,"); // trailing separator Assert.Null(_headers.ContentType); Assert.Equal(1, _headers.GetValues("Content-Type").Count()); Assert.Equal("text/plain,", _headers.GetValues("Content-Type").First()); } [Fact] public void ContentRange_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(_headers.ContentRange); ContentRangeHeaderValue value = new ContentRangeHeaderValue(1, 2, 3); _headers.ContentRange = value; Assert.Equal(value, _headers.ContentRange); _headers.ContentRange = null; Assert.Null(_headers.ContentRange); } [Fact] public void ContentRange_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Content-Range", "custom 1-2/*"); ContentRangeHeaderValue value = new ContentRangeHeaderValue(1, 2); value.Unit = "custom"; Assert.Equal(value, _headers.ContentRange); } [Fact] public void ContentLocation_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(_headers.ContentLocation); Uri expected = new Uri("http://example.com/path/"); _headers.ContentLocation = expected; Assert.Equal(expected, _headers.ContentLocation); _headers.ContentLocation = null; Assert.Null(_headers.ContentLocation); Assert.False(_headers.Contains("Content-Location")); } [Fact] public void ContentLocation_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Content-Location", " http://www.example.com/path/?q=v "); Assert.Equal(new Uri("http://www.example.com/path/?q=v"), _headers.ContentLocation); _headers.Clear(); _headers.TryAddWithoutValidation("Content-Location", "/relative/uri/"); Assert.Equal(new Uri("/relative/uri/", UriKind.Relative), _headers.ContentLocation); } [Fact] public void ContentLocation_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Content-Location", " http://example.com http://other"); Assert.Null(_headers.GetParsedValues(KnownHeaders.ContentLocation.Descriptor)); Assert.Equal(1, _headers.GetValues("Content-Location").Count()); Assert.Equal(" http://example.com http://other", _headers.GetValues("Content-Location").First()); _headers.Clear(); _headers.TryAddWithoutValidation("Content-Location", "http://host /other"); Assert.Null(_headers.GetParsedValues(KnownHeaders.ContentLocation.Descriptor)); Assert.Equal(1, _headers.GetValues("Content-Location").Count()); Assert.Equal("http://host /other", _headers.GetValues("Content-Location").First()); } [Fact] public void ContentEncoding_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, _headers.ContentEncoding.Count); _headers.ContentEncoding.Add("custom1"); _headers.ContentEncoding.Add("custom2"); Assert.Equal(2, _headers.ContentEncoding.Count); Assert.Equal(2, _headers.GetValues("Content-Encoding").Count()); Assert.Equal("custom1", _headers.ContentEncoding.ElementAt(0)); Assert.Equal("custom2", _headers.ContentEncoding.ElementAt(1)); _headers.ContentEncoding.Clear(); Assert.Equal(0, _headers.ContentEncoding.Count); Assert.False(_headers.Contains("Content-Encoding")); } [Fact] public void ContentEncoding_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Content-Encoding", ",custom1, custom2, custom3,"); Assert.Equal(3, _headers.ContentEncoding.Count); Assert.Equal(3, _headers.GetValues("Content-Encoding").Count()); Assert.Equal("custom1", _headers.ContentEncoding.ElementAt(0)); Assert.Equal("custom2", _headers.ContentEncoding.ElementAt(1)); Assert.Equal("custom3", _headers.ContentEncoding.ElementAt(2)); _headers.ContentEncoding.Clear(); Assert.Equal(0, _headers.ContentEncoding.Count); Assert.False(_headers.Contains("Content-Encoding")); } [Fact] public void ContentEncoding_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Content-Encoding", "custom1 custom2"); // no separator Assert.Equal(0, _headers.ContentEncoding.Count); Assert.Equal(1, _headers.GetValues("Content-Encoding").Count()); Assert.Equal("custom1 custom2", _headers.GetValues("Content-Encoding").First()); } [Fact] public void ContentLanguage_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, _headers.ContentLanguage.Count); // Note that Content-Language for us is just a list of tokens. We don't verify if the format is a valid // language tag. Users will pass the language tag to other classes like Encoding.GetEncoding() to retrieve // an encoding. These classes will do not only syntax checking but also verify if the language tag exists. _headers.ContentLanguage.Add("custom1"); _headers.ContentLanguage.Add("custom2"); Assert.Equal(2, _headers.ContentLanguage.Count); Assert.Equal(2, _headers.GetValues("Content-Language").Count()); Assert.Equal("custom1", _headers.ContentLanguage.ElementAt(0)); Assert.Equal("custom2", _headers.ContentLanguage.ElementAt(1)); _headers.ContentLanguage.Clear(); Assert.Equal(0, _headers.ContentLanguage.Count); Assert.False(_headers.Contains("Content-Language")); } [Fact] public void ContentLanguage_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Content-Language", ",custom1, custom2, custom3,"); Assert.Equal(3, _headers.ContentLanguage.Count); Assert.Equal(3, _headers.GetValues("Content-Language").Count()); Assert.Equal("custom1", _headers.ContentLanguage.ElementAt(0)); Assert.Equal("custom2", _headers.ContentLanguage.ElementAt(1)); Assert.Equal("custom3", _headers.ContentLanguage.ElementAt(2)); _headers.ContentLanguage.Clear(); Assert.Equal(0, _headers.ContentLanguage.Count); Assert.False(_headers.Contains("Content-Language")); } [Fact] public void ContentLanguage_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Content-Language", "custom1 custom2"); // no separator Assert.Equal(0, _headers.ContentLanguage.Count); Assert.Equal(1, _headers.GetValues("Content-Language").Count()); Assert.Equal("custom1 custom2", _headers.GetValues("Content-Language").First()); } [Fact] public void ContentMD5_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(_headers.ContentMD5); byte[] expected = new byte[] { 1, 2, 3, 4, 5, 6, 7 }; _headers.ContentMD5 = expected; Assert.Equal(expected, _headers.ContentMD5); // must be the same object reference // Make sure the header gets serialized correctly Assert.Equal("AQIDBAUGBw==", _headers.GetValues("Content-MD5").First()); _headers.ContentMD5 = null; Assert.Null(_headers.ContentMD5); Assert.False(_headers.Contains("Content-MD5")); } [Fact] public void ContentMD5_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Content-MD5", " lvpAKQ== "); Assert.Equal(new byte[] { 150, 250, 64, 41 }, _headers.ContentMD5); _headers.Clear(); _headers.TryAddWithoutValidation("Content-MD5", "+dIkS/MnOP8="); Assert.Equal(new byte[] { 249, 210, 36, 75, 243, 39, 56, 255 }, _headers.ContentMD5); } [Fact] public void ContentMD5_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Content-MD5", "AQ--"); Assert.Null(_headers.GetParsedValues(KnownHeaders.ContentMD5.Descriptor)); Assert.Equal(1, _headers.GetValues("Content-MD5").Count()); Assert.Equal("AQ--", _headers.GetValues("Content-MD5").First()); _headers.Clear(); _headers.TryAddWithoutValidation("Content-MD5", "AQ==, CD"); Assert.Null(_headers.GetParsedValues(KnownHeaders.ContentMD5.Descriptor)); Assert.Equal(1, _headers.GetValues("Content-MD5").Count()); Assert.Equal("AQ==, CD", _headers.GetValues("Content-MD5").First()); } [Fact] public void Allow_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, _headers.Allow.Count); _headers.Allow.Add("custom1"); _headers.Allow.Add("custom2"); Assert.Equal(2, _headers.Allow.Count); Assert.Equal(2, _headers.GetValues("Allow").Count()); Assert.Equal("custom1", _headers.Allow.ElementAt(0)); Assert.Equal("custom2", _headers.Allow.ElementAt(1)); _headers.Allow.Clear(); Assert.Equal(0, _headers.Allow.Count); Assert.False(_headers.Contains("Allow")); } [Fact] public void Allow_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Allow", ",custom1, custom2, custom3,"); Assert.Equal(3, _headers.Allow.Count); Assert.Equal(3, _headers.GetValues("Allow").Count()); Assert.Equal("custom1", _headers.Allow.ElementAt(0)); Assert.Equal("custom2", _headers.Allow.ElementAt(1)); Assert.Equal("custom3", _headers.Allow.ElementAt(2)); _headers.Allow.Clear(); Assert.Equal(0, _headers.Allow.Count); Assert.False(_headers.Contains("Allow")); } [Fact] public void Allow_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Allow", "custom1 custom2"); // no separator Assert.Equal(0, _headers.Allow.Count); Assert.Equal(1, _headers.GetValues("Allow").Count()); Assert.Equal("custom1 custom2", _headers.GetValues("Allow").First()); } [Fact] public void Expires_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(_headers.Expires); DateTimeOffset expected = DateTimeOffset.Now; _headers.Expires = expected; Assert.Equal(expected, _headers.Expires); _headers.Expires = null; Assert.Null(_headers.Expires); Assert.False(_headers.Contains("Expires")); } [Fact] public void Expires_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Expires", " Sun, 06 Nov 1994 08:49:37 GMT "); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.Expires); _headers.Clear(); _headers.TryAddWithoutValidation("Expires", "Sun, 06 Nov 1994 08:49:37 GMT"); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.Expires); } [Fact] public void Expires_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Expires", " Sun, 06 Nov 1994 08:49:37 GMT ,"); Assert.Null(_headers.GetParsedValues(KnownHeaders.Expires.Descriptor)); Assert.Equal(1, _headers.GetValues("Expires").Count()); Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", _headers.GetValues("Expires").First()); _headers.Clear(); _headers.TryAddWithoutValidation("Expires", " Sun, 06 Nov "); Assert.Null(_headers.GetParsedValues(KnownHeaders.Expires.Descriptor)); Assert.Equal(1, _headers.GetValues("Expires").Count()); Assert.Equal(" Sun, 06 Nov ", _headers.GetValues("Expires").First()); } [Fact] public void LastModified_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(_headers.LastModified); DateTimeOffset expected = DateTimeOffset.Now; _headers.LastModified = expected; Assert.Equal(expected, _headers.LastModified); _headers.LastModified = null; Assert.Null(_headers.LastModified); Assert.False(_headers.Contains("Last-Modified")); } [Fact] public void LastModified_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Last-Modified", " Sun, 06 Nov 1994 08:49:37 GMT "); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.LastModified); _headers.Clear(); _headers.TryAddWithoutValidation("Last-Modified", "Sun, 06 Nov 1994 08:49:37 GMT"); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.LastModified); } [Fact] public void LastModified_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Last-Modified", " Sun, 06 Nov 1994 08:49:37 GMT ,"); Assert.Null(_headers.GetParsedValues(KnownHeaders.LastModified.Descriptor)); Assert.Equal(1, _headers.GetValues("Last-Modified").Count()); Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", _headers.GetValues("Last-Modified").First()); _headers.Clear(); _headers.TryAddWithoutValidation("Last-Modified", " Sun, 06 Nov "); Assert.Null(_headers.GetParsedValues(KnownHeaders.LastModified.Descriptor)); Assert.Equal(1, _headers.GetValues("Last-Modified").Count()); Assert.Equal(" Sun, 06 Nov ", _headers.GetValues("Last-Modified").First()); } [Fact] public void InvalidHeaders_AddRequestAndResponseHeaders_Throw() { // Try adding request, response, and general _headers. Use different casing to make sure case-insensitive // comparison is used. Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Ranges", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("age", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("ETag", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Location", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Proxy-Authenticate", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Retry-After", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Server", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Vary", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("WWW-Authenticate", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Charset", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Encoding", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Language", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Authorization", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Expect", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("From", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Host", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Match", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Modified-Since", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-None-Match", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Range", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Unmodified-Since", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Max-Forwards", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Proxy-Authorization", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Range", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Referer", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("TE", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("User-Agent", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Cache-Control", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Connection", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Date", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Pragma", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Trailer", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Transfer-Encoding", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Upgrade", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Via", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Warning", "v"); }); } private sealed class ComputeLengthHttpContent : HttpContent { private readonly Func<long?> _tryComputeLength; internal ComputeLengthHttpContent(Func<long?> tryComputeLength) { _tryComputeLength = tryComputeLength; } protected internal override bool TryComputeLength(out long length) { long? result = _tryComputeLength(); length = result.GetValueOrDefault(); return result.HasValue; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { throw new NotImplementedException(); } } } }
using System; using System.Linq; using BizHawk.Common; using BizHawk.Emulation.Common; using BizHawk.Emulation.Cores.Components.M6502; #pragma warning disable 162 namespace BizHawk.Emulation.Cores.Nintendo.NES { public partial class NES : IEmulator { //hardware/state public MOS6502X cpu; int cpu_accumulate; //cpu timekeeper public PPU ppu; public APU apu; public byte[] ram; NESWatch[] sysbus_watch = new NESWatch[65536]; public byte[] CIRAM; //AKA nametables string game_name = string.Empty; //friendly name exposed to user and used as filename base CartInfo cart; //the current cart prototype. should be moved into the board, perhaps internal INESBoard Board; //the board hardware that is currently driving things EDetectionOrigin origin = EDetectionOrigin.None; int sprdma_countdown; bool _irq_apu; //various irq signals that get merged to the cpu irq pin /// <summary>clock speed of the main cpu in hz</summary> public int cpuclockrate { get; private set; } //irq state management public bool irq_apu { get { return _irq_apu; } set { _irq_apu = value; } } //user configuration int[] palette_compiled = new int[64 * 8]; //variable set when VS system games are running internal bool _isVS = false; //some VS games have a ppu that switches 2000 and 2001, so keep trcak of that public byte _isVS2c05 = 0; //since prg reg for VS System is set in the controller regs, it is convenient to have it here //instead of in the board public byte VS_chr_reg; public byte VS_prg_reg; //various VS controls public byte[] VS_dips = new byte[8]; public byte VS_service = 0; public byte VS_coin_inserted=0; public byte VS_ROM_control; // new input system NESControlSettings ControllerSettings; // this is stored internally so that a new change of settings won't replace IControllerDeck ControllerDeck; byte latched4016; private DisplayType _display_type = DisplayType.NTSC; //Sound config public void SetSquare1(int v) { apu.Square1V = v; } public void SetSquare2(int v) { apu.Square2V = v; } public void SetTriangle(int v) { apu.TriangleV = v; } public void SetNoise(int v) { apu.NoiseV = v; } public void SetDMC(int v) { apu.DMCV = v; } /// <summary> /// for debugging only! /// </summary> /// <returns></returns> public INESBoard GetBoard() { return Board; } public void Dispose() { if (magicSoundProvider != null) magicSoundProvider.Dispose(); magicSoundProvider = null; } class MagicSoundProvider : ISoundProvider, ISyncSoundProvider, IDisposable { BlipBuffer blip; NES nes; const int blipbuffsize = 4096; public MagicSoundProvider(NES nes, uint infreq) { this.nes = nes; blip = new BlipBuffer(blipbuffsize); blip.SetRates(infreq, 44100); //var actualMetaspu = new Sound.MetaspuSoundProvider(Sound.ESynchMethod.ESynchMethod_V); //1.789773mhz NTSC //resampler = new Sound.Utilities.SpeexResampler(2, infreq, 44100 * APU.DECIMATIONFACTOR, infreq, 44100, actualMetaspu.buffer.enqueue_samples); //output = new Sound.Utilities.DCFilter(actualMetaspu); } public void GetSamples(short[] samples) { //Console.WriteLine("Sync: {0}", nes.apu.dlist.Count); int nsamp = samples.Length / 2; if (nsamp > blipbuffsize) // oh well. nsamp = blipbuffsize; uint targetclock = (uint)blip.ClocksNeeded(nsamp); uint actualclock = nes.apu.sampleclock; foreach (var d in nes.apu.dlist) blip.AddDelta(d.time * targetclock / actualclock, d.value); nes.apu.dlist.Clear(); blip.EndFrame(targetclock); nes.apu.sampleclock = 0; blip.ReadSamples(samples, nsamp, true); // duplicate to stereo for (int i = 0; i < nsamp * 2; i += 2) samples[i + 1] = samples[i]; //mix in the cart's extra sound circuit nes.Board.ApplyCustomAudio(samples); } public void GetSamples(out short[] samples, out int nsamp) { //Console.WriteLine("ASync: {0}", nes.apu.dlist.Count); foreach (var d in nes.apu.dlist) blip.AddDelta(d.time, d.value); nes.apu.dlist.Clear(); blip.EndFrame(nes.apu.sampleclock); nes.apu.sampleclock = 0; nsamp = blip.SamplesAvailable(); samples = new short[nsamp * 2]; blip.ReadSamples(samples, nsamp, true); // duplicate to stereo for (int i = 0; i < nsamp * 2; i += 2) samples[i + 1] = samples[i]; nes.Board.ApplyCustomAudio(samples); } public void DiscardSamples() { nes.apu.dlist.Clear(); nes.apu.sampleclock = 0; } public int MaxVolume { get; set; } public void Dispose() { if (blip != null) { blip.Dispose(); blip = null; } } } MagicSoundProvider magicSoundProvider; public void HardReset() { cpu = new MOS6502X(); cpu.SetCallbacks(ReadMemory, ReadMemory, PeekMemory, WriteMemory); cpu.BCD_Enabled = false; cpu.OnExecFetch = ExecFetch; ppu = new PPU(this); ram = new byte[0x800]; CIRAM = new byte[0x800]; // wire controllers // todo: allow changing this ControllerDeck = ControllerSettings.Instantiate(ppu.LightGunCallback); // set controller definition first time only if (ControllerDefinition == null) { ControllerDefinition = new ControllerDefinition(ControllerDeck.GetDefinition()); ControllerDefinition.Name = "NES Controller"; // controls other than the deck ControllerDefinition.BoolButtons.Add("Power"); ControllerDefinition.BoolButtons.Add("Reset"); if (Board is FDS) { var b = Board as FDS; ControllerDefinition.BoolButtons.Add("FDS Eject"); for (int i = 0; i < b.NumSides; i++) ControllerDefinition.BoolButtons.Add("FDS Insert " + i); } if (_isVS) { ControllerDefinition.BoolButtons.Add("Insert Coin P1"); ControllerDefinition.BoolButtons.Add("Insert Coin P2"); ControllerDefinition.BoolButtons.Add("Service Switch"); } } // don't replace the magicSoundProvider on reset, as it's not needed // if (magicSoundProvider != null) magicSoundProvider.Dispose(); // set up region switch (_display_type) { case Common.DisplayType.PAL: apu = new APU(this, apu, true); ppu.region = PPU.Region.PAL; CoreComm.VsyncNum = 50; CoreComm.VsyncDen = 1; cpuclockrate = 1662607; cpu_sequence = cpu_sequence_PAL; _display_type = DisplayType.PAL; break; case Common.DisplayType.NTSC: apu = new APU(this, apu, false); ppu.region = PPU.Region.NTSC; CoreComm.VsyncNum = 39375000; CoreComm.VsyncDen = 655171; cpuclockrate = 1789773; cpu_sequence = cpu_sequence_NTSC; break; // this is in bootgod, but not used at all case Common.DisplayType.DENDY: apu = new APU(this, apu, false); ppu.region = PPU.Region.Dendy; CoreComm.VsyncNum = 50; CoreComm.VsyncDen = 1; cpuclockrate = 1773448; cpu_sequence = cpu_sequence_NTSC; _display_type = DisplayType.DENDY; break; default: throw new Exception("Unknown displaytype!"); } if (magicSoundProvider == null) magicSoundProvider = new MagicSoundProvider(this, (uint)cpuclockrate); BoardSystemHardReset(); // apu has some specific power up bahaviour that we will emulate here apu.NESHardReset(); if (SyncSettings.InitialWRamStatePattern != null && SyncSettings.InitialWRamStatePattern.Any()) { for (int i = 0; i < 0x800; i++) { ram[i] = SyncSettings.InitialWRamStatePattern[i % SyncSettings.InitialWRamStatePattern.Count]; } } else { // check fceux's PowerNES and FCEU_MemoryRand function for more information: // relevant games: Cybernoid; Minna no Taabou no Nakayoshi Daisakusen; Huang Di; and maybe mechanized attack for (int i = 0; i < 0x800; i++) { if ((i & 4) != 0) { ram[i] = 0xFF; } else { ram[i] = 0x00; } } } SetupMemoryDomains(); //in this emulator, reset takes place instantaneously cpu.PC = (ushort)(ReadMemory(0xFFFC) | (ReadMemory(0xFFFD) << 8)); cpu.P = 0x34; cpu.S = 0xFD; // some boards cannot have specific values in RAM upon initialization // Let's hard code those cases here // these will be defined through the gameDB exclusively for now. if (cart.DB_GameInfo!=null) { if (cart.DB_GameInfo.Hash == "60FC5FA5B5ACCAF3AEFEBA73FC8BFFD3C4DAE558" // Camerica Golden 5 || cart.DB_GameInfo.Hash == "BAD382331C30B22A908DA4BFF2759C25113CC26A" // Camerica Golden 5 || cart.DB_GameInfo.Hash == "40409FEC8249EFDB772E6FFB2DCD41860C6CCA23" // Camerica Pegasus 4-in-1 ) { ram[0x701] = 0xFF; } } } bool resetSignal; bool hardResetSignal; public void FrameAdvance(bool render, bool rendersound) { if (Tracer.Enabled) cpu.TraceCallback = (s) => Tracer.Put(s); else cpu.TraceCallback = null; lagged = true; if (resetSignal) { Board.NESSoftReset(); cpu.NESSoftReset(); apu.NESSoftReset(); ppu.NESSoftReset(); } else if (hardResetSignal) { HardReset(); } Frame++; //if (resetSignal) //Controller.UnpressButton("Reset"); TODO fix this resetSignal = Controller["Reset"]; hardResetSignal = Controller["Power"]; if (Board is FDS) { var b = Board as FDS; if (Controller["FDS Eject"]) b.Eject(); for (int i = 0; i < b.NumSides; i++) if (Controller["FDS Insert " + i]) b.InsertSide(i); } if (_isVS) { if (controller["Service Switch"]) VS_service = 1; else VS_service = 0; if (controller["Insert Coin P1"]) VS_coin_inserted |= 1; else VS_coin_inserted &= 2; if (controller["Insert Coin P2"]) VS_coin_inserted |= 2; else VS_coin_inserted &= 1; } ppu.FrameAdvance(); if (lagged) { _lagcount++; islag = true; } else islag = false; videoProvider.FillFrameBuffer(); } //PAL: //0 15 30 45 60 -> 12 27 42 57 -> 9 24 39 54 -> 6 21 36 51 -> 3 18 33 48 -> 0 //sequence of ppu clocks per cpu clock: 3,3,3,3,4 //at least it should be, but something is off with that (start up time?) so it is 3,3,3,4,3 for now //NTSC: //sequence of ppu clocks per cpu clock: 3 ByteBuffer cpu_sequence; static ByteBuffer cpu_sequence_NTSC = new ByteBuffer(new byte[] { 3, 3, 3, 3, 3 }); static ByteBuffer cpu_sequence_PAL = new ByteBuffer(new byte[] { 3, 3, 3, 4, 3 }); public int cpu_step, cpu_stepcounter, cpu_deadcounter; public int oam_dma_index; public bool oam_dma_exec = false; public ushort oam_dma_addr; public byte oam_dma_byte; public bool dmc_dma_exec = false; public bool dmc_realign; public bool IRQ_delay; public bool special_case_delay; // very ugly but the only option public bool do_the_reread; #if VS2012 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif internal void RunCpuOne() { cpu_stepcounter++; if (cpu_stepcounter == cpu_sequence[cpu_step]) { cpu_step++; if (cpu_step == 5) cpu_step = 0; cpu_stepcounter = 0; /////////////////////////// // OAM DMA start /////////////////////////// if (sprdma_countdown > 0) { sprdma_countdown--; if (sprdma_countdown == 0) { if (cpu.TotalExecutedCycles % 2 == 0) { cpu_deadcounter = 2; } else { cpu_deadcounter = 1; } oam_dma_exec = true; cpu.RDY = false; oam_dma_index = 0; special_case_delay = true; } } if (oam_dma_exec && apu.dmc_dma_countdown != 1 && !dmc_realign) { if (cpu_deadcounter == 0) { if (oam_dma_index % 2 == 0) { oam_dma_byte = ReadMemory(oam_dma_addr); oam_dma_addr++; } else { WriteMemory(0x2004, oam_dma_byte); } oam_dma_index++; if (oam_dma_index == 512) oam_dma_exec = false; } else { cpu_deadcounter--; } } else if (apu.dmc_dma_countdown == 1) { dmc_realign = true; } else if (dmc_realign) { dmc_realign = false; } ///////////////////////////// // OAM DMA end ///////////////////////////// ///////////////////////////// // dmc dma start ///////////////////////////// if (apu.dmc_dma_countdown > 0) { cpu.RDY = false; dmc_dma_exec = true; apu.dmc_dma_countdown--; if (apu.dmc_dma_countdown == 0) { apu.RunDMCFetch(); dmc_dma_exec = false; apu.dmc_dma_countdown = -1; do_the_reread = true; } } ///////////////////////////// // dmc dma end ///////////////////////////// apu.RunOne(true); if (cpu.RDY && !IRQ_delay) { cpu.IRQ = _irq_apu || Board.IRQSignal; } else if (special_case_delay || apu.dmc_dma_countdown == 3) { cpu.IRQ = _irq_apu || Board.IRQSignal; special_case_delay = false; } cpu.ExecuteOne(); apu.RunOne(false); if (ppu.double_2007_read > 0) ppu.double_2007_read--; if (do_the_reread && cpu.RDY) do_the_reread = false; if (IRQ_delay) IRQ_delay = false; if (!dmc_dma_exec && !oam_dma_exec && !cpu.RDY) { cpu.RDY = true; IRQ_delay = true; } ppu.ppu_open_bus_decay(0); Board.ClockCPU(); ppu.PostCpuInstructionOne(); } } #if VS2012 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public byte ReadReg(int addr) { byte ret_spec; switch (addr) { case 0x4000: case 0x4001: case 0x4002: case 0x4003: case 0x4004: case 0x4005: case 0x4006: case 0x4007: case 0x4008: case 0x4009: case 0x400A: case 0x400B: case 0x400C: case 0x400D: case 0x400E: case 0x400F: case 0x4010: case 0x4011: case 0x4012: case 0x4013: return DB; //return apu.ReadReg(addr); case 0x4014: /*OAM DMA*/ break; case 0x4015: return (byte)((byte)(apu.ReadReg(addr) & 0xDF) + (byte)(DB & 0x20)); case 0x4016: if (_isVS) { byte ret = 0; ret = read_joyport(0x4016); ret &= 1; ret = (byte)(ret | (VS_service << 2) | (VS_dips[0] << 3) | (VS_dips[1] << 4) | (VS_coin_inserted << 5) | (VS_ROM_control<<7)); return ret; } else { // special hardware glitch case ret_spec = read_joyport(addr); if (do_the_reread) { ret_spec = read_joyport(addr); do_the_reread = false; } return ret_spec; } case 0x4017: { if (_isVS) { byte ret = 0; ret = read_joyport(0x4017); ret &= 1; ret = (byte)(ret | (VS_dips[2] << 2) | (VS_dips[3] << 3) | (VS_dips[4] << 4) | (VS_dips[5] << 5) | (VS_dips[6] << 6) | (VS_dips[7] << 7)); return ret; } else { return read_joyport(addr); } } default: //Console.WriteLine("read register: {0:x4}", addr); break; } return DB; } public byte PeekReg(int addr) { switch (addr) { case 0x4000: case 0x4001: case 0x4002: case 0x4003: case 0x4004: case 0x4005: case 0x4006: case 0x4007: case 0x4008: case 0x4009: case 0x400A: case 0x400B: case 0x400C: case 0x400D: case 0x400E: case 0x400F: case 0x4010: case 0x4011: case 0x4012: case 0x4013: return apu.PeekReg(addr); case 0x4014: /*OAM DMA*/ break; case 0x4015: return apu.PeekReg(addr); case 0x4016: case 0x4017: return peek_joyport(addr); default: //Console.WriteLine("read register: {0:x4}", addr); break; } return 0xFF; } void WriteReg(int addr, byte val) { switch (addr) { case 0x4000: case 0x4001: case 0x4002: case 0x4003: case 0x4004: case 0x4005: case 0x4006: case 0x4007: case 0x4008: case 0x4009: case 0x400A: case 0x400B: case 0x400C: case 0x400D: case 0x400E: case 0x400F: case 0x4010: case 0x4011: case 0x4012: case 0x4013: apu.WriteReg(addr, val); break; case 0x4014: Exec_OAMDma(val); break; case 0x4015: apu.WriteReg(addr, val); break; case 0x4016: if (_isVS) { write_joyport(val); VS_chr_reg = (byte)((val & 0x4)>>2); //TODO: does other stuff for dual system //this is actually different then assignment VS_prg_reg = (byte)((val & 0x4)>>2); } else { write_joyport(val); } break; case 0x4017: apu.WriteReg(addr, val); break; default: //Console.WriteLine("wrote register: {0:x4} = {1:x2}", addr, val); break; } } void write_joyport(byte value) { var si = new StrobeInfo(latched4016, value); ControllerDeck.Strobe(si, Controller); latched4016 = value; } byte read_joyport(int addr) { InputCallbacks.Call(); lagged = false; byte ret = 0; if (_isVS) { // for whatever reason, in VS left and right controller have swapped regs ret = addr == 0x4017 ? ControllerDeck.ReadA(Controller) : ControllerDeck.ReadB(Controller); } else { ret = addr == 0x4016 ? ControllerDeck.ReadA(Controller) : ControllerDeck.ReadB(Controller); } ret &= 0x1f; ret |= (byte)(0xe0 & DB); return ret; } byte peek_joyport(int addr) { // at the moment, the new system doesn't support peeks return 0; } void Exec_OAMDma(byte val) { //schedule a sprite dma event for beginning 1 cycle in the future. //this receives 2 because thats just the way it works out. oam_dma_addr = (ushort)(val << 8); sprdma_countdown = 1; } /// <summary> /// Sets the provided palette as current. /// Applies the current deemph settings if needed to expand a 64-entry palette to 512 /// </summary> public void SetPalette(byte[,] pal) { int nColors = pal.GetLength(0); int nElems = pal.GetLength(1); if (nColors == 512) { //just copy the palette directly for (int c = 0; c < 64 * 8; c++) { int r = pal[c, 0]; int g = pal[c, 1]; int b = pal[c, 2]; palette_compiled[c] = (int)unchecked((int)0xFF000000 | (r << 16) | (g << 8) | b); } } else { //expand using deemph for (int i = 0; i < 64 * 8; i++) { int d = i >> 6; int c = i & 63; int r = pal[c, 0]; int g = pal[c, 1]; int b = pal[c, 2]; Palettes.ApplyDeemphasis(ref r, ref g, ref b, d); palette_compiled[i] = (int)unchecked((int)0xFF000000 | (r << 16) | (g << 8) | b); } } } /// <summary> /// looks up an internal NES pixel value to an rgb int (applying the core's current palette and assuming no deemph) /// </summary> public int LookupColor(int pixel) { return palette_compiled[pixel]; } public byte DummyReadMemory(ushort addr) { return 0; } private void ApplySystemBusPoke(int addr, byte value) { if (addr < 0x2000) { ram[(addr & 0x7FF)] = value; } else if (addr < 0x4000) { ppu.WriteReg((addr & 0x07), value); } else if (addr < 0x4020) { WriteReg(addr, value); } else { ApplyGameGenie(addr, value, null); //Apply a cheat to the remaining regions since they have no direct access, this may not be the best way to handle this situation } } public byte PeekMemory(ushort addr) { byte ret; if (addr >= 0x4020) { ret = Board.PeekCart(addr); //easy optimization, since rom reads are so common, move this up (reordering the rest of these elseifs is not easy) } else if (addr < 0x0800) { ret = ram[addr]; } else if (addr < 0x2000) { ret = ram[addr & 0x7FF]; } else if (addr < 0x4000) { ret = Board.PeekReg2xxx(addr); } else if (addr < 0x4020) { ret = PeekReg(addr); //we're not rebasing the register just to keep register names canonical } else { throw new Exception("Woopsie-doodle!"); ret = 0xFF; } return ret; } //old data bus values from previous reads public byte DB; public void ExecFetch(ushort addr) { MemoryCallbacks.CallExecutes(addr); } public byte ReadMemory(ushort addr) { byte ret; if (addr >= 0x8000) { ret = Board.ReadPRG(addr - 0x8000); //easy optimization, since rom reads are so common, move this up (reordering the rest of these elseifs is not easy) } else if (addr < 0x0800) { ret = ram[addr]; } else if (addr < 0x2000) { ret = ram[addr & 0x7FF]; } else if (addr < 0x4000) { ret = Board.ReadReg2xxx(addr); } else if (addr < 0x4020) { ret = ReadReg(addr); //we're not rebasing the register just to keep register names canonical } else if (addr < 0x6000) { ret = Board.ReadEXP(addr - 0x4000); } else { ret = Board.ReadWRAM(addr - 0x6000); } //handle breakpoints and stuff. //the idea is that each core can implement its own watch class on an address which will track all the different kinds of monitors and breakpoints and etc. //but since freeze is a common case, it was implemented through its own mechanisms if (sysbus_watch[addr] != null) { sysbus_watch[addr].Sync(); ret = sysbus_watch[addr].ApplyGameGenie(ret); } MemoryCallbacks.CallReads(addr); DB = ret; return ret; } public void ApplyGameGenie(int addr, byte value, byte? compare) { if (addr < sysbus_watch.Length) { GetWatch(NESWatch.EDomain.Sysbus, addr).SetGameGenie(compare, value); } } public void RemoveGameGenie(int addr) { if (addr < sysbus_watch.Length) { GetWatch(NESWatch.EDomain.Sysbus, addr).RemoveGameGenie(); } } public void WriteMemory(ushort addr, byte value) { if (addr < 0x0800) { ram[addr] = value; } else if (addr < 0x2000) { ram[addr & 0x7FF] = value; } else if (addr < 0x4000) { Board.WriteReg2xxx(addr, value); } else if (addr < 0x4020) { WriteReg(addr, value); //we're not rebasing the register just to keep register names canonical } else if (addr < 0x6000) { Board.WriteEXP(addr - 0x4000, value); } else if (addr < 0x8000) { Board.WriteWRAM(addr - 0x6000, value); } else { Board.WritePRG(addr - 0x8000, value); } MemoryCallbacks.CallWrites(addr); } // the palette for each VS game needs to be chosen explicitly since there are 6 different ones. public void PickVSPalette(CartInfo cart) { switch (cart.palette) { case "2C05": SetPalette(Palettes.palette_2c03_2c05); ppu.CurrentLuma = PPU.PaletteLuma2C03; break; case "2C04-1": SetPalette(Palettes.palette_2c04_001); ppu.CurrentLuma = PPU.PaletteLuma2C04_1; break; case "2C04-2": SetPalette(Palettes.palette_2c04_002); ppu.CurrentLuma = PPU.PaletteLuma2C04_2; break; case "2C04-3": SetPalette(Palettes.palette_2c04_003); ppu.CurrentLuma = PPU.PaletteLuma2C04_3; break; case "2C04-4": SetPalette(Palettes.palette_2c04_004); ppu.CurrentLuma = PPU.PaletteLuma2C04_4; break; } //since this will run for every VS game, let's get security setting too //values below 16 are for the 2c05 PPU //values 16,32,48 are for Namco games and dealt with in mapper 206 _isVS2c05 = (byte)(cart.vs_security & 15); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Text; using DeOps.Implementation; using DeOps.Services.Assist; using DeOps.Services.Location; using DeOps.Interface.TLVex; namespace DeOps.Services.Trust { public class LinkTree : TreeListViewEx { public OpCore Core; public TrustService Trust; public ProjectNode ProjectNode; public ProjectNode UnlinkedNode; Dictionary<ulong, LinkNode> NodeMap = new Dictionary<ulong, LinkNode>(); public ulong SelectedLink; public uint SelectedProject; public ulong ForceRootID; public bool HideUnlinked; public uint Project; public bool FirstLineBlank = true; public bool SearchOnline; Font TrustedFont = new Font("Tahoma", 8.25F, FontStyle.Bold | FontStyle.Underline); Font UntrustedFont = new Font("Tahoma", 8.25F, FontStyle.Bold); public Font SelectedFont = new System.Drawing.Font("Tahoma", 8.25F, FontStyle.Bold); public Font OnlineFont = new Font("Tahoma", 8.25F); public Font OfflineFont = new Font("Tahoma", 8.25F, System.Drawing.FontStyle.Italic); public LinkTree() { HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; } public void Init(TrustService trust) { Trust = trust; Core = trust.Core; Core.Locations.GuiUpdate += new LocationGuiUpdateHandler(Locations_Update); Trust.GuiUpdate += new LinkGuiUpdateHandler(Trust_Update); Core.KeepDataGui += new KeepDataHandler(Core_KeepData); SelectedLink = Core.UserID; SelectedItemChanged += new EventHandler(LinkTree_SelectedItemChanged); NodeExpanding += new EventHandler(LinkTree_NodeExpanding); NodeCollapsed += new EventHandler(LinkTree_NodeCollapsed); } protected override void Dispose(bool disposing) { if (disposing) { SelectedItemChanged -= new EventHandler(LinkTree_SelectedItemChanged); NodeExpanding -= new EventHandler(LinkTree_NodeExpanding); NodeCollapsed -= new EventHandler(LinkTree_NodeCollapsed); Core.Locations.GuiUpdate -= new LocationGuiUpdateHandler(Locations_Update); Trust.GuiUpdate -= new LinkGuiUpdateHandler(Trust_Update); Core.KeepDataGui -= new KeepDataHandler(Core_KeepData); } base.Dispose(disposing); } private void RefreshOperationTree() { BeginUpdate(); // save selected LinkNode selected = GetSelected(); // save visible while unloading List<ulong> visible = new List<ulong>(); foreach (TreeListNode node in Nodes) if (node.GetType() == typeof(LinkNode)) UnloadNode((LinkNode)node, visible); NodeMap.Clear(); Nodes.Clear(); // white space if(FirstLineBlank) Nodes.Add(new LabelNode("")); if (!Trust.ProjectRoots.SafeContainsKey(Project)) { EndUpdate(); return; } string rootname = Core.User.Settings.Operation; if (Project != 0) rootname = Trust.GetProjectName(Project); // operation ProjectNode = new ProjectNode(rootname, Project); ProjectNode.Font = TrustedFont; Nodes.Add(ProjectNode); // white space Nodes.Add(new LabelNode("")); // unlinked UnlinkedNode = new ProjectNode("Untrusted", 0); UnlinkedNode.Font = UntrustedFont; Nodes.Add(UnlinkedNode); // if forced, load specific node as root if (ForceRootID != 0) { OpLink root = Trust.GetLink(ForceRootID, Project); if (root != null) SetupRoot(root); } // get roots for specific project else { ThreadedList<OpLink> roots = null; if (Trust.ProjectRoots.SafeTryGetValue(Project, out roots)) roots.LockReading(delegate() { foreach (OpLink root in roots) SetupRoot(root); }); } // show unlinked if there's something to show if (Nodes.IndexOf(UnlinkedNode) + 1 == Nodes.Count) UnlinkedNode.Text = ""; else UnlinkedNode.Text = "Untrusted"; // restore visible foreach (ulong id in visible) foreach (TreeListNode node in Nodes) if (node.GetType() == typeof(LinkNode)) { List<ulong> uplinks = Trust.GetUnconfirmedUplinkIDs(id, Project); uplinks.Add(id); VisiblePath((LinkNode)node, uplinks); } // restore selected if (selected != null) if (NodeMap.ContainsKey(selected.Link.UserID)) Select(NodeMap[selected.Link.UserID]); EndUpdate(); } private void SetupRoot(OpLink root) { LinkNode node = CreateNode(root); LoadRoot(node); List<ulong> uplinks = Trust.GetUnconfirmedUplinkIDs(Core.UserID, Project); uplinks.Add(Core.UserID); ExpandPath(node, uplinks); node.Expand(); // expand first level of roots regardless } private void LoadRoot(LinkNode node) { // set up root with hidden subs LoadNode(node); // if self or uplinks contains root, put in project if(node.Link.UserID == Core.UserID || Trust.IsUnconfirmedHigher(node.Link.UserID, Project)) InsertRootNode(ProjectNode, node); // else put in untrusted else if (!HideUnlinked) InsertRootNode(UnlinkedNode, node); } private void LoadNode(LinkNode node) { // check if already loaded if (node.AddSubs) return; node.AddSubs = true; // go through downlinks foreach (OpLink link in node.Link.Downlinks) if (!node.Link.IsLoopedTo(link)) { if(SearchOnline) Core.Locations.Research(link.UserID); // if doesnt exist search for it if (!link.Trust.Loaded) { Trust.Research(link.UserID, Project, false); continue; } //if(node.Link.IsLoopRoot) // node.Nodes.Insert(0, CreateNode(link)); //else GuiUtils.InsertSubNode(node, CreateNode(link)); } } public void InsertRootNode(ProjectNode start, LinkNode node) { // inserts item directly under start, not as a child node int index = 0; TreeListNode root = start.Parent; node.Section = start; bool ready = false; foreach (TreeListNode entry in root.Nodes) { if (ready) if (start == ProjectNode || (start == UnlinkedNode && string.Compare(node.Text, entry.Text, true) < 0) || entry.GetType() == typeof(LabelNode)) // lower bounds { root.Nodes.Insert(index, node); return; } if (entry == start) ready = true; index++; } root.Nodes.Insert(index, node); } private void ExpandPath(LinkNode node, List<ulong> uplinks) { if (!uplinks.Contains(node.Link.UserID)) return; // expand triggers even loading nodes two levels down, one level shown, the other hidden node.Expand(); foreach (LinkNode sub in node.Nodes) ExpandPath(sub, uplinks); } private void VisiblePath(LinkNode node, List<ulong> uplinks) { bool found = false; foreach (LinkNode sub in node.Nodes) if (uplinks.Contains(sub.Link.UserID)) found = true; if (found) { node.Expand(); foreach (LinkNode sub in node.Nodes) VisiblePath(sub, uplinks); } } private LinkNode CreateNode(OpLink link) { LinkNode node = new LinkNode(link, this); NodeMap[link.UserID] = node; return node; } void Core_KeepData() { foreach (TreeListNode item in Nodes) RecurseFocus(item); } void RecurseFocus(TreeListNode parent) { // add parent to focus list if (parent.GetType() == typeof(LinkNode)) Core.KeepData.SafeAdd(((LinkNode)parent).Link.UserID, true); // iterate through sub items foreach (TreeListNode subitem in parent.Nodes) if (parent.GetType() == typeof(LinkNode)) RecurseFocus(subitem); } void Locations_Update(ulong key) { if (NodeMap.ContainsKey(key)) { NodeMap[key].UpdateStatus(); Invalidate(); } } void Trust_Update(ulong key) { // update OpLink link = Trust.GetLink(key, Project); if (link == null) { if (NodeMap.ContainsKey(key)) RemoveNode(NodeMap[key]); return; } ProjectNode.Text = Trust.GetProjectName(Project); /* taken care of above * if (!link.Projects.Contains(Project) && !link.Downlinks.ContainsKey(Project)) { if (NodeMap.ContainsKey(key)) RemoveNode(NodeMap[key]); return; }*/ if (ForceRootID != 0) { // root must be a parent of the updating node if (link.UserID != ForceRootID && !Trust.IsUnconfirmedHigher(link.UserID, ForceRootID, Project)) return; } LinkNode node = null; if (NodeMap.ContainsKey(key)) { node = NodeMap[key]; node.Link = link; // links reset and re-loaded from file } TreeListNode parent = null; OpLink uplink = GetTreeHigher(link); if (uplink == null) parent = virtualParent; else if (NodeMap.ContainsKey(uplink.UserID)) parent = NodeMap[uplink.UserID]; else if (uplink.IsLoopRoot) parent = new TreeListNode(); // ensures that tree is refreshed // if nodes status unchanged if (node != null && parent != null && node.Parent == parent) { node.UpdateStatus(); Invalidate(); return; } // only if parent is visible if(parent != null) RefreshOperationTree(); } private void UpdateOperation(LinkNode node) { OpLink link = node.Link; TreeListNode parent = null; OpLink uplink = GetTreeHigher(link); if (uplink == null) parent = virtualParent; else if (NodeMap.ContainsKey(uplink.UserID)) parent = NodeMap[uplink.UserID]; else if (uplink.IsLoopRoot) { parent = CreateNode(uplink); LoadRoot((LinkNode)parent); } // else branch this link is apart of is not visible in current display // self is changing ensure it's visible if (node.Link.UserID == Core.UserID) { if (parent == null) { List<ulong> uplinks = Trust.GetUnconfirmedUplinkIDs(Core.UserID, Project); uplinks.Add(Core.UserID); ExpandPath(node, uplinks); // check nodeMap again now that highers added if (NodeMap.ContainsKey(uplink.UserID)) parent = NodeMap[uplink.UserID]; } if (parent != null) parent.Expand(); } // remember settings bool selected = node.Selected; bool expanded = node.IsExpanded; bool loadsubs = node.AddSubs; // update parent node if (node.Parent != parent) { List<ulong> visible = new List<ulong>(); // remove previous instance of node if (node.Parent != null) { if (node.IsVisible()) visible.Add(link.UserID); LinkNode oldParent = node.Parent as LinkNode; LinkNode unload = (oldParent != null && oldParent.Link.IsLoopRoot) ? oldParent : node; // if old parent is a loop node, the loop is made obsolete by change UnloadNode(unload, visible); unload.Remove(); } if (parent == null) return; // if new parent is hidden, dont bother adding till user expands LinkNode newParent = parent as LinkNode; // null if virtual parent (root) if (newParent != null && newParent.AddSubs == false) return; // copy node to start fresh LinkNode newNode = CreateNode(node.Link); if (newParent != null) GuiUtils.InsertSubNode(newParent, newNode); else LoadRoot(newNode); ArrangeRoots(); // arrange nodes can cause newNode to become invalid, retrieve updated copy if(!NodeMap.ContainsKey(link.UserID)) return; newNode = NodeMap[link.UserID]; if (loadsubs) // if previous node set to add kids { LoadNode(newNode); if (expanded) // if previous node set expanded newNode.Expand(); } node = newNode; // recurse to each previously visible node List<LinkNode> roots = new List<LinkNode>(); foreach (TreeListNode treeNode in Nodes) if (treeNode.GetType() == typeof(LinkNode)) if (((LinkNode)treeNode).Section == ProjectNode) roots.Add(treeNode as LinkNode); foreach (ulong id in visible) { List<ulong> uplinks = Trust.GetUnconfirmedUplinkIDs(id, Project); foreach (LinkNode root in roots) VisiblePath(root, uplinks); } // show unlinked if there's something to show if (Nodes.IndexOf(UnlinkedNode) + 1 == Nodes.Count) UnlinkedNode.Text = ""; else UnlinkedNode.Text = "Untrusted"; } node.UpdateStatus(); if (selected) node.Selected = true; Invalidate(); } private OpLink GetTreeHigher(OpLink link) { if (link.LoopRoot != null) return link.LoopRoot; return link.GetHigher(false); } private void ArrangeRoots() { List<ulong> uplinks = Trust.GetUnconfirmedUplinkIDs(Core.UserID, Project); uplinks.Add(Core.UserID); OpLink highest = Trust.GetLink(uplinks[uplinks.Count - 1], Project); if (highest.LoopRoot != null) uplinks.Add(highest.LoopRoot.UserID); List<LinkNode> makeUntrusted = new List<LinkNode>(); List<LinkNode> makeProject = new List<LinkNode>(); // look for nodes to switch foreach (TreeListNode entry in Nodes) { LinkNode node = entry as LinkNode; if (node == null) continue; if(entry == ProjectNode && !uplinks.Contains(node.Link.UserID)) makeUntrusted.Add(node); else if(entry == UnlinkedNode && uplinks.Contains(node.Link.UserID)) makeProject.Add(node); } // remove, recreate, insert, expand root, expand to self foreach (LinkNode delNode in makeUntrusted) { RemoveNode(delNode); if (HideUnlinked) continue; LinkNode node = CreateNode(delNode.Link); LoadNode(node); InsertRootNode(UnlinkedNode, node); node.Expand(); } Debug.Assert(makeProject.Count <= 1); foreach (LinkNode delNode in makeProject) { RemoveNode(delNode); LinkNode node = CreateNode(delNode.Link); LoadNode(node); InsertRootNode(ProjectNode, node); node.Expand(); ExpandPath(node, uplinks); } } private void RemoveNode(LinkNode node) { UnloadNode(node, null); // unload subs NodeMap.Remove(node.Link.UserID); // remove from map node.Remove(); // remove from tree } void LinkTree_NodeExpanding(object sender, EventArgs e) { LinkNode node = sender as LinkNode; if (node == null) return; Debug.Assert(node.AddSubs); // node now expanded, get next level below children foreach (LinkNode child in node.Nodes) LoadNode(child); } void LinkTree_NodeCollapsed(object sender, EventArgs e) { LinkNode node = sender as LinkNode; if (node == null) return; if (!node.AddSubs) // this node is already collapsed return; // remove nodes 2 levels down foreach (LinkNode child in node.Nodes) UnloadNode(child, null); Debug.Assert(node.AddSubs); // this is the top level, children hidden underneath } private void UnloadNode(LinkNode node, List<ulong> visible) { node.AddSubs = false; if (visible != null && node.IsVisible()) visible.Add(node.Link.UserID); if (NodeMap.ContainsKey(node.Link.UserID)) NodeMap.Remove(node.Link.UserID); // for each child, call unload node, then clear foreach (LinkNode child in node.Nodes) UnloadNode(child, visible); // unloads children of node, not the node itself node.Nodes.Clear(); node.Collapse(); } public void SelectLink(ulong id, uint project) { if (!Trust.TrustMap.SafeContainsKey(id)) id = Core.UserID; ulong oldLink = SelectedLink; SelectedLink = id; SelectedProject = project; // unbold current if (NodeMap.ContainsKey(oldLink)) NodeMap[oldLink].UpdateStatus(); // bold new and set if (NodeMap.ContainsKey(SelectedLink) && Project == SelectedProject) { NodeMap[SelectedLink].UpdateStatus(); NodeMap[SelectedLink].EnsureVisible(); } Invalidate(); } public void ShowProject(uint project) { LinkNode item = GetSelected(); Project = project; RefreshOperationTree(); if (item != null && NodeMap.ContainsKey(item.Link.UserID)) NodeMap[item.Link.UserID].Selected = true; } LinkNode GetSelected() { if (SelectedNodes.Count == 0) return null; TreeListNode node = SelectedNodes[0]; if (node.GetType() != typeof(LinkNode)) return null; return (LinkNode)node; } void LinkTree_SelectedItemChanged(object sender, EventArgs e) { foreach (TreeListNode node in SelectedNodes) { if (node.Text == "") node.Selected = false; if (node.GetType() == typeof(LinkNode)) { LinkNode item = node as LinkNode; Trust.Research(item.Link.UserID, Project, true); if(SearchOnline) Core.Locations.Research(item.Link.UserID); } } } public List<ulong> GetSelectedIDs() { List<ulong> selected = new List<ulong>(); foreach (TreeListNode node in SelectedNodes) if (node.GetType() == typeof(LinkNode)) if( !((LinkNode)node).Link.IsLoopRoot ) selected.Add(((LinkNode)node).Link.UserID); return selected; } } public class LabelNode : TreeListNode { public LabelNode(string text) { Text = text; } } public class ProjectNode : TreeListNode { public uint ID; public ProjectNode(string text, uint id) { Text = text; ID = id; } } public class LinkNode : TreeListNode { public OpLink Link; LinkTree ParentView; public TrustService Trust; public LocationService Locations; public bool AddSubs; public ProjectNode Section; static Color DarkDarkGray = Color.FromArgb(96, 96, 96); public LinkNode(OpLink link, LinkTree parent) { Link = link; ParentView = parent; Trust = parent.Trust; Locations = parent.Core.Locations; UpdateStatus(); } public void UpdateStatus() { // reset Font = ParentView.OnlineFont; ForeColor = Color.Black; string txt = ""; txt += Trust.Core.GetName(Link.UserID); if (Link.IsLoopRoot) txt = "Trust Loop"; OpLink parent = Link.GetHigher(false); if (parent != null) { bool confirmed = false; //bool requested = false; if (parent.Confirmed.Contains(Link.UserID)) confirmed = true; if (!confirmed) ForeColor = Color.Red; /*foreach (UplinkRequest request in parent.Requests) if (request.KeyID == Link.UserID) requested = true; if (confirmed) { } else if (requested && parent.UserID == Trust.Core.UserID) txt += " (Accept Trust?)"; else if (requested) txt += " (Trust Requested)"; else if (parent.UserID == Trust.Core.UserID) txt += " (Trust Denied)"; else txt += " (Trust Unconfirmed)";*/ } else if (!Link.Active) { txt += " (Left Project)"; } txt += " "; // tree bug not showing all text if (Text != txt) Text = txt; // bold selected if (ParentView.SelectedLink == Link.UserID && ParentView.Project == ParentView.SelectedProject) Font = ParentView.SelectedFont; // if not else, can override above if (Link.UserID == Trust.Core.UserID && Trust.Core.User.Settings.Invisible) { Font = ParentView.OfflineFont; ForeColor = Color.Gray; } } public void UpdateColor() { Color newColor = Color.Black; if (Link.UserID == Trust.Core.UserID || Locations.ActiveClientCount(Link.UserID) > 0) newColor = Color.Black; else newColor = Color.DarkGray; if (newColor != ForeColor) ForeColor = newColor; } public override string ToString() { return Text; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// CountryResource /// </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.Pricing.V1.Messaging { public class CountryResource : Resource { private static Request BuildReadRequest(ReadCountryOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Pricing, "/v1/Messaging/Countries", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Country parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Country </returns> public static ResourceSet<CountryResource> Read(ReadCountryOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<CountryResource>.FromJson("countries", response.Content); return new ResourceSet<CountryResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Country parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Country </returns> public static async System.Threading.Tasks.Task<ResourceSet<CountryResource>> ReadAsync(ReadCountryOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<CountryResource>.FromJson("countries", response.Content); return new ResourceSet<CountryResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <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 Country </returns> public static ResourceSet<CountryResource> Read(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadCountryOptions(){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <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 Country </returns> public static async System.Threading.Tasks.Task<ResourceSet<CountryResource>> ReadAsync(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadCountryOptions(){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<CountryResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<CountryResource>.FromJson("countries", 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<CountryResource> NextPage(Page<CountryResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Pricing) ); var response = client.Request(request); return Page<CountryResource>.FromJson("countries", 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<CountryResource> PreviousPage(Page<CountryResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Pricing) ); var response = client.Request(request); return Page<CountryResource>.FromJson("countries", response.Content); } private static Request BuildFetchRequest(FetchCountryOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Pricing, "/v1/Messaging/Countries/" + options.PathIsoCountry + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Country parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Country </returns> public static CountryResource Fetch(FetchCountryOptions 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 Country parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Country </returns> public static async System.Threading.Tasks.Task<CountryResource> FetchAsync(FetchCountryOptions 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="pathIsoCountry"> The ISO country code </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Country </returns> public static CountryResource Fetch(string pathIsoCountry, ITwilioRestClient client = null) { var options = new FetchCountryOptions(pathIsoCountry); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathIsoCountry"> The ISO country code </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Country </returns> public static async System.Threading.Tasks.Task<CountryResource> FetchAsync(string pathIsoCountry, ITwilioRestClient client = null) { var options = new FetchCountryOptions(pathIsoCountry); return await FetchAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a CountryResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> CountryResource object represented by the provided JSON </returns> public static CountryResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<CountryResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The name of the country /// </summary> [JsonProperty("country")] public string Country { get; private set; } /// <summary> /// The ISO country code /// </summary> [JsonProperty("iso_country")] public string IsoCountry { get; private set; } /// <summary> /// The list of OutboundSMSPrice records /// </summary> [JsonProperty("outbound_sms_prices")] public List<OutboundSmsPrice> OutboundSmsPrices { get; private set; } /// <summary> /// The list of InboundPrice records /// </summary> [JsonProperty("inbound_sms_prices")] public List<InboundSmsPrice> InboundSmsPrices { get; private set; } /// <summary> /// The currency in which prices are measured, in ISO 4127 format (e.g. usd, eur, jpy) /// </summary> [JsonProperty("price_unit")] public string PriceUnit { get; private set; } /// <summary> /// The absolute URL of the resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private CountryResource() { } } }
// 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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime; using System.Runtime.CompilerServices; using System.Text; using Internal.Runtime.Augments; using Internal.Reflection.Core.NonPortable; namespace System { public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible { public int CompareTo(Object target) { if (target == null) return 1; if (target == this) return 0; if (this.EETypePtr != target.EETypePtr) { throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, target.GetType().ToString(), this.GetType().ToString())); } ref byte pThisValue = ref this.GetRawData(); ref byte pTargetValue = ref target.GetRawData(); switch (this.EETypePtr.CorElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: return (Unsafe.As<byte, sbyte>(ref pThisValue) == Unsafe.As<byte, sbyte>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, sbyte>(ref pThisValue) < Unsafe.As<byte, sbyte>(ref pTargetValue)) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: return (Unsafe.As<byte, byte>(ref pThisValue) == Unsafe.As<byte, byte>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, byte>(ref pThisValue) < Unsafe.As<byte, byte>(ref pTargetValue)) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: return (Unsafe.As<byte, short>(ref pThisValue) == Unsafe.As<byte, short>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, short>(ref pThisValue) < Unsafe.As<byte, short>(ref pTargetValue)) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: return (Unsafe.As<byte, ushort>(ref pThisValue) == Unsafe.As<byte, ushort>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, ushort>(ref pThisValue) < Unsafe.As<byte, ushort>(ref pTargetValue)) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: return (Unsafe.As<byte, int>(ref pThisValue) == Unsafe.As<byte, int>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, int>(ref pThisValue) < Unsafe.As<byte, int>(ref pTargetValue)) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: return (Unsafe.As<byte, uint>(ref pThisValue) == Unsafe.As<byte, uint>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, uint>(ref pThisValue) < Unsafe.As<byte, uint>(ref pTargetValue)) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: return (Unsafe.As<byte, long>(ref pThisValue) == Unsafe.As<byte, long>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, long>(ref pThisValue) < Unsafe.As<byte, long>(ref pTargetValue)) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: return (Unsafe.As<byte, ulong>(ref pThisValue) == Unsafe.As<byte, ulong>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, ulong>(ref pThisValue) < Unsafe.As<byte, ulong>(ref pTargetValue)) ? -1 : 1; default: Environment.FailFast("Unexpected enum underlying type"); return 0; } } public override bool Equals(Object obj) { if (obj == null) return false; EETypePtr eeType = this.EETypePtr; if (!eeType.FastEquals(obj.EETypePtr)) return false; ref byte pThisValue = ref this.GetRawData(); ref byte pOtherValue = ref obj.GetRawData(); RuntimeImports.RhCorElementTypeInfo corElementTypeInfo = eeType.CorElementTypeInfo; switch (corElementTypeInfo.Log2OfSize) { case 0: return Unsafe.As<byte, byte>(ref pThisValue) == Unsafe.As<byte, byte>(ref pOtherValue); case 1: return Unsafe.As<byte, ushort>(ref pThisValue) == Unsafe.As<byte, ushort>(ref pOtherValue); case 2: return Unsafe.As<byte, uint>(ref pThisValue) == Unsafe.As<byte, uint>(ref pOtherValue); case 3: return Unsafe.As<byte, ulong>(ref pThisValue) == Unsafe.As<byte, ulong>(ref pOtherValue); default: Environment.FailFast("Unexpected enum underlying type"); return false; } } public override int GetHashCode() { ref byte pValue = ref this.GetRawData(); switch (this.EETypePtr.CorElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: return Unsafe.As<byte, bool>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: return Unsafe.As<byte, char>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: return Unsafe.As<byte, sbyte>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: return Unsafe.As<byte, byte>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: return Unsafe.As<byte, short>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: return Unsafe.As<byte, ushort>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: return Unsafe.As<byte, int>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: return Unsafe.As<byte, uint>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: return Unsafe.As<byte, long>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: return Unsafe.As<byte, ulong>(ref pValue).GetHashCode(); default: Environment.FailFast("Unexpected enum underlying type"); return 0; } } public static String Format(Type enumType, Object value, String format) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); EnumInfo enumInfo = GetEnumInfo(enumType); if (value == null) throw new ArgumentNullException(nameof(value)); if (format == null) throw new ArgumentNullException(nameof(format)); Contract.EndContractBlock(); if (value.EETypePtr.IsEnum) { EETypePtr enumTypeEEType; if ((!enumType.TryGetEEType(out enumTypeEEType)) || enumTypeEEType != value.EETypePtr) throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, value.GetType().ToString(), enumType.ToString())); } else { if (value.EETypePtr != enumInfo.UnderlyingType.TypeHandle.ToEETypePtr()) throw new ArgumentException(SR.Format(SR.Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType, value.GetType().ToString(), enumInfo.UnderlyingType.ToString())); } return Format(enumInfo, value, format); } private static String Format(EnumInfo enumInfo, Object value, String format) { ulong rawValue; if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue)) { Debug.Assert(false, "Caller was expected to do enough validation to avoid reaching this."); throw new ArgumentException(); } if (format.Length != 1) { // all acceptable format string are of length 1 throw new FormatException(SR.Format_InvalidEnumFormatSpecification); } char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { return DoFormatD(rawValue, value.EETypePtr.CorElementType); } if (formatCh == 'X' || formatCh == 'x') { return DoFormatX(rawValue, value.EETypePtr.CorElementType); } if (formatCh == 'G' || formatCh == 'g') { return DoFormatG(enumInfo, rawValue); } if (formatCh == 'F' || formatCh == 'f') { return DoFormatF(enumInfo, rawValue); } throw new FormatException(SR.Format_InvalidEnumFormatSpecification); } // // Helper for Enum.Format(,,"d") // private static String DoFormatD(ulong rawValue, RuntimeImports.RhCorElementType corElementType) { switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { SByte result = (SByte)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { Byte result = (Byte)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: { // direct cast from bool to byte is not allowed bool b = (rawValue != 0); return b.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { Int16 result = (Int16)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { UInt16 result = (UInt16)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { Char result = (Char)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { UInt32 result = (UInt32)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { Int32 result = (Int32)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { UInt64 result = (UInt64)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { Int64 result = (Int64)rawValue; return result.ToString(); } default: Debug.Assert(false, "Invalid Object type in Format"); throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } } // // Helper for Enum.Format(,,"x") // private static String DoFormatX(ulong rawValue, RuntimeImports.RhCorElementType corElementType) { switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { Byte result = (byte)(sbyte)rawValue; return result.ToString("X2", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { Byte result = (byte)rawValue; return result.ToString("X2", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: { // direct cast from bool to byte is not allowed Byte result = (byte)rawValue; return result.ToString("X2", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { UInt16 result = (UInt16)(Int16)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { UInt16 result = (UInt16)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { UInt16 result = (UInt16)(Char)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { UInt32 result = (UInt32)rawValue; return result.ToString("X8", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { UInt32 result = (UInt32)(int)rawValue; return result.ToString("X8", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { UInt64 result = (UInt64)rawValue; return result.ToString("X16", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { UInt64 result = (UInt64)(Int64)rawValue; return result.ToString("X16", null); } default: Debug.Assert(false, "Invalid Object type in Format"); throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } } // // Helper for Enum.Format(,,"g") // private static String DoFormatG(EnumInfo enumInfo, ulong rawValue) { Debug.Assert(enumInfo != null); if (!enumInfo.HasFlagsAttribute) // Not marked with Flags attribute { // Try to see if its one of the enum values, then we return a String back else the value String name = GetNameIfAny(enumInfo, rawValue); if (name == null) return DoFormatD(rawValue, enumInfo.UnderlyingType.TypeHandle.ToEETypePtr().CorElementType); else return name; } else // These are flags OR'ed together (We treat everything as unsigned types) { return DoFormatF(enumInfo, rawValue); } } // // Helper for Enum.Format(,,"f") // private static String DoFormatF(EnumInfo enumInfo, ulong rawValue) { Debug.Assert(enumInfo != null); // These values are sorted by value. Don't change this KeyValuePair<String, ulong>[] namesAndValues = enumInfo.NamesAndValues; int index = namesAndValues.Length - 1; StringBuilder retval = new StringBuilder(); bool firstTime = true; ulong result = rawValue; // We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied // to minimize the comparsions required. This code works the same for the best/worst case. In general the number of // items in an enum are sufficiently small and not worth the optimization. while (index >= 0) { if ((index == 0) && (namesAndValues[index].Value == 0)) break; if ((result & namesAndValues[index].Value) == namesAndValues[index].Value) { result -= namesAndValues[index].Value; if (!firstTime) retval.Insert(0, ", "); retval.Insert(0, namesAndValues[index].Key); firstTime = false; } index--; } // We were unable to represent this number as a bitwise or of valid flags if (result != 0) return DoFormatD(rawValue, enumInfo.UnderlyingType.TypeHandle.ToEETypePtr().CorElementType); // For the case when we have zero if (rawValue == 0) { if (namesAndValues.Length > 0 && namesAndValues[0].Value == 0) return namesAndValues[0].Key; // Zero was one of the enum values. else return "0"; } else return retval.ToString(); // Built a list of matching names. Return it. } internal Object GetValue() { ref byte pValue = ref this.GetRawData(); switch (this.EETypePtr.CorElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: return Unsafe.As<byte, bool>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: return Unsafe.As<byte, char>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: return Unsafe.As<byte, sbyte>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: return Unsafe.As<byte, byte>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: return Unsafe.As<byte, short>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: return Unsafe.As<byte, ushort>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: return Unsafe.As<byte, int>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: return Unsafe.As<byte, uint>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: return Unsafe.As<byte, long>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: return Unsafe.As<byte, ulong>(ref pValue); default: Environment.FailFast("Unexpected enum underlying type"); return 0; } } public static String GetName(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsRuntimeImplemented()) return enumType.GetEnumName(value); if (value == null) throw new ArgumentNullException(nameof(value)); ulong rawValue; if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue)) throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value)); // For desktop compatibility, do not bounce an incoming integer that's the wrong size. // Do a value-preserving cast of both it and the enum values and do a 64-bit compare. EnumInfo enumInfo = GetEnumInfo(enumType); String nameOrNull = GetNameIfAny(enumInfo, rawValue); return nameOrNull; } public static String[] GetNames(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsRuntimeImplemented()) return enumType.GetEnumNames(); KeyValuePair<String, ulong>[] namesAndValues = GetEnumInfo(enumType).NamesAndValues; String[] names = new String[namesAndValues.Length]; for (int i = 0; i < namesAndValues.Length; i++) names[i] = namesAndValues[i].Key; return names; } public static Type GetUnderlyingType(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); RuntimeTypeHandle runtimeTypeHandle = enumType.TypeHandle; EETypePtr eeType = runtimeTypeHandle.ToEETypePtr(); if (!eeType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); switch (eeType.CorElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: return CommonRuntimeTypes.Boolean; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: return CommonRuntimeTypes.Char; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: return CommonRuntimeTypes.SByte; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: return CommonRuntimeTypes.Byte; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: return CommonRuntimeTypes.Int16; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: return CommonRuntimeTypes.UInt16; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: return CommonRuntimeTypes.Int32; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: return CommonRuntimeTypes.UInt32; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: return CommonRuntimeTypes.Int64; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: return CommonRuntimeTypes.UInt64; default: throw new ArgumentException(); } } public static Array GetValues(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); Array values = GetEnumInfo(enumType).Values; int count = values.Length; EETypePtr enumArrayType = enumType.MakeArrayType().TypeHandle.ToEETypePtr(); Array result = RuntimeImports.RhNewArray(enumArrayType, count); Array.CopyImplValueTypeArrayNoInnerGcRefs(values, 0, result, 0, count); return result; } public Boolean HasFlag(Enum flag) { if (flag == null) throw new ArgumentNullException(nameof(flag)); Contract.EndContractBlock(); if (!(this.EETypePtr == flag.EETypePtr)) throw new ArgumentException(SR.Format(SR.Argument_EnumTypeDoesNotMatch, flag.GetType(), this.GetType())); ref byte pThisValue = ref this.GetRawData(); ref byte pFlagValue = ref flag.GetRawData(); switch (this.EETypePtr.CorElementTypeInfo.Log2OfSize) { case 0: return (Unsafe.As<byte, byte>(ref pThisValue) & Unsafe.As<byte, byte>(ref pFlagValue)) == Unsafe.As<byte, byte>(ref pFlagValue); case 1: return (Unsafe.As<byte, ushort>(ref pThisValue) & Unsafe.As<byte, ushort>(ref pFlagValue)) == Unsafe.As<byte, ushort>(ref pFlagValue); case 2: return (Unsafe.As<byte, uint>(ref pThisValue) & Unsafe.As<byte, uint>(ref pFlagValue)) == Unsafe.As<byte, uint>(ref pFlagValue); case 3: return (Unsafe.As<byte, ulong>(ref pThisValue) & Unsafe.As<byte, ulong>(ref pFlagValue)) == Unsafe.As<byte, ulong>(ref pFlagValue); default: Environment.FailFast("Unexpected enum underlying type"); return false; } } public static bool IsDefined(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsRuntimeImplemented()) return enumType.IsEnumDefined(value); if (value == null) throw new ArgumentNullException(nameof(value)); if (value.EETypePtr == EETypePtr.EETypePtrOf<string>()) { EnumInfo enumInfo = GetEnumInfo(enumType); foreach (KeyValuePair<String, ulong> kv in enumInfo.NamesAndValues) { if (value.Equals(kv.Key)) return true; } return false; } else { ulong rawValue; if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue)) { if (Type.IsIntegerType(value.GetType())) throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, value.GetType(), Enum.GetUnderlyingType(enumType))); else throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } EnumInfo enumInfo = null; if (value.EETypePtr.IsEnum) { if (!ValueTypeMatchesEnumType(enumType, value)) throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, value.GetType(), enumType)); } else { enumInfo = GetEnumInfo(enumType); if (!(enumInfo.UnderlyingType.TypeHandle.ToEETypePtr() == value.EETypePtr)) throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, value.GetType(), enumInfo.UnderlyingType)); } if (enumInfo == null) enumInfo = GetEnumInfo(enumType); String nameOrNull = GetNameIfAny(enumInfo, rawValue); return nameOrNull != null; } } public static Object Parse(Type enumType, String value) { return Parse(enumType, value, ignoreCase: false); } public static Object Parse(Type enumType, String value, bool ignoreCase) { Object result; Exception exception; if (!TryParseEnum(enumType, value, ignoreCase, out result, out exception)) throw exception; return result; } public static TEnum Parse<TEnum>(String value) where TEnum : struct { return Parse<TEnum>(value, ignoreCase: false); } public static TEnum Parse<TEnum>(String value, bool ignoreCase) where TEnum : struct { Object result; Exception exception; if (!TryParseEnum(typeof(TEnum), value, ignoreCase, out result, out exception)) throw exception; return (TEnum)result; } // // Non-boxing overloads for Enum.ToObject(). // // The underlying integer type of the enum does not have to match the type of "value." If // the enum type is larger, this api does a value-preserving widening if possible (or a 2's complement // conversion if not.) If the enum type is smaller, the api discards the higher order bits. // Either way, no exception is thrown upon overflow. // [CLSCompliant(false)] public static object ToObject(Type enumType, sbyte value) => ToObjectWorker(enumType, value); public static object ToObject(Type enumType, byte value) => ToObjectWorker(enumType, value); [CLSCompliant(false)] public static object ToObject(Type enumType, ushort value) => ToObjectWorker(enumType, value); public static object ToObject(Type enumType, short value) => ToObjectWorker(enumType, value); [CLSCompliant(false)] public static object ToObject(Type enumType, uint value) => ToObjectWorker(enumType, value); public static object ToObject(Type enumType, int value) => ToObjectWorker(enumType, value); [CLSCompliant(false)] public static object ToObject(Type enumType, ulong value) => ToObjectWorker(enumType, (long)value); public static object ToObject(Type enumType, long value) => ToObjectWorker(enumType, value); // These are needed to service ToObject(Type, Object). private static object ToObject(Type enumType, char value) => ToObjectWorker(enumType, value); private static object ToObject(Type enumType, bool value) => ToObjectWorker(enumType, value ? 1 : 0); // Common helper for the non-boxing Enum.ToObject() overloads. private static object ToObjectWorker(Type enumType, long value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsRuntimeImplemented()) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); EETypePtr enumEEType = enumType.TypeHandle.ToEETypePtr(); if (!enumEEType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); unsafe { byte* pValue = (byte*)&value; AdjustForEndianness(ref pValue, enumEEType); return RuntimeImports.RhBox(enumEEType, pValue); } } public static Object ToObject(Type enumType, Object value) { if (value == null) throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); // Delegate rest of error checking to the other functions TypeCode typeCode = Convert.GetTypeCode(value); switch (typeCode) { case TypeCode.Int32: return ToObject(enumType, (int)value); case TypeCode.SByte: return ToObject(enumType, (sbyte)value); case TypeCode.Int16: return ToObject(enumType, (short)value); case TypeCode.Int64: return ToObject(enumType, (long)value); case TypeCode.UInt32: return ToObject(enumType, (uint)value); case TypeCode.Byte: return ToObject(enumType, (byte)value); case TypeCode.UInt16: return ToObject(enumType, (ushort)value); case TypeCode.UInt64: return ToObject(enumType, (ulong)value); case TypeCode.Char: return ToObject(enumType, (char)value); case TypeCode.Boolean: return ToObject(enumType, (bool)value); default: // All unsigned types will be directly cast throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value)); } } public static bool TryParse(Type enumType, String value, bool ignoreCase, out Object result) { Exception exception; return TryParseEnum(enumType, value, ignoreCase, out result, out exception); } public static bool TryParse(Type enumType, String value, out Object result) { Exception exception; return TryParseEnum(enumType, value, false, out result, out exception); } public static bool TryParse<TEnum>(String value, bool ignoreCase, out TEnum result) where TEnum : struct { Exception exception; Object tempResult; if (!TryParseEnum(typeof(TEnum), value, ignoreCase, out tempResult, out exception)) { result = default(TEnum); return false; } result = (TEnum)tempResult; return true; } public static bool TryParse<TEnum>(String value, out TEnum result) where TEnum : struct { return TryParse<TEnum>(value, false, out result); } public override String ToString() { try { return this.ToString("G"); } catch (Exception) { return this.LastResortToString; } } public String ToString(String format) { if (format == null || format.Length == 0) format = "G"; EnumInfo enumInfo = GetEnumInfoIfAvailable(this.GetType()); // Project N port note: If Reflection info isn't available, fallback to ToString() which will substitute a numeric value for the "correct" output. // This scenario has been hit frequently when throwing exceptions formatted with error strings containing enum substitations. // To avoid replacing the masking the actual exception with an uninteresting MissingMetadataException, we choose instead // to return a base-effort string. if (enumInfo == null) return this.LastResortToString; return Format(enumInfo, this, format); } String IFormattable.ToString(String format, IFormatProvider provider) { return ToString(format); } [Obsolete("The provider argument is not used. Please use ToString().")] String IConvertible.ToString(IFormatProvider provider) { return ToString(); } // // Note: this helper also checks if the enumType is in fact an Enum and throws an user-visible ArgumentException if it's not. // private static EnumInfo GetEnumInfo(Type enumType) { EnumInfo enumInfo = GetEnumInfoIfAvailable(enumType); if (enumInfo == null) throw RuntimeAugments.Callbacks.CreateMissingMetadataException(enumType); return enumInfo; } // // Note: this helper also checks if the enumType is in fact an Enum and throws an user-visible ArgumentException if it's not. // private static EnumInfo GetEnumInfoIfAvailable(Type enumType) { RuntimeTypeHandle runtimeTypeHandle = enumType.TypeHandle; if (!runtimeTypeHandle.ToEETypePtr().IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum); return s_enumInfoCache.GetOrAdd(new TypeUnificationKey(enumType)); } // // Checks if value.GetType() matches enumType exactly. // private static bool ValueTypeMatchesEnumType(Type enumType, Object value) { EETypePtr enumEEType; if (!enumType.TryGetEEType(out enumEEType)) return false; if (!(enumEEType == value.EETypePtr)) return false; return true; } // Exported for use by legacy user-defined Type Enum apis. internal static ulong ToUInt64(object value) { ulong result; if (!TryGetUnboxedValueOfEnumOrInteger(value, out result)) throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); return result; } // // Note: This works on both Enum's and underlying integer values. // // // This returns the underlying enum values as "ulong" regardless of the actual underlying type. Signed integral // types get sign-extended into the 64-bit value, unsigned types get zero-extended. // // The return value is "bool" if "value" is not an enum or an "integer type" as defined by the BCL Enum apis. // private static bool TryGetUnboxedValueOfEnumOrInteger(Object value, out ulong result) { EETypePtr eeType = value.EETypePtr; // For now, this check is required to flush out pointers. if (!eeType.IsDefType) { result = 0; return false; } RuntimeImports.RhCorElementType corElementType = eeType.CorElementType; ref byte pValue = ref value.GetRawData(); switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: result = Unsafe.As<byte, bool>(ref pValue) ? 1UL : 0UL; return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: result = (ulong)(long)Unsafe.As<byte, char>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: result = (ulong)(long)Unsafe.As<byte, sbyte>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: result = (ulong)(long)Unsafe.As<byte, byte>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: result = (ulong)(long)Unsafe.As<byte, short>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: result = (ulong)(long)Unsafe.As<byte, ushort>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: result = (ulong)(long)Unsafe.As<byte, int>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: result = (ulong)(long)Unsafe.As<byte, uint>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: result = (ulong)(long)Unsafe.As<byte, long>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: result = (ulong)(long)Unsafe.As<byte, ulong>(ref pValue); return true; default: result = 0; return false; } } // // Look up a name for rawValue if a matching one exists. Returns null if no matching name exists. // private static String GetNameIfAny(EnumInfo enumInfo, ulong rawValue) { KeyValuePair<String, ulong>[] namesAndValues = enumInfo.NamesAndValues; KeyValuePair<String, ulong> searchKey = new KeyValuePair<String, ulong>(null, rawValue); int index = Array.BinarySearch<KeyValuePair<String, ulong>>(namesAndValues, searchKey, s_nameAndValueComparer); if (index < 0) return null; return namesAndValues[index].Key; } // // Common funnel for Enum.Parse methods. // private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, out Object result, out Exception exception) { exception = null; result = null; if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsRuntimeImplemented()) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); if (value == null) { exception = new ArgumentNullException(nameof(value)); return false; } int firstNonWhitespaceIndex = -1; for (int i = 0; i < value.Length; i++) { if (!char.IsWhiteSpace(value[i])) { firstNonWhitespaceIndex = i; break; } } if (firstNonWhitespaceIndex == -1) { exception = new ArgumentException(SR.Arg_MustContainEnumInfo); return false; } EETypePtr enumEEType = enumType.TypeHandle.ToEETypePtr(); if (!enumEEType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); if (TryParseAsInteger(enumEEType, value, firstNonWhitespaceIndex, out result)) return true; // Parse as string. Now (and only now) do we look for metadata information. EnumInfo enumInfo = RuntimeAugments.Callbacks.GetEnumInfoIfAvailable(enumType); if (enumInfo == null) throw RuntimeAugments.Callbacks.CreateMissingMetadataException(enumType); ulong v = 0; // Port note: The docs are silent on how multiple matches are resolved when doing case-insensitive parses. // The desktop's ad-hoc behavior is to pick the one with the smallest value after doing a value-preserving cast // to a ulong, so we'll follow that here. StringComparison comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; KeyValuePair<String, ulong>[] actualNamesAndValues = enumInfo.NamesAndValues; int valueIndex = firstNonWhitespaceIndex; while (valueIndex <= value.Length) // '=' is to handle invalid case of an ending comma { // Find the next separator, if there is one, otherwise the end of the string. int endIndex = value.IndexOf(',', valueIndex); if (endIndex == -1) { endIndex = value.Length; } // Shift the starting and ending indices to eliminate whitespace int endIndexNoWhitespace = endIndex; while (valueIndex < endIndex && char.IsWhiteSpace(value[valueIndex])) valueIndex++; while (endIndexNoWhitespace > valueIndex && char.IsWhiteSpace(value[endIndexNoWhitespace - 1])) endIndexNoWhitespace--; int valueSubstringLength = endIndexNoWhitespace - valueIndex; // Try to match this substring against each enum name bool foundMatch = false; foreach (KeyValuePair<String, ulong> kv in actualNamesAndValues) { String actualName = kv.Key; if (actualName.Length == valueSubstringLength && String.Compare(actualName, 0, value, valueIndex, valueSubstringLength, comparison) == 0) { v |= kv.Value; foundMatch = true; break; } } if (!foundMatch) { exception = new ArgumentException(SR.Format(SR.Arg_EnumValueNotFound, value)); return false; } // Move our pointer to the ending index to go again. valueIndex = endIndex + 1; } unsafe { result = RuntimeImports.RhBox(enumEEType, &v); //@todo: Not compatible with big-endian platforms. } return true; } private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int valueOffset, out Object result) { Debug.Assert(value != null, "Expected non-null value"); Debug.Assert(value.Length > 0, "Expected non-empty value"); Debug.Assert(valueOffset >= 0 && valueOffset < value.Length, "Expected valueOffset to be within value"); result = null; char firstNonWhitespaceChar = value[valueOffset]; if (!(Char.IsDigit(firstNonWhitespaceChar) || firstNonWhitespaceChar == '+' || firstNonWhitespaceChar == '-')) return false; RuntimeImports.RhCorElementType corElementType = enumEEType.CorElementType; value = value.Trim(); unsafe { switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: { Boolean v; if (!Boolean.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { Char v; if (!Char.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { SByte v; if (!SByte.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { Byte v; if (!Byte.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { Int16 v; if (!Int16.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { UInt16 v; if (!UInt16.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { Int32 v; if (!Int32.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { UInt32 v; if (!UInt32.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { Int64 v; if (!Int64.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { UInt64 v; if (!UInt64.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } default: throw new NotSupportedException(); } } } [Conditional("BIGENDIAN")] private static unsafe void AdjustForEndianness(ref byte* pValue, EETypePtr enumEEType) { // On Debug builds, include the big-endian code to help deter bitrot (the "Conditional("BIGENDIAN")" will prevent it from executing on little-endian). // On Release builds, exclude code to deter IL bloat and toolchain work. #if BIGENDIAN || DEBUG RuntimeImports.RhCorElementType corElementType = enumEEType.CorElementType; switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: pValue += sizeof(long) - sizeof(byte); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: pValue += sizeof(long) - sizeof(short); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: pValue += sizeof(long) - sizeof(int); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: break; default: throw new NotSupportedException(); } #endif //BIGENDIAN || DEBUG } // // Sort comparer for NamesAndValues // private class NamesAndValueComparer : IComparer<KeyValuePair<String, ulong>> { public int Compare(KeyValuePair<String, ulong> kv1, KeyValuePair<String, ulong> kv2) { ulong x = kv1.Value; ulong y = kv2.Value; if (x < y) return -1; else if (x > y) return 1; else return 0; } } private static NamesAndValueComparer s_nameAndValueComparer = new NamesAndValueComparer(); private String LastResortToString { get { return String.Format("{0}", GetValue()); } } private sealed class EnumInfoUnifier : ConcurrentUnifierW<TypeUnificationKey, EnumInfo> { protected override EnumInfo Factory(TypeUnificationKey key) { return RuntimeAugments.Callbacks.GetEnumInfoIfAvailable(key.Type); } } private static EnumInfoUnifier s_enumInfoCache = new EnumInfoUnifier(); #region IConvertible TypeCode IConvertible.GetTypeCode() { Type enumType = this.GetType(); Type underlyingType = GetUnderlyingType(enumType); if (underlyingType == typeof(Int32)) { return TypeCode.Int32; } if (underlyingType == typeof(sbyte)) { return TypeCode.SByte; } if (underlyingType == typeof(Int16)) { return TypeCode.Int16; } if (underlyingType == typeof(Int64)) { return TypeCode.Int64; } if (underlyingType == typeof(UInt32)) { return TypeCode.UInt32; } if (underlyingType == typeof(byte)) { return TypeCode.Byte; } if (underlyingType == typeof(UInt16)) { return TypeCode.UInt16; } if (underlyingType == typeof(UInt64)) { return TypeCode.UInt64; } if (underlyingType == typeof(Boolean)) { return TypeCode.Boolean; } if (underlyingType == typeof(Char)) { return TypeCode.Char; } Debug.Assert(false, "Unknown underlying type."); throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Enum", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } #endregion } }
// InflaterHuffmanTree.cs // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. #if ZIPLIB using System; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// Huffman tree used for inflation /// </summary> internal class InflaterHuffmanTree { #region Constants const int MAX_BITLEN = 15; #endregion #region Instance Fields short[] tree; #endregion /// <summary> /// Literal length tree /// </summary> public static InflaterHuffmanTree defLitLenTree; /// <summary> /// Distance tree /// </summary> public static InflaterHuffmanTree defDistTree; static InflaterHuffmanTree() { try { byte[] codeLengths = new byte[288]; int i = 0; while (i < 144) { codeLengths[i++] = 8; } while (i < 256) { codeLengths[i++] = 9; } while (i < 280) { codeLengths[i++] = 7; } while (i < 288) { codeLengths[i++] = 8; } defLitLenTree = new InflaterHuffmanTree(codeLengths); codeLengths = new byte[32]; i = 0; while (i < 32) { codeLengths[i++] = 5; } defDistTree = new InflaterHuffmanTree(codeLengths); } catch (Exception) { throw new SharpZipBaseException("InflaterHuffmanTree: static tree length illegal"); } } #region Constructors /// <summary> /// Constructs a Huffman tree from the array of code lengths. /// </summary> /// <param name = "codeLengths"> /// the array of code lengths /// </param> public InflaterHuffmanTree(byte[] codeLengths) { BuildTree(codeLengths); } #endregion void BuildTree(byte[] codeLengths) { int[] blCount = new int[MAX_BITLEN + 1]; int[] nextCode = new int[MAX_BITLEN + 1]; for (int i = 0; i < codeLengths.Length; i++) { int bits = codeLengths[i]; if (bits > 0) { blCount[bits]++; } } int code = 0; int treeSize = 512; for (int bits = 1; bits <= MAX_BITLEN; bits++) { nextCode[bits] = code; code += blCount[bits] << (16 - bits); if (bits >= 10) { /* We need an extra table for bit lengths >= 10. */ int start = nextCode[bits] & 0x1ff80; int end = code & 0x1ff80; treeSize += (end - start) >> (16 - bits); } } /* -jr comment this out! doesnt work for dynamic trees and pkzip 2.04g if (code != 65536) { throw new SharpZipBaseException("Code lengths don't add up properly."); } */ /* Now create and fill the extra tables from longest to shortest * bit len. This way the sub trees will be aligned. */ tree = new short[treeSize]; int treePtr = 512; for (int bits = MAX_BITLEN; bits >= 10; bits--) { int end = code & 0x1ff80; code -= blCount[bits] << (16 - bits); int start = code & 0x1ff80; for (int i = start; i < end; i += 1 << 7) { tree[DeflaterHuffman.BitReverse(i)] = (short) ((-treePtr << 4) | bits); treePtr += 1 << (bits-9); } } for (int i = 0; i < codeLengths.Length; i++) { int bits = codeLengths[i]; if (bits == 0) { continue; } code = nextCode[bits]; int revcode = DeflaterHuffman.BitReverse(code); if (bits <= 9) { do { tree[revcode] = (short) ((i << 4) | bits); revcode += 1 << bits; } while (revcode < 512); } else { int subTree = tree[revcode & 511]; int treeLen = 1 << (subTree & 15); subTree = -(subTree >> 4); do { tree[subTree | (revcode >> 9)] = (short) ((i << 4) | bits); revcode += 1 << bits; } while (revcode < treeLen); } nextCode[bits] = code + (1 << (16 - bits)); } } /// <summary> /// Reads the next symbol from input. The symbol is encoded using the /// huffman tree. /// </summary> /// <param name="input"> /// input the input source. /// </param> /// <returns> /// the next symbol, or -1 if not enough input is available. /// </returns> public int GetSymbol(StreamManipulator input) { int lookahead, symbol; if ((lookahead = input.PeekBits(9)) >= 0) { if ((symbol = tree[lookahead]) >= 0) { input.DropBits(symbol & 15); return symbol >> 4; } int subtree = -(symbol >> 4); int bitlen = symbol & 15; if ((lookahead = input.PeekBits(bitlen)) >= 0) { symbol = tree[subtree | (lookahead >> 9)]; input.DropBits(symbol & 15); return symbol >> 4; } else { int bits = input.AvailableBits; lookahead = input.PeekBits(bits); symbol = tree[subtree | (lookahead >> 9)]; if ((symbol & 15) <= bits) { input.DropBits(symbol & 15); return symbol >> 4; } else { return -1; } } } else { int bits = input.AvailableBits; lookahead = input.PeekBits(bits); symbol = tree[lookahead]; if (symbol >= 0 && (symbol & 15) <= bits) { input.DropBits(symbol & 15); return symbol >> 4; } else { return -1; } } } } } #endif
// // PersonaAuthorizer.cs // // Author: // Zachary Gramana <[email protected]> // // Copyright (c) 2013, 2014 Xamarin Inc (http://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. // /** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch, Traun Leyden * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using Couchbase.Lite; using Couchbase.Lite.Auth; using Couchbase.Lite.Util; using Sharpen; using System.Text; namespace Couchbase.Lite.Auth { public class PersonaAuthorizer : Authorizer { public const string LoginParameterAssertion = "assertion"; private static IDictionary<IList<string>, string> assertions; public const string AssertionFieldEmail = "email"; public const string AssertionFieldOrigin = "origin"; public const string AssertionFieldExpiration = "exp"; public const string QueryParameter = "personaAssertion"; private bool skipAssertionExpirationCheck; private string emailAddress; public PersonaAuthorizer(string emailAddress) { // set to true to skip checking whether assertions have expired (useful for testing) this.emailAddress = emailAddress; } public virtual void SetSkipAssertionExpirationCheck(bool skipAssertionExpirationCheck ) { this.skipAssertionExpirationCheck = skipAssertionExpirationCheck; } public virtual bool IsSkipAssertionExpirationCheck() { return skipAssertionExpirationCheck; } public virtual string GetEmailAddress() { return emailAddress; } protected internal virtual bool IsAssertionExpired(IDictionary<string, object> parsedAssertion ) { if (this.IsSkipAssertionExpirationCheck() == true) { return false; } DateTime exp; exp = (DateTime)parsedAssertion.Get(AssertionFieldExpiration); DateTime now = new DateTime(); if (exp < now) { Log.W(Database.Tag, string.Format("{0} assertion for {1} expired: {2}", GetType(), emailAddress, exp)); return true; } return false; } public virtual string AssertionForSite(Uri site) { var assertion = AssertionForEmailAndSite(emailAddress, site); if (assertion == null) { Log.W(Database.Tag, String.Format("{0} {1} no assertion found for: {2}", GetType(), emailAddress, site)); return null; } var result = ParseAssertion(assertion); return IsAssertionExpired (result) ? null : assertion; } public override bool UsesCookieBasedLogin { get { return true; } } public override IDictionary<string, string> LoginParametersForSite(Uri site) { IDictionary<string, string> loginParameters = new Dictionary<string, string>(); string assertion = AssertionForSite(site); if (assertion != null) { loginParameters[LoginParameterAssertion] = assertion; return loginParameters; } else { return null; } } public override string LoginPathForSite(Uri site) { return "/_persona"; } public static string RegisterAssertion(string assertion) { lock (typeof(PersonaAuthorizer)) { string email; string origin; IDictionary<string, object> result = ParseAssertion(assertion); email = (string)result.Get(AssertionFieldEmail); origin = (string)result.Get(AssertionFieldOrigin); // Normalize the origin URL string: try { Uri originURL = new Uri(origin); if (origin == null) { throw new ArgumentException("Invalid assertion, origin was null"); } origin = originURL.ToString().ToLower(); } catch (UriFormatException e) { string message = "Error registering assertion: " + assertion; Log.E(Database.Tag, message, e); throw new ArgumentException(message, e); } return RegisterAssertion(assertion, email, origin); } } /// <summary> /// don't use this!! this was factored out for testing purposes, and had to be /// made public since tests are in their own package. /// </summary> /// <remarks> /// don't use this!! this was factored out for testing purposes, and had to be /// made public since tests are in their own package. /// </remarks> public static string RegisterAssertion(string assertion, string email, string origin ) { lock (typeof(PersonaAuthorizer)) { IList<string> key = new AList<string>(); key.AddItem(email); key.AddItem(origin); if (assertions == null) { assertions = new Dictionary<IList<string>, string>(); } Log.D(Database.Tag, "PersonaAuthorizer registering key: " + key); assertions[key] = assertion; return email; } } public static IDictionary<string, object> ParseAssertion(string assertion) { // https://github.com/mozilla/id-specs/blob/prod/browserid/index.md // http://self-issued.info/docs/draft-jones-json-web-token-04.html var result = new Dictionary<string, object>(); var components = assertion.Split('.'); // split on "." if (components.Length < 4) { throw new ArgumentException("Invalid assertion given, only " + components.Length + " found. Expected 4+"); } var component1Decoded = Encoding.UTF8.GetString(Convert.FromBase64String(components[1])); var component3Decoded = Encoding.UTF8.GetString(Convert.FromBase64String(components[3])); try { var mapper = Manager.GetObjectMapper(); var component1Json = mapper.ReadValue<IDictionary<Object, Object>>(component1Decoded); var principal = (IDictionary<Object, Object>)component1Json.Get("principal"); result.Put(AssertionFieldEmail, principal.Get("email")); var component3Json = mapper.ReadValue<IDictionary<Object, Object>>(component3Decoded); result.Put(AssertionFieldOrigin, component3Json.Get("aud")); var expObject = (long)component3Json.Get("exp"); Log.D(Database.Tag, "PersonaAuthorizer exp: " + expObject + " class: " + expObject.GetType()); var expDate = Extensions.CreateDate(expObject); result[AssertionFieldExpiration] = expDate; } catch (IOException e) { string message = "Error parsing assertion: " + assertion; Log.E(Database.Tag, message, e); throw new ArgumentException(message, e); } return result; } public static string AssertionForEmailAndSite(string email, Uri site) { IList<string> key = new AList<string>(); key.AddItem(email); key.AddItem(site.ToString().ToLower()); Log.D(Database.Tag, "PersonaAuthorizer looking up key: " + key + " from list of assertions" ); return assertions.Get(key); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenSim.Framework.Client; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Connectors.Hypergrid; using OpenSim.Services.Interfaces; using OpenSim.Server.Base; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; using log4net; using Nini.Config; using Mono.Addins; namespace OpenSim.Region.CoreModules.Framework.InventoryAccess { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGInventoryAccessModule")] public class HGInventoryAccessModule : BasicInventoryAccessModule, INonSharedRegionModule, IInventoryAccessModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static HGAssetMapper m_assMapper; public static HGAssetMapper AssetMapper { get { return m_assMapper; } } private string m_HomeURI; private bool m_OutboundPermission; private string m_ThisGatekeeper; private bool m_RestrictInventoryAccessAbroad; private bool m_bypassPermissions = true; // This simple check makes it possible to support grids in which all the simulators // share all central services of the Robust server EXCEPT assets. In other words, // grids where the simulators' assets are kept in one DB and the users' inventory assets // are kept on another. When users rez items from inventory or take objects from world, // an HG-like asset copy takes place between the 2 servers, the world asset server and // the user's asset server. private bool m_CheckSeparateAssets = false; private string m_LocalAssetsURL = string.Empty; // private bool m_Initialized = false; #region INonSharedRegionModule public override string Name { get { return "HGInventoryAccessModule"; } } public override void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("InventoryAccessModule", ""); if (name == Name) { m_Enabled = true; InitialiseCommon(source); m_log.InfoFormat("[HG INVENTORY ACCESS MODULE]: {0} enabled.", Name); IConfig thisModuleConfig = source.Configs["HGInventoryAccessModule"]; if (thisModuleConfig != null) { m_HomeURI = Util.GetConfigVarFromSections<string>(source, "HomeURI", new string[] { "Startup", "Hypergrid", "HGInventoryAccessModule" }, String.Empty); m_ThisGatekeeper = Util.GetConfigVarFromSections<string>(source, "GatekeeperURI", new string[] { "Startup", "Hypergrid", "HGInventoryAccessModule" }, String.Empty); // Legacy. Renove soon! m_ThisGatekeeper = thisModuleConfig.GetString("Gatekeeper", m_ThisGatekeeper); m_OutboundPermission = thisModuleConfig.GetBoolean("OutboundPermission", true); m_RestrictInventoryAccessAbroad = thisModuleConfig.GetBoolean("RestrictInventoryAccessAbroad", true); m_CheckSeparateAssets = thisModuleConfig.GetBoolean("CheckSeparateAssets", false); m_LocalAssetsURL = thisModuleConfig.GetString("RegionHGAssetServerURI", string.Empty); m_LocalAssetsURL = m_LocalAssetsURL.Trim(new char[] { '/' }); } else m_log.Warn("[HG INVENTORY ACCESS MODULE]: HGInventoryAccessModule configs not found. ProfileServerURI not set!"); m_bypassPermissions = !Util.GetConfigVarFromSections<bool>(source, "serverside_object_permissions", new string[] { "Startup", "Permissions" }, true); } } } public override void AddRegion(Scene scene) { if (!m_Enabled) return; base.AddRegion(scene); m_assMapper = new HGAssetMapper(scene, m_HomeURI); scene.EventManager.OnNewInventoryItemUploadComplete += PostInventoryAsset; scene.EventManager.OnTeleportStart += TeleportStart; scene.EventManager.OnTeleportFail += TeleportFail; // We're fgoing to enforce some stricter permissions if Outbound is false scene.Permissions.OnTakeObject += CanTakeObject; scene.Permissions.OnTakeCopyObject += CanTakeObject; scene.Permissions.OnTransferUserInventory += OnTransferUserInventory; } #endregion #region Event handlers protected override void OnNewClient(IClientAPI client) { base.OnNewClient(client); client.OnCompleteMovementToRegion += new Action<IClientAPI, bool>(OnCompleteMovementToRegion); } protected void OnCompleteMovementToRegion(IClientAPI client, bool arg2) { //m_log.DebugFormat("[HG INVENTORY ACCESS MODULE]: OnCompleteMovementToRegion of user {0}", client.Name); object sp = null; if (client.Scene.TryGetScenePresence(client.AgentId, out sp)) { if (sp is ScenePresence) { AgentCircuitData aCircuit = ((ScenePresence)sp).Scene.AuthenticateHandler.GetAgentCircuitData(client.AgentId); if (aCircuit != null && (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0) { if (m_RestrictInventoryAccessAbroad) { IUserManagement uMan = m_Scene.RequestModuleInterface<IUserManagement>(); if (uMan.IsLocalGridUser(client.AgentId)) ProcessInventoryForComingHome(client); else ProcessInventoryForArriving(client); } } } } } protected void TeleportStart(IClientAPI client, GridRegion destination, GridRegion finalDestination, uint teleportFlags, bool gridLogout) { if (gridLogout && m_RestrictInventoryAccessAbroad) { IUserManagement uMan = m_Scene.RequestModuleInterface<IUserManagement>(); if (uMan != null && uMan.IsLocalGridUser(client.AgentId)) { // local grid user ProcessInventoryForHypergriding(client); } else { // Foreigner ProcessInventoryForLeaving(client); } } } protected void TeleportFail(IClientAPI client, bool gridLogout) { if (gridLogout && m_RestrictInventoryAccessAbroad) { IUserManagement uMan = m_Scene.RequestModuleInterface<IUserManagement>(); if (uMan.IsLocalGridUser(client.AgentId)) { ProcessInventoryForComingHome(client); } else { ProcessInventoryForArriving(client); } } } private void PostInventoryAsset(InventoryItemBase item, int userlevel) { InventoryFolderBase f = m_Scene.InventoryService.GetFolderForType(item.Owner, FolderType.Trash); if (f == null || (f != null && item.Folder != f.ID)) PostInventoryAsset(item.Owner, (AssetType)item.AssetType, item.AssetID, item.Name, userlevel); } private void PostInventoryAsset(UUID avatarID, AssetType type, UUID assetID, string name, int userlevel) { if (type == AssetType.Link) return; string userAssetServer = string.Empty; if (IsForeignUser(avatarID, out userAssetServer) && userAssetServer != string.Empty && m_OutboundPermission) { m_assMapper.Post(assetID, avatarID, userAssetServer); } } #endregion #region Overrides of Basic Inventory Access methods protected override string GenerateLandmark(ScenePresence presence, out string prefix, out string suffix) { if (UserManagementModule != null && !UserManagementModule.IsLocalGridUser(presence.UUID)) prefix = "HG "; else prefix = string.Empty; suffix = " @ " + m_ThisGatekeeper; Vector3 pos = presence.AbsolutePosition; return String.Format("Landmark version 2\nregion_id {0}\nlocal_pos {1} {2} {3}\nregion_handle {4}\ngatekeeper {5}\n", presence.Scene.RegionInfo.RegionID, pos.X, pos.Y, pos.Z, presence.RegionHandle, m_ThisGatekeeper); } /// /// CapsUpdateInventoryItemAsset /// public override UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data) { UUID newAssetID = base.CapsUpdateInventoryItemAsset(remoteClient, itemID, data); // We need to construct this here to satisfy the calling convention. // Better this in two places than five formal params in all others. InventoryItemBase item = new InventoryItemBase(); item.Owner = remoteClient.AgentId; item.AssetType = (int)AssetType.Unknown; item.AssetID = newAssetID; item.Name = String.Empty; PostInventoryAsset(item, 0); return newAssetID; } /// /// UpdateInventoryItemAsset /// public override bool UpdateInventoryItemAsset(UUID ownerID, InventoryItemBase item, AssetBase asset) { if (base.UpdateInventoryItemAsset(ownerID, item, asset)) { PostInventoryAsset(item, 0); return true; } return false; } /// /// Used in DeleteToInventory /// protected override void ExportAsset(UUID agentID, UUID assetID) { if (!assetID.Equals(UUID.Zero)) { InventoryItemBase item = new InventoryItemBase(); item.Owner = agentID; item.AssetType = (int)AssetType.Unknown; item.AssetID = assetID; item.Name = String.Empty; PostInventoryAsset(item, 0); } else { m_log.Debug("[HGScene]: Scene.Inventory did not create asset"); } } /// /// RezObject /// // compatibility do not use public override SceneObjectGroup RezObject( IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment) { return RezObject(remoteClient, itemID, UUID.Zero, RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection, RezSelected, RemoveItem, fromTaskID, attachment); } public override SceneObjectGroup RezObject(IClientAPI remoteClient, UUID itemID, UUID groupID, Vector3 RayEnd, Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment) { //m_log.DebugFormat("[HGScene]: RezObject itemID={0} fromTaskID={1}", itemID, fromTaskID); //if (fromTaskID.Equals(UUID.Zero)) //{ InventoryItemBase item = m_Scene.InventoryService.GetItem(remoteClient.AgentId, itemID); //if (item == null) //{ // Fetch the item // item = new InventoryItemBase(); // item.Owner = remoteClient.AgentId; // item.ID = itemID; // item = m_assMapper.Get(item, userInfo.RootFolder.ID, userInfo); //} string userAssetServer = string.Empty; if (item != null && IsForeignUser(remoteClient.AgentId, out userAssetServer)) { m_assMapper.Get(item.AssetID, remoteClient.AgentId, userAssetServer); } //} // OK, we're done fetching. Pass it up to the default RezObject SceneObjectGroup sog = base.RezObject(remoteClient, itemID, groupID, RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection, RezSelected, RemoveItem, fromTaskID, attachment); return sog; } public override void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver) { string senderAssetServer = string.Empty; string receiverAssetServer = string.Empty; bool isForeignSender, isForeignReceiver; isForeignSender = IsForeignUser(sender, out senderAssetServer); isForeignReceiver = IsForeignUser(receiver, out receiverAssetServer); // They're both local. Nothing to do. if (!isForeignSender && !isForeignReceiver) return; // At least one of them is foreign. // If both users have the same asset server, no need to transfer the asset if (senderAssetServer.Equals(receiverAssetServer)) { m_log.DebugFormat("[HGScene]: Asset transfer between foreign users, but they have the same server. No transfer."); return; } if (isForeignSender && senderAssetServer != string.Empty) m_assMapper.Get(item.AssetID, sender, senderAssetServer); if (isForeignReceiver && receiverAssetServer != string.Empty && m_OutboundPermission) m_assMapper.Post(item.AssetID, receiver, receiverAssetServer); } public override bool IsForeignUser(UUID userID, out string assetServerURL) { assetServerURL = string.Empty; if (UserManagementModule != null) { if (!m_CheckSeparateAssets) { if (!UserManagementModule.IsLocalGridUser(userID)) { // foreign ScenePresence sp = null; if (m_Scene.TryGetScenePresence(userID, out sp)) { AgentCircuitData aCircuit = m_Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode); if (aCircuit != null && aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("AssetServerURI")) { assetServerURL = aCircuit.ServiceURLs["AssetServerURI"].ToString(); assetServerURL = assetServerURL.Trim(new char[] { '/' }); } } else { assetServerURL = UserManagementModule.GetUserServerURL(userID, "AssetServerURI"); assetServerURL = assetServerURL.Trim(new char[] { '/' }); } return true; } } else { if (IsLocalInventoryAssetsUser(userID, out assetServerURL)) { m_log.DebugFormat("[HGScene]: user {0} has local assets {1}", userID, assetServerURL); return false; } else { m_log.DebugFormat("[HGScene]: user {0} has foreign assets {1}", userID, assetServerURL); return true; } } } return false; } private bool IsLocalInventoryAssetsUser(UUID uuid, out string assetsURL) { assetsURL = UserManagementModule.GetUserServerURL(uuid, "AssetServerURI"); if (assetsURL == string.Empty) { AgentCircuitData agent = m_Scene.AuthenticateHandler.GetAgentCircuitData(uuid); if (agent != null) { assetsURL = agent.ServiceURLs["AssetServerURI"].ToString(); assetsURL = assetsURL.Trim(new char[] { '/' }); } } return m_LocalAssetsURL.Equals(assetsURL); } protected override InventoryItemBase GetItem(UUID agentID, UUID itemID) { InventoryItemBase item = base.GetItem(agentID, itemID); if (item == null) return null; string userAssetServer = string.Empty; if (IsForeignUser(agentID, out userAssetServer)) m_assMapper.Get(item.AssetID, agentID, userAssetServer); return item; } #endregion #region Inventory manipulation upon arriving/leaving // // These 2 are for local and foreign users coming back, respectively // private void ProcessInventoryForComingHome(IClientAPI client) { m_log.DebugFormat("[HG INVENTORY ACCESS MODULE]: Restoring root folder for local user {0}", client.Name); if (client is IClientCore) { IClientCore core = (IClientCore)client; IClientInventory inv; if (core.TryGet<IClientInventory>(out inv)) { InventoryFolderBase root = m_Scene.InventoryService.GetRootFolder(client.AgentId); InventoryCollection content = m_Scene.InventoryService.GetFolderContent(client.AgentId, root.ID); List<InventoryFolderBase> keep = new List<InventoryFolderBase>(); foreach (InventoryFolderBase f in content.Folders) { if (f.Name != "My Suitcase" && f.Name != "Current Outfit") keep.Add(f); } inv.SendBulkUpdateInventory(keep.ToArray(), content.Items.ToArray()); } } } private void ProcessInventoryForArriving(IClientAPI client) { // No-op for now, but we may need to do something for freign users inventory } // // These 2 are for local and foreign users going away respectively // private void ProcessInventoryForHypergriding(IClientAPI client) { if (client is IClientCore) { IClientCore core = (IClientCore)client; IClientInventory inv; if (core.TryGet<IClientInventory>(out inv)) { InventoryFolderBase root = m_Scene.InventoryService.GetRootFolder(client.AgentId); if (root != null) { m_log.DebugFormat("[HG INVENTORY ACCESS MODULE]: Changing root inventory for user {0}", client.Name); InventoryCollection content = m_Scene.InventoryService.GetFolderContent(client.AgentId, root.ID); List<InventoryFolderBase> keep = new List<InventoryFolderBase>(); foreach (InventoryFolderBase f in content.Folders) { if (f.Name != "My Suitcase" && f.Name != "Current Outfit") { f.Name = f.Name + " (Unavailable)"; keep.Add(f); } } // items directly under the root folder foreach (InventoryItemBase it in content.Items) it.Name = it.Name + " (Unavailable)"; ; // Send the new names inv.SendBulkUpdateInventory(keep.ToArray(), content.Items.ToArray()); } } } } private void ProcessInventoryForLeaving(IClientAPI client) { // No-op for now } #endregion #region Permissions private bool CanTakeObject(SceneObjectGroup sog, ScenePresence sp) { if (m_bypassPermissions) return true; if(sp == null || sog == null) return false; if (!m_OutboundPermission && !UserManagementModule.IsLocalGridUser(sp.UUID)) { if (sog.OwnerID == sp.UUID) return true; return false; } return true; } private bool OnTransferUserInventory(UUID itemID, UUID userID, UUID recipientID) { if (m_bypassPermissions) return true; if (!m_OutboundPermission && !UserManagementModule.IsLocalGridUser(recipientID)) return false; return true; } #endregion } }
using System; using System.Collections.Generic; using System.Data.Services.Common; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.Versioning; namespace NuGet { [DataServiceKey("Id", "Version")] [EntityPropertyMapping("LastUpdated", SyndicationItemProperty.Updated, SyndicationTextContentKind.Plaintext, keepInContent: false)] [EntityPropertyMapping("Id", SyndicationItemProperty.Title, SyndicationTextContentKind.Plaintext, keepInContent: false)] [EntityPropertyMapping("Authors", SyndicationItemProperty.AuthorName, SyndicationTextContentKind.Plaintext, keepInContent: false)] [EntityPropertyMapping("Summary", SyndicationItemProperty.Summary, SyndicationTextContentKind.Plaintext, keepInContent: false)] [CLSCompliant(false)] public class DataServicePackage : IPackage { private IHashProvider _hashProvider; private bool _usingMachineCache; internal IPackage _package; public string Id { get; set; } public string Version { get; set; } public string Title { get; set; } public string Authors { get; set; } public string Owners { get; set; } public Uri IconUrl { get; set; } public Uri LicenseUrl { get; set; } public Uri ProjectUrl { get; set; } public Uri ReportAbuseUrl { get; set; } public Uri GalleryDetailsUrl { get; set; } public Uri DownloadUrl { get { return Context.GetReadStreamUri(this); } } public bool Listed { get; set; } public DateTimeOffset? Published { get; set; } public DateTimeOffset LastUpdated { get; set; } public int DownloadCount { get; set; } public int VersionDownloadCount { get; set; } public bool RequireLicenseAcceptance { get; set; } public string Description { get; set; } public string Summary { get; set; } public string ReleaseNotes { get; set; } public string Language { get; set; } public string Tags { get; set; } public string Dependencies { get; set; } public string PackageHash { get; set; } public string PackageHashAlgorithm { get; set; } public bool IsLatestVersion { get; set; } public bool IsAbsoluteLatestVersion { get; set; } public string Copyright { get; set; } private string OldHash { get; set; } private IPackage Package { get { EnsurePackage(MachineCache.Default); return _package; } } internal IDataServiceContext Context { get; set; } internal PackageDownloader Downloader { get; set; } internal IHashProvider HashProvider { get { return _hashProvider ?? new CryptoHashProvider(PackageHashAlgorithm); } set { _hashProvider = value; } } bool IPackage.Listed { get { return Listed; } } IEnumerable<string> IPackageMetadata.Authors { get { if (String.IsNullOrEmpty(Authors)) { return Enumerable.Empty<string>(); } return Authors.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } } IEnumerable<string> IPackageMetadata.Owners { get { if (String.IsNullOrEmpty(Owners)) { return Enumerable.Empty<string>(); } return Owners.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } } public IEnumerable<PackageDependencySet> DependencySets { get { if (String.IsNullOrEmpty(Dependencies)) { return Enumerable.Empty<PackageDependencySet>(); } return ParseDependencySet(Dependencies); } } SemanticVersion IPackageMetadata.Version { get { if (Version != null) { return new SemanticVersion(Version); } return null; } } public IEnumerable<IPackageAssemblyReference> AssemblyReferences { get { return Package.AssemblyReferences; } } public IEnumerable<FrameworkAssemblyReference> FrameworkAssemblies { get { return Package.FrameworkAssemblies; } } public virtual IEnumerable<FrameworkName> GetSupportedFrameworks() { return Package.GetSupportedFrameworks(); } public IEnumerable<IPackageFile> GetFiles() { return Package.GetFiles(); } public Stream GetStream() { return Package.GetStream(); } public override string ToString() { return this.GetFullName(); } internal void EnsurePackage(IPackageRepository cacheRepository) { // OData caches instances of DataServicePackage while updating their property values. As a result, // the ZipPackage that we downloaded may no longer be valid (as indicated by a newer hash). // When using MachineCache, once we've verified that the hashes match (which happens the first time around), // we'll simply verify the file exists between successive calls. IPackageMetadata packageMetadata = this; bool refreshPackage = _package == null || !String.Equals(OldHash, PackageHash, StringComparison.OrdinalIgnoreCase) || (_usingMachineCache && !cacheRepository.Exists(Id, packageMetadata.Version)); if (refreshPackage && TryGetPackage(cacheRepository, packageMetadata, out _package) && _package.GetHash(HashProvider).Equals(PackageHash, StringComparison.OrdinalIgnoreCase)) { OldHash = PackageHash; // Reset the flag so that we no longer need to download the package since it exists and is valid. refreshPackage = false; // Make a note that we the backing store for the ZipPackage is the machine cache. _usingMachineCache = true; } if (refreshPackage) { // We either do not have a package available locally or they are invalid. Download the package from the server. _package = Downloader.DownloadPackage(DownloadUrl, this); // Make a note that we are using an in-memory instance of the package. _usingMachineCache = false; // Add the package to the cache cacheRepository.AddPackage(_package); OldHash = PackageHash; // Clear any cached items for this package ZipPackage.ClearCache(_package); } } private static List<PackageDependencySet> ParseDependencySet(string value) { var dependencySets = new List<PackageDependencySet>(); var dependencies = value.Split('|').Select(ParseDependency).ToList(); // group the dependencies by target framework var groups = dependencies.GroupBy(d => d.Item3); dependencySets.AddRange( groups.Select(g => new PackageDependencySet( g.Key, // target framework g.Where(pair => !String.IsNullOrEmpty(pair.Item1)) // the Id is empty when a group is empty. .Select(pair => new PackageDependency(pair.Item1, pair.Item2))))); // dependencies by that target framework return dependencySets; } /// <summary> /// Parses a dependency from the feed in the format: /// id or id:versionSpec, or id:versionSpec:targetFramework /// </summary> private static Tuple<string, IVersionSpec, FrameworkName> ParseDependency(string value) { if (String.IsNullOrWhiteSpace(value)) { return null; } // IMPORTANT: Do not pass StringSplitOptions.RemoveEmptyEntries to this method, because it will break // if the version spec is null, for in that case, the Dependencies string sent down is "<id>::<target framework>". // We do want to preserve the second empty element after the split. string[] tokens = value.Trim().Split(new[] { ':' }); if (tokens.Length == 0) { return null; } // Trim the id string id = tokens[0].Trim(); IVersionSpec versionSpec = null; if (tokens.Length > 1) { // Attempt to parse the version VersionUtility.TryParseVersionSpec(tokens[1], out versionSpec); } var targetFramework = (tokens.Length > 2 && !String.IsNullOrEmpty(tokens[2])) ? VersionUtility.ParseFrameworkName(tokens[2]) : null; return Tuple.Create(id, versionSpec, targetFramework); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to return null if any error occurred while trying to find the package.")] private static bool TryGetPackage(IPackageRepository repository, IPackageMetadata packageMetadata, out IPackage package) { try { package = repository.FindPackage(packageMetadata.Id, packageMetadata.Version); } catch { // If the package in the repository is corrupted then return null package = null; } return package != null; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics.CodeAnalysis; using System.Linq; using NetGore; using NetGore.IO; namespace DemoGame { /// <summary> /// Represents a unique ID for an Item template. /// </summary> [Serializable] [TypeConverter(typeof(ItemTemplateIDTypeConverter))] public struct ItemTemplateID : IComparable<ItemTemplateID>, IConvertible, IFormattable, IComparable<int>, IEquatable<int> { /// <summary> /// Represents the largest possible value of ItemTemplateID. This field is constant. /// </summary> public const int MaxValue = int.MaxValue; /// <summary> /// Represents the smallest possible value of ItemTemplateID. This field is constant. /// </summary> public const int MinValue = int.MinValue; /// <summary> /// The underlying value. This contains the actual value of the struct instance. /// </summary> readonly int _value; /// <summary> /// Initializes a new instance of the <see cref="ItemTemplateID"/> struct. /// </summary> /// <param name="value">Value to assign to the new ItemTemplateID.</param> /// <exception cref="ArgumentOutOfRangeException"><c>value</c> is out of range.</exception> public ItemTemplateID(int value) { if (value < MinValue || value > MaxValue) throw new ArgumentOutOfRangeException("value"); _value = value; } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="other">Another object to compare to.</param> /// <returns> /// True if <paramref name="other"/> and this instance are the same type and represent the same value; otherwise, false. /// </returns> public bool Equals(ItemTemplateID other) { return other._value == _value; } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">Another object to compare to.</param> /// <returns> /// True if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false. /// </returns> public override bool Equals(object obj) { return obj is ItemTemplateID && this == (ItemTemplateID)obj; } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns> /// A 32-bit signed integer that is the hash code for this instance. /// </returns> public override int GetHashCode() { return _value.GetHashCode(); } /// <summary> /// Gets the raw internal value of this ItemTemplateID. /// </summary> /// <returns>The raw internal value.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public int GetRawValue() { return _value; } /// <summary> /// Reads an ItemTemplateID from an IValueReader. /// </summary> /// <param name="reader">IValueReader to read from.</param> /// <param name="name">Unique name of the value to read.</param> /// <returns>The ItemTemplateID read from the IValueReader.</returns> public static ItemTemplateID Read(IValueReader reader, string name) { var value = reader.ReadInt(name); return new ItemTemplateID(value); } /// <summary> /// Reads an ItemTemplateID from an <see cref="IDataRecord"/>. /// </summary> /// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param> /// <param name="i">The index of the field to find.</param> /// <returns>The ItemTemplateID read from the <see cref="IDataRecord"/>.</returns> public static ItemTemplateID Read(IDataRecord reader, int i) { var value = reader.GetValue(i); if (value is int) return new ItemTemplateID((int)value); var convertedValue = Convert.ToInt32(value); return new ItemTemplateID(convertedValue); } /// <summary> /// Reads an ItemTemplateID from an <see cref="IDataRecord"/>. /// </summary> /// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param> /// <param name="name">The name of the field to find.</param> /// <returns>The ItemTemplateID read from the <see cref="IDataRecord"/>.</returns> public static ItemTemplateID Read(IDataRecord reader, string name) { return Read(reader, reader.GetOrdinal(name)); } /// <summary> /// Reads an ItemTemplateID from an IValueReader. /// </summary> /// <param name="bitStream">BitStream to read from.</param> /// <returns>The ItemTemplateID read from the BitStream.</returns> public static ItemTemplateID Read(BitStream bitStream) { var value = bitStream.ReadInt(); return new ItemTemplateID(value); } /// <summary> /// Converts the numeric value of this instance to its equivalent string representation. /// </summary> /// <returns>The string representation of the value of this instance, consisting of a sequence /// of digits ranging from 0 to 9, without leading zeroes.</returns> public override string ToString() { return _value.ToString(); } /// <summary> /// Writes the ItemTemplateID to an IValueWriter. /// </summary> /// <param name="writer">IValueWriter to write to.</param> /// <param name="name">Unique name of the ItemTemplateID that will be used to distinguish it /// from other values when reading.</param> public void Write(IValueWriter writer, string name) { writer.Write(name, _value); } /// <summary> /// Writes the ItemTemplateID to an IValueWriter. /// </summary> /// <param name="bitStream">BitStream to write to.</param> public void Write(BitStream bitStream) { bitStream.Write(_value); } #region IComparable<int> Members /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: /// Value /// Meaning /// Less than zero /// This object is less than the <paramref name="other"/> parameter. /// Zero /// This object is equal to <paramref name="other"/>. /// Greater than zero /// This object is greater than <paramref name="other"/>. /// </returns> public int CompareTo(int other) { return _value.CompareTo(other); } #endregion #region IComparable<ItemTemplateID> Members /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. /// The return value has the following meanings: /// Value /// Meaning /// Less than zero /// This object is less than the <paramref name="other"/> parameter. /// Zero /// This object is equal to <paramref name="other"/>. /// Greater than zero /// This object is greater than <paramref name="other"/>. /// </returns> public int CompareTo(ItemTemplateID other) { return _value.CompareTo(other._value); } #endregion #region IConvertible Members /// <summary> /// Returns the <see cref="T:System.TypeCode"/> for this instance. /// </summary> /// <returns> /// The enumerated constant that is the <see cref="T:System.TypeCode"/> of the class or value type that implements this interface. /// </returns> public TypeCode GetTypeCode() { return _value.GetTypeCode(); } /// <summary> /// Converts the value of this instance to an equivalent Boolean value using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation /// that supplies culture-specific formatting information.</param> /// <returns> /// A Boolean value equivalent to the value of this instance. /// </returns> bool IConvertible.ToBoolean(IFormatProvider provider) { return ((IConvertible)_value).ToBoolean(provider); } /// <summary> /// Converts the value of this instance to an equivalent 8-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 8-bit unsigned integer equivalent to the value of this instance. /// </returns> byte IConvertible.ToByte(IFormatProvider provider) { return ((IConvertible)_value).ToByte(provider); } /// <summary> /// Converts the value of this instance to an equivalent Unicode character using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A Unicode character equivalent to the value of this instance. /// </returns> char IConvertible.ToChar(IFormatProvider provider) { return ((IConvertible)_value).ToChar(provider); } /// <summary> /// Converts the value of this instance to an equivalent <see cref="T:System.DateTime"/> using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A <see cref="T:System.DateTime"/> instance equivalent to the value of this instance. /// </returns> DateTime IConvertible.ToDateTime(IFormatProvider provider) { return ((IConvertible)_value).ToDateTime(provider); } /// <summary> /// Converts the value of this instance to an equivalent <see cref="T:System.Decimal"/> number using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information. </param> /// <returns> /// A <see cref="T:System.Decimal"/> number equivalent to the value of this instance. /// </returns> decimal IConvertible.ToDecimal(IFormatProvider provider) { return ((IConvertible)_value).ToDecimal(provider); } /// <summary> /// Converts the value of this instance to an equivalent double-precision floating-point number using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A double-precision floating-point number equivalent to the value of this instance. /// </returns> double IConvertible.ToDouble(IFormatProvider provider) { return ((IConvertible)_value).ToDouble(provider); } /// <summary> /// Converts the value of this instance to an equivalent 16-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 16-bit signed integer equivalent to the value of this instance. /// </returns> short IConvertible.ToInt16(IFormatProvider provider) { return ((IConvertible)_value).ToInt16(provider); } /// <summary> /// Converts the value of this instance to an equivalent 32-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 32-bit signed integer equivalent to the value of this instance. /// </returns> int IConvertible.ToInt32(IFormatProvider provider) { return ((IConvertible)_value).ToInt32(provider); } /// <summary> /// Converts the value of this instance to an equivalent 64-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 64-bit signed integer equivalent to the value of this instance. /// </returns> long IConvertible.ToInt64(IFormatProvider provider) { return ((IConvertible)_value).ToInt64(provider); } /// <summary> /// Converts the value of this instance to an equivalent 8-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 8-bit signed integer equivalent to the value of this instance. /// </returns> sbyte IConvertible.ToSByte(IFormatProvider provider) { return ((IConvertible)_value).ToSByte(provider); } /// <summary> /// Converts the value of this instance to an equivalent single-precision floating-point number using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information. </param> /// <returns> /// A single-precision floating-point number equivalent to the value of this instance. /// </returns> float IConvertible.ToSingle(IFormatProvider provider) { return ((IConvertible)_value).ToSingle(provider); } /// <summary> /// Converts the value of this instance to an equivalent <see cref="T:System.String"/> using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A <see cref="T:System.String"/> instance equivalent to the value of this instance. /// </returns> public string ToString(IFormatProvider provider) { return ((IConvertible)_value).ToString(provider); } /// <summary> /// Converts the value of this instance to an <see cref="T:System.Object"/> of the specified <see cref="T:System.Type"/> that has an equivalent value, using the specified culture-specific formatting information. /// </summary> /// <param name="conversionType">The <see cref="T:System.Type"/> to which the value of this instance is converted.</param> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An <see cref="T:System.Object"/> instance of type <paramref name="conversionType"/> whose value is equivalent to the value of this instance. /// </returns> object IConvertible.ToType(Type conversionType, IFormatProvider provider) { return ((IConvertible)_value).ToType(conversionType, provider); } /// <summary> /// Converts the value of this instance to an equivalent 16-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 16-bit unsigned integer equivalent to the value of this instance. /// </returns> ushort IConvertible.ToUInt16(IFormatProvider provider) { return ((IConvertible)_value).ToUInt16(provider); } /// <summary> /// Converts the value of this instance to an equivalent 32-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 32-bit unsigned integer equivalent to the value of this instance. /// </returns> uint IConvertible.ToUInt32(IFormatProvider provider) { return ((IConvertible)_value).ToUInt32(provider); } /// <summary> /// Converts the value of this instance to an equivalent 64-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 64-bit unsigned integer equivalent to the value of this instance. /// </returns> ulong IConvertible.ToUInt64(IFormatProvider provider) { return ((IConvertible)_value).ToUInt64(provider); } #endregion #region IEquatable<int> Members /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> public bool Equals(int other) { return _value.Equals(other); } #endregion #region IFormattable Members /// <summary> /// Formats the value of the current instance using the specified format. /// </summary> /// <param name="format">The <see cref="T:System.String"/> specifying the format to use. /// -or- /// null to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation. /// </param> /// <param name="formatProvider">The <see cref="T:System.IFormatProvider"/> to use to format the value. /// -or- /// null to obtain the numeric format information from the current locale setting of the operating system. /// </param> /// <returns> /// A <see cref="T:System.String"/> containing the value of the current instance in the specified format. /// </returns> public string ToString(string format, IFormatProvider formatProvider) { return _value.ToString(format, formatProvider); } #endregion /// <summary> /// Implements operator ++. /// </summary> /// <param name="l">The ItemTemplateID to increment.</param> /// <returns>The incremented ItemTemplateID.</returns> public static ItemTemplateID operator ++(ItemTemplateID l) { return new ItemTemplateID(l._value + 1); } /// <summary> /// Implements operator --. /// </summary> /// <param name="l">The ItemTemplateID to decrement.</param> /// <returns>The decremented ItemTemplateID.</returns> public static ItemTemplateID operator --(ItemTemplateID l) { return new ItemTemplateID(l._value - 1); } /// <summary> /// Implements operator +. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>Result of the left side plus the right side.</returns> public static ItemTemplateID operator +(ItemTemplateID left, ItemTemplateID right) { return new ItemTemplateID(left._value + right._value); } /// <summary> /// Implements operator -. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>Result of the left side minus the right side.</returns> public static ItemTemplateID operator -(ItemTemplateID left, ItemTemplateID right) { return new ItemTemplateID(left._value - right._value); } /// <summary> /// Implements operator ==. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are equal.</returns> public static bool operator ==(ItemTemplateID left, int right) { return left._value == right; } /// <summary> /// Implements operator !=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are not equal.</returns> public static bool operator !=(ItemTemplateID left, int right) { return left._value != right; } /// <summary> /// Implements operator ==. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are equal.</returns> public static bool operator ==(int left, ItemTemplateID right) { return left == right._value; } /// <summary> /// Implements operator !=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are not equal.</returns> public static bool operator !=(int left, ItemTemplateID right) { return left != right._value; } /// <summary> /// Casts a ItemTemplateID to an Int32. /// </summary> /// <param name="ItemTemplateID">ItemTemplateID to cast.</param> /// <returns>The Int32.</returns> public static explicit operator int(ItemTemplateID ItemTemplateID) { return ItemTemplateID._value; } /// <summary> /// Casts an Int32 to a ItemTemplateID. /// </summary> /// <param name="value">Int32 to cast.</param> /// <returns>The ItemTemplateID.</returns> public static explicit operator ItemTemplateID(int value) { return new ItemTemplateID(value); } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than the right.</returns> public static bool operator >(int left, ItemTemplateID right) { return left > right._value; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than the left.</returns> public static bool operator <(int left, ItemTemplateID right) { return left < right._value; } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than the right.</returns> public static bool operator >(ItemTemplateID left, ItemTemplateID right) { return left._value > right._value; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than the left.</returns> public static bool operator <(ItemTemplateID left, ItemTemplateID right) { return left._value < right._value; } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than the right.</returns> public static bool operator >(ItemTemplateID left, int right) { return left._value > right; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than the left.</returns> public static bool operator <(ItemTemplateID left, int right) { return left._value < right; } /// <summary> /// Implements the operator &gt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than or equal to the right.</returns> public static bool operator >=(int left, ItemTemplateID right) { return left >= right._value; } /// <summary> /// Implements the operator &lt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than or equal to the left.</returns> public static bool operator <=(int left, ItemTemplateID right) { return left <= right._value; } /// <summary> /// Implements the operator &gt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than or equal to the right.</returns> public static bool operator >=(ItemTemplateID left, int right) { return left._value >= right; } /// <summary> /// Implements the operator &lt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than or equal to the left.</returns> public static bool operator <=(ItemTemplateID left, int right) { return left._value <= right; } /// <summary> /// Implements the operator &gt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than or equal to the right.</returns> public static bool operator >=(ItemTemplateID left, ItemTemplateID right) { return left._value >= right._value; } /// <summary> /// Implements the operator &lt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than or equal to the left.</returns> public static bool operator <=(ItemTemplateID left, ItemTemplateID right) { return left._value <= right._value; } /// <summary> /// Implements operator !=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are not equal.</returns> public static bool operator !=(ItemTemplateID left, ItemTemplateID right) { return left._value != right._value; } /// <summary> /// Implements operator ==. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are equal.</returns> public static bool operator ==(ItemTemplateID left, ItemTemplateID right) { return left._value == right._value; } } /// <summary> /// Adds extensions to some data I/O objects for performing Read and Write operations for the ItemTemplateID. /// All of the operations are implemented in the ItemTemplateID struct. These extensions are provided /// purely for the convenience of accessing all the I/O operations from the same place. /// </summary> public static class ItemTemplateIDReadWriteExtensions { /// <summary> /// Gets the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type ItemTemplateID. /// </summary> /// <typeparam name="T">The key Type.</typeparam> /// <param name="dict">The IDictionary.</param> /// <param name="key">The key for the value to get.</param> /// <returns>The value at the given <paramref name="key"/> parsed as a ItemTemplateID.</returns> public static ItemTemplateID AsItemTemplateID<T>(this IDictionary<T, string> dict, T key) { return Parser.Invariant.ParseItemTemplateID(dict[key]); } /// <summary> /// Tries to get the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type ItemTemplateID. /// </summary> /// <typeparam name="T">The key Type.</typeparam> /// <param name="dict">The IDictionary.</param> /// <param name="key">The key for the value to get.</param> /// <param name="defaultValue">The value to use if the value at the <paramref name="key"/> could not be parsed.</param> /// <returns>The value at the given <paramref name="key"/> parsed as an int, or the /// <paramref name="defaultValue"/> if the <paramref name="key"/> did not exist in the <paramref name="dict"/> /// or the value at the given <paramref name="key"/> could not be parsed.</returns> public static ItemTemplateID AsItemTemplateID<T>(this IDictionary<T, string> dict, T key, ItemTemplateID defaultValue) { string value; if (!dict.TryGetValue(key, out value)) return defaultValue; ItemTemplateID parsed; if (!Parser.Invariant.TryParse(value, out parsed)) return defaultValue; return parsed; } /// <summary> /// Reads the ItemTemplateID from an <see cref="IDataRecord"/>. /// </summary> /// <param name="r"><see cref="IDataRecord"/> to read the ItemTemplateID from.</param> /// <param name="i">The field index to read.</param> /// <returns>The ItemTemplateID read from the <see cref="IDataRecord"/>.</returns> public static ItemTemplateID GetItemTemplateID(this IDataRecord r, int i) { return ItemTemplateID.Read(r, i); } /// <summary> /// Reads the ItemTemplateID from an <see cref="IDataRecord"/>. /// </summary> /// <param name="r"><see cref="IDataRecord"/> to read the ItemTemplateID from.</param> /// <param name="name">The name of the field to read the value from.</param> /// <returns>The ItemTemplateID read from the <see cref="IDataRecord"/>.</returns> public static ItemTemplateID GetItemTemplateID(this IDataRecord r, string name) { return ItemTemplateID.Read(r, name); } /// <summary> /// Parses the ItemTemplateID from a string. /// </summary> /// <param name="parser">The Parser to use.</param> /// <param name="value">The string to parse.</param> /// <returns>The ItemTemplateID parsed from the string.</returns> public static ItemTemplateID ParseItemTemplateID(this Parser parser, string value) { return new ItemTemplateID(parser.ParseInt(value)); } /// <summary> /// Reads the ItemTemplateID from a BitStream. /// </summary> /// <param name="bitStream">BitStream to read the ItemTemplateID from.</param> /// <returns>The ItemTemplateID read from the BitStream.</returns> public static ItemTemplateID ReadItemTemplateID(this BitStream bitStream) { return ItemTemplateID.Read(bitStream); } /// <summary> /// Reads the ItemTemplateID from an IValueReader. /// </summary> /// <param name="valueReader">IValueReader to read the ItemTemplateID from.</param> /// <param name="name">The unique name of the value to read.</param> /// <returns>The ItemTemplateID read from the IValueReader.</returns> public static ItemTemplateID ReadItemTemplateID(this IValueReader valueReader, string name) { return ItemTemplateID.Read(valueReader, name); } /// <summary> /// Tries to parse the ItemTemplateID from a string. /// </summary> /// <param name="parser">The Parser to use.</param> /// <param name="value">The string to parse.</param> /// <param name="outValue">If this method returns true, contains the parsed ItemTemplateID.</param> /// <returns>True if the parsing was successfully; otherwise false.</returns> public static bool TryParse(this Parser parser, string value, out ItemTemplateID outValue) { int tmp; var ret = parser.TryParse(value, out tmp); outValue = new ItemTemplateID(tmp); return ret; } /// <summary> /// Writes a ItemTemplateID to a BitStream. /// </summary> /// <param name="bitStream">BitStream to write to.</param> /// <param name="value">ItemTemplateID to write.</param> public static void Write(this BitStream bitStream, ItemTemplateID value) { value.Write(bitStream); } /// <summary> /// Writes a ItemTemplateID to a IValueWriter. /// </summary> /// <param name="valueWriter">IValueWriter to write to.</param> /// <param name="name">Unique name of the ItemTemplateID that will be used to distinguish it /// from other values when reading.</param> /// <param name="value">ItemTemplateID to write.</param> public static void Write(this IValueWriter valueWriter, string name, ItemTemplateID value) { value.Write(valueWriter, name); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.Dnx.Runtime.Common.CommandLine; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ProjectModel; using Microsoft.Extensions.PlatformAbstractions; using NuGet.Frameworks; // This class is responsible with defining the arguments for the Compile verb. // It knows how to interpret them and set default values namespace Microsoft.DotNet.Tools.Compiler { public delegate bool OnExecute(List<ProjectContext> contexts, CompilerCommandApp compilerCommand); public class CompilerCommandApp { private readonly CommandLineApplication _app; // options and arguments for compilation private CommandOption _outputOption; private CommandOption _buildBasePath; private CommandOption _frameworkOption; private CommandOption _runtimeOption; private CommandOption _versionSuffixOption; private CommandOption _configurationOption; private CommandArgument _projectArgument; private CommandOption _nativeOption; private CommandOption _archOption; private CommandOption _ilcArgsOption; private CommandOption _ilcPathOption; private CommandOption _ilcSdkPathOption; private CommandOption _appDepSdkPathOption; private CommandOption _cppModeOption; private CommandOption _cppCompilerFlagsOption; // resolved values for the options and arguments public string ProjectPathValue { get; set; } public string BuildBasePathValue { get; set; } public string RuntimeValue { get; set; } public string OutputValue { get; set; } public string VersionSuffixValue { get; set; } public string ConfigValue { get; set; } public bool IsNativeValue { get; set; } public string ArchValue { get; set; } public IEnumerable<string> IlcArgsValue { get; set; } public string IlcPathValue { get; set; } public string IlcSdkPathValue { get; set; } public bool IsCppModeValue { get; set; } public string AppDepSdkPathValue { get; set; } public string CppCompilerFlagsValue { get; set; } // workaround: CommandLineApplication is internal therefore I cannot make _app protected so baseclasses can add their own params private readonly Dictionary<string, CommandOption> baseClassOptions; public CompilerCommandApp(string name, string fullName, string description) { _app = new CommandLineApplication { Name = name, FullName = fullName, Description = description }; baseClassOptions = new Dictionary<string, CommandOption>(); AddCompileParameters(); } private void AddCompileParameters() { _app.HelpOption("-h|--help"); _outputOption = _app.Option("-o|--output <OUTPUT_DIR>", "Directory in which to place outputs", CommandOptionType.SingleValue); _buildBasePath = _app.Option("-b|--build-base-path <OUTPUT_DIR>", "Directory in which to place temporary outputs", CommandOptionType.SingleValue); _frameworkOption = _app.Option("-f|--framework <FRAMEWORK>", "Compile a specific framework", CommandOptionType.SingleValue); _runtimeOption = _app.Option("-r|--runtime <RUNTIME_IDENTIFIER>", "Produce runtime-specific assets for the specified runtime", CommandOptionType.SingleValue); _configurationOption = _app.Option("-c|--configuration <CONFIGURATION>", "Configuration under which to build", CommandOptionType.SingleValue); _versionSuffixOption = _app.Option("--version-suffix <VERSION_SUFFIX>", "Defines what `*` should be replaced with in version field in project.json", CommandOptionType.SingleValue); _projectArgument = _app.Argument("<PROJECT>", "The project to compile, defaults to the current directory. Can be a path to a project.json or a project directory"); // Native Args _nativeOption = _app.Option("-n|--native", "Compiles source to native machine code.", CommandOptionType.NoValue); _archOption = _app.Option("-a|--arch <ARCH>", "The architecture for which to compile. x64 only currently supported.", CommandOptionType.SingleValue); _ilcArgsOption = _app.Option("--ilcarg <ARG>", "Command line option to be passed directly to ILCompiler.", CommandOptionType.MultipleValue); _ilcPathOption = _app.Option("--ilcpath <PATH>", "Path to the folder containing custom built ILCompiler.", CommandOptionType.SingleValue); _ilcSdkPathOption = _app.Option("--ilcsdkpath <PATH>", "Path to the folder containing ILCompiler application dependencies.", CommandOptionType.SingleValue); _appDepSdkPathOption = _app.Option("--appdepsdkpath <PATH>", "Path to the folder containing ILCompiler application dependencies.", CommandOptionType.SingleValue); _cppModeOption = _app.Option("--cpp", "Flag to do native compilation with C++ code generator.", CommandOptionType.NoValue); _cppCompilerFlagsOption = _app.Option("--cppcompilerflags <flags>", "Additional flags to be passed to the native compiler.", CommandOptionType.SingleValue); } public int Execute(OnExecute execute, string[] args) { _app.OnExecute(() => { if (_outputOption.HasValue() && !_frameworkOption.HasValue()) { Reporter.Error.WriteLine("When the '--output' option is provided, the '--framework' option must also be provided."); return 1; } // Locate the project and get the name and full path ProjectPathValue = _projectArgument.Value; if (string.IsNullOrEmpty(ProjectPathValue)) { ProjectPathValue = Directory.GetCurrentDirectory(); } OutputValue = _outputOption.Value(); BuildBasePathValue = _buildBasePath.Value(); ConfigValue = _configurationOption.Value() ?? Constants.DefaultConfiguration; RuntimeValue = _runtimeOption.Value(); VersionSuffixValue = _versionSuffixOption.Value(); IsNativeValue = _nativeOption.HasValue(); ArchValue = _archOption.Value(); IlcArgsValue = _ilcArgsOption.HasValue() ? _ilcArgsOption.Values : Enumerable.Empty<string>(); IlcPathValue = _ilcPathOption.Value(); IlcSdkPathValue = _ilcSdkPathOption.Value(); AppDepSdkPathValue = _appDepSdkPathOption.Value(); IsCppModeValue = _cppModeOption.HasValue(); CppCompilerFlagsValue = _cppCompilerFlagsOption.Value(); // Set defaults based on the environment var settings = ProjectReaderSettings.ReadFromEnvironment(); if (!string.IsNullOrEmpty(VersionSuffixValue)) { settings.VersionSuffix = VersionSuffixValue; } // Load the project file and construct all the targets var targets = ProjectContext.CreateContextForEachFramework(ProjectPathValue, settings).ToList(); if (targets.Count == 0) { // Project is missing 'frameworks' section Reporter.Error.WriteLine("Project does not have any frameworks listed in the 'frameworks' section."); return 1; } // Filter the targets down based on the inputs if (_frameworkOption.HasValue()) { var fx = NuGetFramework.Parse(_frameworkOption.Value()); targets = targets.Where(t => fx.Equals(t.TargetFramework)).ToList(); if (targets.Count == 0) { // We filtered everything out Reporter.Error.WriteLine($"Project does not support framework: {fx.DotNetFrameworkName}."); return 1; } Debug.Assert(targets.Count == 1); } Debug.Assert(targets.All(t => string.IsNullOrEmpty(t.RuntimeIdentifier))); var success = execute(targets, this); return success ? 0 : 1; }); return _app.Execute(args); } public CompilerCommandApp ShallowCopy() { return (CompilerCommandApp)MemberwiseClone(); } // CommandOptionType is internal. Cannot pass it as argument. Therefore the method name encodes the option type. protected void AddNoValueOption(string optionTemplate, string descriptino) { baseClassOptions[optionTemplate] = _app.Option(optionTemplate, descriptino, CommandOptionType.NoValue); } protected bool OptionHasValue(string optionTemplate) { CommandOption option; return baseClassOptions.TryGetValue(optionTemplate, out option) && option.HasValue(); } public IEnumerable<string> GetRuntimes() { var rids = new List<string>(); if (string.IsNullOrEmpty(RuntimeValue)) { return PlatformServices.Default.Runtime.GetAllCandidateRuntimeIdentifiers(); } else { return new[] { RuntimeValue }; } } } }
// Copyright (C) 2014 dot42 // // Original filename: Path.cs // // 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.Text; using Dot42; using JFile = Java.Io.File; namespace System.IO { public static class Path { /// <summary> /// Separator character used to separate path strings in environment variables. /// </summary> [DexImport("java/io/File", "pathSeparatorChar", "C")] public static readonly char PathSeparator; /// <summary> /// Separator character used to separate directory levels in a full path. /// </summary> [DexImport("java/io/File", "separatorChar", "C")] public static readonly char DirectorySeparatorChar; /// <summary> /// Provides a platform-specific volume separator character. /// </summary> public const char VolumeSeparatorChar = '/'; /// <summary> /// Gets all characters that are not allowed in a path name. /// </summary> [ObsoleteAttribute("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] public static readonly char[] InvalidPathChars = GetInvalidPathChars(); /// <summary> /// Change the extension of the given path. /// </summary> public static string ChangeExtension(string path, string extension) { if (string.IsNullOrEmpty(path)) return path; var index = GetExtensionIndex(path); if (extension == null) { // Remove extension return (index < 0) ? path : path.JavaSubstring(0, index); } // Replace extension var stripped = (index < 0) ? path + '.' : path.JavaSubstring(0, index + 1); if (extension.Length == 0) return stripped; if (extension[0] == '.') extension = extension.JavaSubstring(1); return stripped + extension; } /// <summary> /// Combine the given elements into a path. /// </summary> public static string Combine(string part1, string part2) { if (part1 == null) throw new ArgumentNullException("part1"); if (part2 == null) throw new ArgumentNullException("part2"); if (part1.Length == 0) return part2; if (part2.Length == 0) return part1; return new JFile(part1, part2).GetPath(); } /// <summary> /// Gets the parent of the specified path. /// </summary> public static string GetDirectoryName(string path) { return new JFile(path).GetParent(); } /// <summary> /// Gets the enxtesion of the given path. /// </summary> /// <returns>The extension of the given path including the period. If path is null, null is returned. If path does not have an extension, an empty string is returned.</returns> public static string GetExtension(string path) { if (path == null) return null; var index = GetExtensionIndex(path); return (index >= 0) ? path.JavaSubstring(index) : string.Empty; } /// <summary> /// Find the index of the start of the extension ('.') in the given path. /// </summary> private static int GetExtensionIndex(string path) { if (path == null) return -1; var index = path.Length - 1; while (index >= 0) { var ch = path[index]; if (ch == '.') return index; if (ch == DirectorySeparatorChar) return -1; index--; } return -1; } /// <summary> /// Gets the file name and extension part of the specified path. /// </summary> public static string GetFileName(string path) { return new JFile(path).GetName(); } /// <summary> /// Gets the file name part (without extension) of the specified path. /// </summary> public static string GetFileNameWithoutExtension(string path) { var name = new JFile(path).GetName(); var index = GetExtensionIndex(name); return (index >= 0) ? name.JavaSubstring(0, index) : name; } /// <summary> /// Gets the absolute path for the given path. /// </summary> public static string GetFullPath(string path) { return new JFile(path).GetAbsolutePath(); } /// <summary> /// Gets all characters that are not allowed in a file name. /// </summary> public static char[] GetInvalidFileNameChars() { return new[] { '\0', '/' }; } /// <summary> /// Gets all characters that are not allowed in a path name. /// </summary> public static char[] GetInvalidPathChars() { return new[] { '\0' }; } /// <summary> /// Gets the root directory of the specified path. /// </summary> public static string GetPathRoot(string path) { if (path == null) return null; return string.Empty; } /// <summary> /// Gets a random directory of file name. /// </summary> public static string GetRandomFileName() { const int length = 11; var rnd = new Random(); var bytes = new byte[length]; rnd.NextBytes(bytes); var sb = new StringBuilder(length + 1); for (var i = 0; i < length; i++) { if (i == 8) sb.Append('.'); var x = bytes[i] % 36; char c = (char)(x < 26 ? (x + 'a') : (x - 26 + '0')); sb.Append(c); } return sb.ToString(); } /// <summary> /// Create a unique named zero-byte length temporary file on disk and returns it's path. /// </summary> public static string GetTempFileName() { var rndName = GetRandomFileName(); var index = rndName.IndexOf('.'); return JFile.CreateTempFile(rndName.JavaSubstring(0, index), rndName.JavaSubstring(index)).GetAbsolutePath(); } /// <summary> /// Returns the path of the current users temporary folder. /// </summary> public static string GetTempPath() { return Java.Lang.System.GetProperty("java.io.tmpdir"); } /// <summary> /// Does the given path have an extension? /// </summary> public static bool HasExtension(string path) { return (GetExtensionIndex(path) >= 0); } /// <summary> /// Does the given path contain a filesystem root? /// </summary> public static bool IsPathRooted(string path) { if ((path == null) || (path.Length == 0)) return false; return (path[0] == DirectorySeparatorChar); } } }
using SmartQuant.FinChart.Objects; using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; #if GTK using Compatibility.Gtk; #else using System.Windows.Forms; #endif namespace SmartQuant.FinChart { public enum ChartUpdateStyle { WholeRange, Trailing, Fixed, } public enum EGridSize : long { sec1 = TimeSpan.TicksPerSecond, sec2 = 2 * sec1, sec5 = 5 * sec1, sec10 = 10 * sec1, sec20 = 20 * sec1, sec30 = 30 * sec1, min1 = TimeSpan.TicksPerMinute, min2 = 2 * min1, min5 = 5 * min1, min10 = 10 * min1, min15 = 15 * min1, min20 = 20 * min1, min30 = 30 * min1, hour1 = TimeSpan.TicksPerHour, hour2 = 2 * hour1, hour3 = 3 * hour1, hour4 = 4 * hour1, hour6 = 6 * hour1, hour12 = 12 * hour1, day1 = TimeSpan.TicksPerDay, day2 = 2 * day1, day3 = 3 * day1, day5 = 5 * day1, week1 = 7 * day1, week2 = 14 * day1, month1 = 30 * day1, month2 = 60 * day1, month3 = 90 * day1, month4 = 120 * day1, month6 = 180 * day1, year1 = 365 * 3 * day1, year2 = 2 * year1, year3 = 3 * year1, year4 = 4 * year1, year5 = 5 * year1, year10 = 10 * year1, year20 = 20 * year1, } public enum ChartActionType { Cross, None } enum ChartCursorType { Default, VSplitter, Hand, Cross } public enum BSStyle { Candle, Bar, Line, Kagi, Ranko, LineBreak, PointAndFigure } public class Distance { public double DX { get; set; } public double DY { get; set; } public double X { get; set; } public double Y { get; set; } public string ToolTipText { get; set; } public Distance() { DX = DY = double.MaxValue; ToolTipText = null; } } public partial class Chart { private int prevMouseX = -1; private int prevMouseY = -1; protected SmoothingMode TimeSeriesSmoothingMode = SmoothingMode.HighSpeed; protected PadList pads = new PadList(); protected int minCountOfBars = 125; protected int canvasLeftOffset = 20; protected int canvasTopOffset = 20; protected int canvasRightOffset = 20; protected int canvasBottomOffset = 30; protected Color canvasColor = Color.MidnightBlue; protected ArrayList padsHeightArray = new ArrayList(); protected int padSplitIndex = -1; protected bool contentUpdated = true; private ChartActionType actionType = ChartActionType.None; protected ChartUpdateStyle updateStyle = ChartUpdateStyle.Trailing; protected int minAxisGap = 50; private int rightAxesFontSize = 7; private Color dateTipRectangleColor = Color.LightGray; private Color dateTipTextColor = Color.Black; private Color valTipRectangleColor = Color.LightGray; private Color valTipTextColor = Color.Black; private Color crossColor = Color.DarkGray; private Color borderColor = Color.Gray; private Color splitterColor = Color.LightGray; private Color candleUpColor = Color.Black; private Color candleDownColor = Color.Lime; private Color volumeColor = Color.SteelBlue; private Color rightAxisGridColor = Color.DimGray; private Color rightAxisTextColor = Color.LightGray; private Color rightAxisMinorTicksColor = Color.LightGray; private Color rightAxisMajorTicksColor = Color.LightGray; private Color itemTextColor = Color.LightGray; private Color selectedItemTextColor = Color.Yellow; private Color selectedFillHighlightColor = Color.LightBlue; private Color activeStopColor = Color.Yellow; private Color executedStopColor = Color.MediumSeaGreen; private Color canceledStopColor = Color.Gray; private object lockObject = new object(); private DateTime lastDate = DateTime.MaxValue; private DateTime polosaDate = DateTime.MinValue; private IContainer components; protected Color sessionGridColor; protected TimeSpan sessionStart; protected TimeSpan sessionEnd; protected bool sessionGridEnabled; protected SmoothingMode smoothingMode; protected BSStyle barSeriesStyle; protected SeriesView mainSeriesView; protected ISeries mainSeries; protected ISeries series; protected int firstIndex; protected int lastIndex; protected Graphics graphics; protected double intervalWidth; protected AxisBottom axisBottom; protected int mouseX; protected int mouseY; protected bool padSplit; protected bool isMouseOverCanvas; protected Bitmap bitmap; protected DateTime leftDateTime; protected DateTime rightDateTime; protected bool volumePadShown; protected PadScaleStyle scaleStyle; internal Font RightAxesFont; private Color chartBackColor; public bool ContextMenuEnabled { get; set; } = true; public int RightAxesFontSize { get { return this.rightAxesFontSize; } set { this.rightAxesFontSize = value; this.RightAxesFont = new Font(Font.FontFamily, this.rightAxesFontSize); } } public int LabelDigitsCount { get; set; } = 2; public Image PrimitiveDeleteImage { get; set; } public Image PrimitivePropertiesImage { get; set; } [Browsable(false)] public bool DrawItems { get; set; } [Browsable(false)] public bool VolumePadVisible { get { return this.volumePadShown; } set { if (value) ShowVolumePad(); else HideVolumePad(); } } public ChartUpdateStyle UpdateStyle { get { return this.updateStyle; } set { this.updateStyle = value; EmitUpdateStyleChanged(); } } public BSStyle BarSeriesStyle { get { return this.barSeriesStyle; } set { this.DrawItems = true; if (this.barSeriesStyle == value) return; lock (this.lockObject) { this.barSeriesStyle = value; if (this.mainSeries != null) { bool local_0 = this.SetBarSeriesStyle(this.barSeriesStyle, false); if (this.volumePadShown) { int temp_55 = local_0 ? 1 : 0; } if (local_0) { this.firstIndex = Math.Max(0, this.mainSeries.Count - this.minCountOfBars); this.lastIndex = this.mainSeries.Count - 1; if (this.mainSeries.Count == 0) this.firstIndex = -1; if (this.lastIndex >= 0) SetIndexInterval(this.firstIndex, this.lastIndex); } this.contentUpdated = true; } EmitBarSeriesStyleChanged(); Invalidate(); } } } [Category("Transformation")] [Description("")] public bool SessionGridEnabled { get { return this.sessionGridEnabled; } set { this.sessionGridEnabled = value; } } [Description("")] [Category("Transformation")] public Color SessionGridColor { get { return this.sessionGridColor; } set { this.sessionGridColor = value; } } [Description("")] [Category("Transformation")] public TimeSpan SessionStart { get { return this.sessionStart; } set { this.sessionStart = value; } } [Category("Transformation")] [Description("")] public TimeSpan SessionEnd { get { return this.sessionEnd; } set { this.sessionEnd = value; } } public double IntervalWidth => this.intervalWidth; public Graphics Graphics => this.graphics; public SmoothingMode SmoothingMode { get { return this.smoothingMode; } set { this.smoothingMode = value; } } internal ISeries Series => this.series; public ISeries MainSeries => this.mainSeries; public int FirstIndex => this.firstIndex; public int LastIndex => this.lastIndex; public int PadCount => Pads.Count; public Color CanvasColor { get { return this.canvasColor; } set { this.contentUpdated = true; this.canvasColor = value; } } public Color ChartBackColor { get { return this.chartBackColor; } set { this.contentUpdated = true; this.chartBackColor = value; } } public ChartActionType ActionType { get { return this.actionType; } set { if (this.actionType == value) return; this.actionType = value; EmitActionTypeChanged(); Invalidate(); } } public int MinNumberOfBars { get { return this.minCountOfBars; } set { this.minCountOfBars = value; } } internal bool ContentUpdated { get { return this.contentUpdated; } set { this.contentUpdated = value; } } public PadList Pads => this.pads; public Color SelectedFillHighlightColor { get { return this.selectedFillHighlightColor; } set { this.selectedFillHighlightColor = Color.FromArgb(100, value); this.contentUpdated = true; } } public Color ItemTextColor { get { return this.itemTextColor; } set { this.itemTextColor = value; this.contentUpdated = true; } } public Color SelectedItemTextColor { get { return this.selectedItemTextColor; } set { this.selectedItemTextColor = value; this.contentUpdated = true; } } public Color BottomAxisGridColor { get { return this.axisBottom.GridColor; } set { this.contentUpdated = true; this.axisBottom.GridColor = value; } } public Color BottomAxisLabelColor { get { return this.axisBottom.LabelColor; } set { this.contentUpdated = true; this.axisBottom.LabelColor = value; } } public Color RightAxisGridColor { get { return this.rightAxisGridColor; } set { this.contentUpdated = true; foreach (Pad pad in this.pads) pad.Axis.GridColor = value; this.rightAxisGridColor = value; } } public Color RightAxisTextColor { get { return this.rightAxisTextColor; } set { this.contentUpdated = true; foreach (Pad pad in this.pads) pad.Axis.LabelColor = value; this.rightAxisTextColor = value; } } public Color RightAxisMinorTicksColor { get { return this.rightAxisMinorTicksColor; } set { this.contentUpdated = true; foreach (Pad pad in this.pads) pad.Axis.MinorTicksColor = value; this.rightAxisMinorTicksColor = value; } } public Color RightAxisMajorTicksColor { get { return this.rightAxisMajorTicksColor; } set { this.contentUpdated = true; foreach (Pad pad in this.pads) pad.Axis.MajorTicksColor = value; this.rightAxisMajorTicksColor = value; } } public Color DateTipRectangleColor { get { return this.dateTipRectangleColor; } set { this.contentUpdated = true; this.dateTipRectangleColor = value; } } public Color DateTipTextColor { get { return this.dateTipTextColor; } set { this.contentUpdated = true; this.dateTipTextColor = value; } } public Color ValTipRectangleColor { get { return this.valTipRectangleColor; } set { this.contentUpdated = true; this.valTipRectangleColor = value; } } public Color ValTipTextColor { get { return this.valTipTextColor; } set { this.contentUpdated = true; this.valTipTextColor = value; } } public Color CrossColor { get { return this.crossColor; } set { this.contentUpdated = true; this.crossColor = value; } } public Color BorderColor { get { return this.borderColor; } set { this.contentUpdated = true; this.borderColor = value; } } public Color SplitterColor { get { return this.splitterColor; } set { this.contentUpdated = true; this.splitterColor = value; } } public PadScaleStyle ScaleStyle { get { return this.scaleStyle; } set { this.scaleStyle = value; this.pads[0].ScaleStyle = value; this.contentUpdated = true; Invalidate(); EmitScaleStyleChanged(); } } public event EventHandler UpdateStyleChanged; public event EventHandler VolumeVisibleChanged; public event EventHandler ActionTypeChanged; public event EventHandler BarSeriesStyleChanged; public event EventHandler ScaleStyleChanged; public Chart() { InitializeComponent(); RightAxesFont = new Font(Font.FontFamily, this.rightAxesFontSize); this.canvasLeftOffset = 10; this.canvasTopOffset = 10; this.canvasRightOffset = 40; this.canvasBottomOffset = 40; AddPad(); this.axisBottom = new AxisBottom(this, this.canvasLeftOffset, this.Width - this.canvasRightOffset, this.Height - this.canvasTopOffset); this.chartBackColor = Color.MidnightBlue; this.firstIndex = -1; this.lastIndex = -1; } public Chart(TimeSeries mainSeries) : this() { SetMainSeries(mainSeries); } protected override void Dispose(bool disposing) { if (disposing) this.components?.Dispose(); base.Dispose(disposing); } internal void DrawVerticalTick(Pen Pen, long x, int length) { this.graphics.DrawLine(Pen, this.ClientX(new DateTime(x)), this.canvasTopOffset + this.Height - (this.canvasBottomOffset + this.canvasTopOffset), this.ClientX(new DateTime(x)), this.canvasTopOffset + this.Height - (this.canvasBottomOffset + this.canvasTopOffset) + length); } internal void DrawVerticalGrid(Pen pen, long x) { int x1 = ClientX(new DateTime(x)); this.graphics.DrawLine(pen, x1, this.canvasTopOffset, x1, this.canvasTopOffset + this.Height - (this.canvasBottomOffset + this.canvasTopOffset)); } internal void DrawSessionGrid(Pen pen, long x) { this.graphics.DrawLine(pen, (int)((double)ClientX(new DateTime(x)) - this.intervalWidth / 2.0), this.canvasTopOffset, (int)((double)this.ClientX(new DateTime(x)) - this.intervalWidth / 2.0), this.canvasTopOffset + this.Height - (this.canvasBottomOffset + this.canvasTopOffset)); } public void DrawSeries(TimeSeries series, int padNumber, Color color) { DrawSeries(series, padNumber, color, SearchOption.ExactFirst); } public void DrawSeries(TimeSeries series, int padNumber, Color color, SearchOption option) { lock (this.lockObject) { if (!this.volumePadShown && padNumber > 1) --padNumber; var view = new DSView(this.pads[padNumber], series, color, option, this.TimeSeriesSmoothingMode); this.pads[padNumber].AddPrimitive(view); view.SetInterval(this.leftDateTime, this.rightDateTime); this.contentUpdated = true; } } public void DrawSeries(TimeSeries series, int padNumber, Color color, SimpleDSStyle style) { DrawSeries(series, padNumber, color, style, SearchOption.ExactFirst, this.TimeSeriesSmoothingMode); } public void DrawSeries(TimeSeries series, int padNumber, Color color, SimpleDSStyle style, SmoothingMode smoothingMode) { DrawSeries(series, padNumber, color, style, SearchOption.ExactFirst, smoothingMode); } public DSView DrawSeries(TimeSeries series, int padNumber, Color color, SimpleDSStyle style, SearchOption option, SmoothingMode smoothingMode) { lock (this.lockObject) { if (!this.volumePadShown && padNumber > 1) --padNumber; DSView local_0 = new DSView(this.pads[padNumber], series, color, option, smoothingMode); local_0.Style = style; this.pads[padNumber].AddPrimitive(local_0); local_0.SetInterval(this.leftDateTime, this.rightDateTime); this.contentUpdated = true; return local_0; } } private void OnPrimitiveUpdated(object sender, EventArgs e) { this.contentUpdated = true; Invalidate(); } public void DrawFill(Fill fill, int padNumber) { lock (this.lockObject) { if (!this.volumePadShown && padNumber > 1) --padNumber; FillView view = new FillView(fill, this.pads[padNumber]); this.pads[padNumber].AddPrimitive(view); view.SetInterval(this.leftDateTime, this.rightDateTime); } } public void DrawLine(DrawingLine line, int padNumber) { lock (this.lockObject) { if (!this.volumePadShown && padNumber > 1) --padNumber; LineView local_0 = new LineView(line, this.pads[padNumber]); line.Updated += new EventHandler(this.OnPrimitiveUpdated); this.pads[padNumber].AddPrimitive((IChartDrawable)local_0); local_0.SetInterval(this.leftDateTime, this.rightDateTime); this.contentUpdated = true; } } public void DrawEllipse(DrawingEllipse circle, int padNumber) { lock (this.lockObject) { if (!this.volumePadShown && padNumber > 1) --padNumber; var view = new EllipseView(circle, this.pads[padNumber]); circle.Updated += new EventHandler(this.OnPrimitiveUpdated); this.pads[padNumber].AddPrimitive(view); view.SetInterval(this.leftDateTime, this.rightDateTime); this.contentUpdated = true; } } public void DrawRectangle(DrawingRectangle rect, int padNumber) { lock (this.lockObject) { if (!this.volumePadShown && padNumber > 1) --padNumber; var view = new RectangleView(rect, this.pads[padNumber]); rect.Updated += new EventHandler(this.OnPrimitiveUpdated); this.pads[padNumber].AddPrimitive(view); view.SetInterval(this.leftDateTime, this.rightDateTime); this.contentUpdated = true; } } public void DrawPath(DrawingPath path, int padNumber) { lock (this.lockObject) { if (!this.volumePadShown && padNumber > 1) --padNumber; PathView local_0 = new PathView(path, this.pads[padNumber]); path.Updated += new EventHandler(this.OnPrimitiveUpdated); this.pads[padNumber].AddPrimitive((IChartDrawable)local_0); local_0.SetInterval(this.leftDateTime, this.rightDateTime); this.contentUpdated = true; } } public void DrawImage(DrawingImage image, int padNumber) { lock (this.lockObject) { if (!this.volumePadShown && padNumber > 1) --padNumber; ImageView local_0 = new ImageView(image, this.pads[padNumber]); image.Updated += new EventHandler(this.OnPrimitiveUpdated); this.pads[padNumber].AddPrimitive((IChartDrawable)local_0); local_0.SetInterval(this.leftDateTime, this.rightDateTime); this.contentUpdated = true; } } protected override void OnPaint(PaintEventArgs e) { lock (this.lockObject) { try { Update(e.Graphics); if (this.firstIndex < 0 || this.lastIndex <= 0) return; #if GTK if (this.scrollbar.Adjustment.Upper != MainSeries.Count-1) this.scrollbar.Adjustment.Upper = MainSeries.Count-1; // if (this.scrollbar.Adjustment.Upper != this.mainSeries.Count - (this.lastIndex - this.firstIndex + 1) + this.scrollbar.Adjustment.PageIncrement - 1) // this.scrollbar.Adjustment.Upper = this.mainSeries.Count - (this.lastIndex - this.firstIndex + 1) + this.scrollbar.Adjustment.PageIncrement - 1; // Console.WriteLine("scrollvalue:{0} min:{1} max:{2}", this.scrollbar.Value,this.scrollbar.Adjustment.Lower,this.scrollbar.Adjustment.Upper ); if (this.scrollbar.Value == this.firstIndex) return; this.scrollbar.Value = this.firstIndex; Console.WriteLine("this.firstIndex:{0} this.lastIndex:{1}", this.firstIndex, this.lastIndex); #else if (this.scrollBar.Maximum != MainSeries.Count - (this.lastIndex - this.firstIndex + 1) + this.scrollBar.LargeChange - 1) this.scrollBar.Maximum = MainSeries.Count - (this.lastIndex - this.firstIndex + 1) + this.scrollBar.LargeChange - 1; Console.WriteLine("scrollvalue:{0} min:{1} max:{2}", this.scrollBar.Value, this.scrollBar.Minimum, this.scrollBar.Maximum); Console.WriteLine("this.firstIndex:{0} this.lastIndex:{1}", this.firstIndex, this.lastIndex); if (this.scrollBar.Value == this.firstIndex) return; this.scrollBar.Value = this.firstIndex; #endif } catch (Exception) { } } } private void Update(Graphics graphics) { if (this.lastIndex - this.firstIndex + 1 == 0) return; int num1 = Width - this.canvasLeftOffset - this.canvasRightOffset; int height = Height; this.intervalWidth = (double)(num1 / (this.lastIndex - this.firstIndex + 1)); if (this.contentUpdated) { if (this.bitmap != null) this.bitmap.Dispose(); this.bitmap = new Bitmap(Width, Height); using (var g = Graphics.FromImage(this.bitmap)) { g.SmoothingMode = SmoothingMode; g.Clear(ChartBackColor); this.graphics = g; int val1 = int.MinValue; foreach (Pad pad in this.pads) { pad.PrepareForUpdate(); val1 = Math.Max(val1, pad.AxisGap + 2); } this.canvasRightOffset = Math.Max(val1, this.minAxisGap); foreach (Pad pad in this.pads) { pad.DrawItems = DrawItems; pad.Width = Width - this.canvasRightOffset - this.canvasLeftOffset; } g.FillRectangle(new SolidBrush(this.canvasColor), this.canvasLeftOffset, this.canvasTopOffset, Width - this.canvasRightOffset - this.canvasLeftOffset, this.Height - this.canvasBottomOffset - this.canvasLeftOffset); if (this.polosaDate != DateTime.MinValue) { int num2 = this.ClientX(this.polosaDate); if (num2 > this.canvasLeftOffset && num2 < this.Width - this.canvasRightOffset) g.FillRectangle(new SolidBrush(this.selectedFillHighlightColor), (float)num2 - (float)this.intervalWidth / 2f, this.canvasTopOffset, (float)this.intervalWidth, Height - this.canvasBottomOffset - this.canvasLeftOffset); } g.DrawRectangle(new Pen(this.borderColor), this.canvasLeftOffset, this.canvasTopOffset, Width - this.canvasRightOffset - this.canvasLeftOffset, Height - this.canvasBottomOffset - this.canvasLeftOffset); if (this.mainSeries != null && this.mainSeries.Count != 0) this.axisBottom.PaintWithDates(this.mainSeries.GetDateTime(this.firstIndex), this.mainSeries.GetDateTime(this.lastIndex)); foreach (Pad pad in this.pads) pad.Update(g); for (int i = 1; i < this.pads.Count; ++i) g.DrawLine(new Pen(this.splitterColor), this.pads[i].X1, this.pads[i].Y1, this.pads[i].X2, this.pads[i].Y1); } this.contentUpdated = false; } // Draw date and value tips if (MainSeries != null && MainSeries.Count != 0 && ActionType == ChartActionType.Cross && this.isMouseOverCanvas && this.bitmap != null) { graphics.DrawImage(this.bitmap, 0, 0); graphics.SmoothingMode = SmoothingMode; graphics.DrawLine(new Pen(CrossColor, 0.5f), this.canvasLeftOffset, this.mouseY, this.mouseX - 10, this.mouseY); graphics.DrawLine(new Pen(CrossColor, 0.5f), this.mouseX + 10, this.mouseY, Width - this.canvasRightOffset, this.mouseY); graphics.DrawLine(new Pen(CrossColor, 0.5f), this.mouseX, this.canvasTopOffset, this.mouseX, this.mouseY - 10); graphics.DrawLine(new Pen(CrossColor, 0.5f), this.mouseX, this.mouseY + 10, this.mouseX, Height - this.canvasBottomOffset); string dateTip = GetDateTime(this.mouseX).ToString(); var dateTipSize = graphics.MeasureString(dateTip, this.Font); graphics.FillRectangle(new SolidBrush(DateTipRectangleColor), this.mouseX - dateTipSize.Width / 2 - 2f, Height - this.canvasBottomOffset, dateTipSize.Width, dateTipSize.Height + 2f); graphics.DrawString(dateTip, Font, new SolidBrush(DateTipTextColor), this.mouseX - dateTipSize.Width / 2 - 1f, Height - this.canvasBottomOffset + 2f); double num2 = 0.0; for (int i = 0; i < this.pads.Count; ++i) { Pad pad = this.pads[i]; if (pad.Y1 < this.mouseY && this.mouseY < pad.Y2) { num2 = pad.WorldY(this.mouseY); break; } } string valTip = num2.ToString("F" + this.LabelDigitsCount); var valTipSize = graphics.MeasureString(valTip, this.Font); graphics.FillRectangle(new SolidBrush(ValTipRectangleColor), Width - this.canvasRightOffset, this.mouseY - valTipSize.Height / 2 - 2f, valTipSize.Width, valTipSize.Height + 2f); graphics.DrawString(valTip, Font, new SolidBrush(ValTipTextColor), Width - this.canvasRightOffset + 2f, this.mouseY - valTipSize.Height / 2 - 1f); } else { if (this.bitmap != null) graphics.DrawImage(this.bitmap, 0, 0); } } protected override void OnPaintBackground(PaintEventArgs pevent) { } private void OnChartMouseDown(object sender, MouseEventArgs e) { try { if (this.isMouseOverCanvas) { foreach (Pad pad in this.pads) { if (pad.Y1 - 1 <= e.Y && e.Y <= pad.Y1 + 1) { this.padSplit = true; this.padSplitIndex = this.pads.IndexOf(pad); return; } } } foreach (Pad pad in this.pads) { if (pad.X1 <= e.X && e.X <= pad.X2 && pad.Y1 <= e.Y && e.Y <= pad.Y2) pad.MouseDown(e); } } catch { } } private void OnChartMouseUp(object sender, MouseEventArgs e) { try { if (this.padSplit) this.padSplit = false; foreach (Pad pad in this.pads) { if (pad.X1 <= e.X && e.X <= pad.X2 && pad.Y1 <= e.Y && e.Y <= pad.Y2) pad.MouseUp(e); } Invalidate(); } catch { } } private void OnChartMouseWheel(object sender, MouseEventArgs e) { if (e.Delta > 0) ZoomIn(e.Delta / 20); else ZoomOut(-e.Delta / 20); Invalidate(); } protected override void OnMouseMove(MouseEventArgs e) { try { this.mouseX = e.X; this.mouseY = e.Y; if (this.prevMouseX != this.mouseX || this.prevMouseY != this.mouseY) { if (this.canvasLeftOffset < e.X && e.X < Width - this.canvasRightOffset && this.canvasTopOffset < e.Y && e.Y < Height - this.canvasBottomOffset) { this.isMouseOverCanvas = true; if (this.actionType == ChartActionType.Cross) SetCursor(ChartCursorType.Cross); } else { this.isMouseOverCanvas = false; if (this.actionType == ChartActionType.Cross) Invalidate(); SetCursor(ChartCursorType.Default); } if (this.padSplit && this.padSplitIndex != 0) { Pad pad1 = this.pads[this.padSplitIndex]; Pad pad2 = this.pads[this.padSplitIndex - 1]; int num1 = e.Y; if (pad1.Y2 - e.Y < 20) num1 = pad1.Y2 - 20; if (e.Y - pad2.Y1 < 20) num1 = pad2.Y1 + 20; if (pad1.Y2 - num1 >= 20 && num1 - pad2.Y1 >= 20) { int num2 = pad1.Y2 - num1; int num3 = num1 - pad2.Y1; this.padsHeightArray[this.padSplitIndex] = (object)((double)num2 / (double)(this.Height - this.canvasTopOffset - this.canvasBottomOffset)); this.padsHeightArray[this.padSplitIndex - 1] = (object)((double)num3 / (double)(this.Height - this.canvasTopOffset - this.canvasBottomOffset)); pad1.SetCanvas(pad1.X1, pad1.X2, num1, pad1.Y2); pad2.SetCanvas(pad2.X1, pad2.X2, pad2.Y1, num1); } this.contentUpdated = true; Invalidate(); } foreach (Pad pad in this.pads) if (pad.Y1 - 1 <= e.Y && e.Y <= pad.Y1 + 1 && this.pads.IndexOf(pad) != 0) SetCursor(ChartCursorType.VSplitter); foreach (Pad pad in this.pads) if (pad.X1 <= e.X && e.X <= pad.X2 && pad.Y1 <= e.Y && e.Y <= pad.Y2) pad.MouseMove(e); if (this.isMouseOverCanvas && this.actionType == ChartActionType.Cross) Invalidate(); } this.prevMouseX = this.mouseX; this.prevMouseY = this.mouseY; } catch { } } private void OnChartMouseLeave(object sender, EventArgs e) { this.isMouseOverCanvas = false; Invalidate(); } protected override void OnResize(EventArgs e) { base.OnResize(e); SetPadSizes(); this.contentUpdated = true; this.axisBottom?.SetBounds(this.canvasLeftOffset, Width - this.canvasRightOffset, Height - this.canvasBottomOffset); Invalidate(); } protected override void OnKeyPress(KeyPressEventArgs e) { // no-op } private void ZoomIn(int delta) { SetIndexInterval(Math.Min(this.firstIndex + delta, this.lastIndex - 1 + 1), this.lastIndex); Invalidate(); } private void ZoomOut(int delta) { if (MainSeries == null || MainSeries.Count == 0) return; SetIndexInterval(Math.Max(0, this.firstIndex - delta), this.lastIndex); Invalidate(); } public void ZoomIn() { ZoomIn((this.lastIndex - this.firstIndex) / 5); } public void ZoomOut() { ZoomOut((this.lastIndex - this.firstIndex) / 10 + 1); } public void UnSelectAll() { foreach (var pad in Pads.Cast<Pad>().Where(p => p.SelectedPrimitive != null)) { pad.SelectedPrimitive.UnSelect(); pad.SelectedPrimitive = null; } } public virtual void ShowProperties(DSView view, Pad pad, bool forceShowProperties) { } public void AddPad() { lock (this.lockObject) { FillPadsHeightArray(); this.pads.Add(new Pad(this, this.canvasLeftOffset, this.Width - this.canvasRightOffset, this.canvasTopOffset, this.Height - this.canvasBottomOffset)); SetPadSizes(); this.contentUpdated = true; } } private void SetPadSizes() { int y1 = this.canvasTopOffset; int num1 = Height - this.canvasBottomOffset - this.canvasTopOffset; int index = 0; double num2 = 0.0; foreach (Pad pad in this.pads) { num2 += (double)this.padsHeightArray[index]; int y2 = (int)((double)this.canvasTopOffset + (double)num1 * num2); pad.SetCanvas(this.canvasLeftOffset, this.Width - this.canvasRightOffset, y1, y2); ++index; y1 = y2; } } private void FillPadsHeightArray() { if (this.padsHeightArray.Count == 0) { this.padsHeightArray.Add((object)1.0); } else { this.padsHeightArray.Add((object)0.0); int count = this.padsHeightArray.Count; if (this.volumePadShown) --count; this.padsHeightArray[0] = (object)(3.0 / (double)(count + 2)); for (int i = 1; i < this.padsHeightArray.Count; ++i) { if (this.volumePadShown && i == 1) { this.padsHeightArray[1] = (object)((double)this.padsHeightArray[0] / 6.0); this.padsHeightArray[0] = (object)((double)this.padsHeightArray[1] * 5.0); } else this.padsHeightArray[i] = (object)(1.0 / (double)(count + 2)); } } } public void ShowVolumePad() { } public void HideVolumePad() { } public int ClientX(DateTime dateTime) { double num = (double)(this.Width - this.canvasLeftOffset - this.canvasRightOffset) / (double)(this.lastIndex - this.firstIndex + 1); return this.canvasLeftOffset + (int)((double)(this.mainSeries.GetIndex(dateTime, IndexOption.Null) - this.firstIndex) * num + num / 2.0); } public DateTime GetDateTime(int x) { double num = (double)(Width - this.canvasLeftOffset - this.canvasRightOffset) / (double)(this.lastIndex - this.firstIndex + 1); return this.mainSeries.GetDateTime((int)Math.Floor((double)(x - this.canvasLeftOffset) / num) + this.firstIndex); } public void Reset() { lock (this.lockObject) { foreach (Pad pad in this.pads) { pad.Reset(); foreach (object primitive in pad.Primitives) if (primitive is IUpdatable) (primitive as IUpdatable).Updated -= OnPrimitiveUpdated; } this.pads.Clear(); this.padsHeightArray.Clear(); this.volumePadShown = false; AddPad(); this.firstIndex = -1; this.lastIndex = -1; this.mainSeries = null; this.polosaDate = DateTime.MinValue; this.contentUpdated = true; if (this.updateStyle == ChartUpdateStyle.Fixed) this.UpdateStyle = ChartUpdateStyle.Trailing; BarSeriesStyle = BSStyle.Candle; } } public void SetMainSeries(ISeries mainSeries) { SetMainSeries(mainSeries, false, Color.Black); } public void SetMainSeries(ISeries mainSeries, bool showVolumePad, Color color) { lock (this.lockObject) { ISeries temp_5 = this.mainSeries; this.series = mainSeries; if (mainSeries is BarSeries) SetBarSeriesStyle(BarSeriesStyle, true); else { this.mainSeries = this.series; this.mainSeriesView = new DSView(this.pads[0], mainSeries as TimeSeries, color, SearchOption.ExactFirst, SmoothingMode.HighSpeed); this.pads[0].AddPrimitive(this.mainSeriesView); } this.pads[0].ScaleStyle = this.scaleStyle; if (showVolumePad) this.ShowVolumePad(); this.firstIndex = this.updateStyle != ChartUpdateStyle.WholeRange ? Math.Max(0, mainSeries.Count - this.minCountOfBars) : 0; this.lastIndex = mainSeries.Count - 1; if (mainSeries.Count == 0) this.firstIndex = -1; if (this.lastIndex >= 0) SetIndexInterval(this.firstIndex, this.lastIndex); this.contentUpdated = true; Invalidate(); } } private void SetIndexInterval(int firstIndex, int lastIndex) { if (MainSeries == null || firstIndex < 0 || lastIndex > MainSeries.Count - 1) return; this.firstIndex = firstIndex; this.lastIndex = lastIndex; this.leftDateTime = firstIndex >= 0 ? MainSeries.GetDateTime(this.firstIndex) : DateTime.MaxValue; this.rightDateTime = lastIndex < 0 || lastIndex > MainSeries.Count - 1 ? DateTime.MinValue : MainSeries.GetDateTime(this.lastIndex); foreach (Pad pad in this.pads) pad.SetInterval(this.leftDateTime, this.rightDateTime); this.contentUpdated = true; } private void SetDateInterval(DateTime firstDateTime, DateTime lastDateTime) { SetIndexInterval(MainSeries.GetIndex(firstDateTime, IndexOption.Next), MainSeries.GetIndex(lastDateTime, IndexOption.Prev)); } #if GTK #else private void OnScrollBarScroll(object sender, ScrollEventArgs e) { Console.WriteLine("scrollvalue:{0} min:{1} max:{2}", e.NewValue, this.scrollBar.Minimum, this.scrollBar.Maximum); if (this.scrollBar.Value == e.NewValue) return; int delta = e.NewValue - this.scrollBar.Value; SetIndexInterval(this.firstIndex + delta, this.lastIndex + delta); Invalidate(); } #endif public void OnItemAdded() { bool flag = false; lock (this.lockObject) { this.contentUpdated = true; if (this.firstIndex == -1) this.firstIndex = 0; switch (this.updateStyle) { case ChartUpdateStyle.WholeRange: SetIndexInterval(0, MainSeries.Count - 1); flag = true; break; case ChartUpdateStyle.Trailing: if (this.lastIndex - this.firstIndex + 1 < this.minCountOfBars) SetIndexInterval(this.firstIndex, this.lastIndex + 1); else SetIndexInterval(this.firstIndex + 1, this.lastIndex + 1); flag = true; break; } } if (flag) Invalidate(); #if !GTK Application.DoEvents(); #endif } private bool SetBarSeriesStyle(BSStyle barSeriesStyle, bool force) { bool flag = true; if (barSeriesStyle == BSStyle.Candle || barSeriesStyle == BSStyle.Bar || barSeriesStyle == BSStyle.Line) { if (!(this.mainSeriesView is SimpleBSView) || force) { this.pads[0].RemovePrimitive(this.mainSeriesView); this.mainSeriesView = new SimpleBSView(this.pads[0], this.series as BarSeries); (this.mainSeriesView as SimpleBSView).UpColor = this.candleUpColor; (this.mainSeriesView as SimpleBSView).DownColor = this.candleDownColor; this.mainSeries = this.mainSeriesView.MainSeries; this.pads[0].AddPrimitive(this.mainSeriesView); } else flag = false; if (barSeriesStyle == BSStyle.Candle) (this.mainSeriesView as SimpleBSView).Style = SimpleBSStyle.Candle; if (barSeriesStyle == BSStyle.Bar) (this.mainSeriesView as SimpleBSView).Style = SimpleBSStyle.Bar; if (barSeriesStyle == BSStyle.Line) (this.mainSeriesView as SimpleBSView).Style = SimpleBSStyle.Line; } return flag; } private void EmitUpdateStyleChanged() { UpdateStyleChanged?.Invoke(this, EventArgs.Empty); } private void EmitVolumeVisibleChanged() { VolumeVisibleChanged?.Invoke(this, EventArgs.Empty); } private void EmitBarSeriesStyleChanged() { BarSeriesStyleChanged?.Invoke(this, EventArgs.Empty); } private void EmitActionTypeChanged() { ActionTypeChanged?.Invoke(this, EventArgs.Empty); } private void EmitScaleStyleChanged() { ScaleStyleChanged?.Invoke(this, EventArgs.Empty); } public void EnsureVisible(Fill fill) { if (fill.DateTime < MainSeries.FirstDateTime) return; int num = Math.Max(MainSeries.GetIndex(fill.DateTime, IndexOption.Prev), 0); int val2 = this.lastIndex - this.firstIndex + 1; int lastIndex = Math.Max(Math.Min(MainSeries.Count - 1, num + val2 / 5), val2); SetIndexInterval(lastIndex - val2 + 1, lastIndex); this.pads[0].SetSelectedObject(fill); this.polosaDate = MainSeries.GetDateTime(MainSeries.GetIndex(fill.DateTime, IndexOption.Prev)); this.contentUpdated = true; Invalidate(); } public int GetPadNumber(Point point) { for (int i = 0; i < this.pads.Count; ++i) if (this.pads[i].Y1 <= point.Y && point.Y <= this.pads[i].Y2) return i; return -1; } private delegate void SetIndexIntervalHandler(int firstIndex,int lastIndex); #region Helper Methods internal void SetCursor(ChartCursorType type) { #if GTK switch(type) { case ChartCursorType.VSplitter: GdkWindow.Cursor = UserControl.VSplitterCursor; break; case ChartCursorType.Cross: GdkWindow.Cursor = UserControl.CrossCursor; break; case ChartCursorType.Hand: GdkWindow.Cursor = UserControl.HandCursor; break; case ChartCursorType.Default: GdkWindow.Cursor = null; break; } #else switch (type) { case ChartCursorType.VSplitter: Cursor.Current = Cursors.HSplit; break; case ChartCursorType.Cross: Cursor.Current = Cursors.Cross; break; case ChartCursorType.Hand: Cursor.Current = Cursors.Hand; break; case ChartCursorType.Default: default: Cursor.Current = Cursors.Default; break; } #endif } // private void DrawUpdatableObject(IUpdatable obj, int padNumber) // { // lock (this.lockObject) // { // if (!this.volumePadShown && padNumber > 1) // --padNumber; // IChartDrawable drawable; // if (obj is DrawingImage) // drawable = new ImageView(obj, this.pads[padNumber]); // else if(obj is DrawingLine) // drawable = new LineView(obj, this.pads[padNumber]); // else if(obj is DrawingEllipse) // drawable = new EllipseView(obj, this.pads[padNumber]); // else if(obj is DrawingLine) // drawable = new LineView(obj, this.pads[padNumber]); // else if(obj is DrawingLine) // drawable = new LineView(obj, this.pads[padNumber]); // else if(obj is DrawingLine) // drawable = new LineView(obj, this.pads[padNumber]); // ImageView local_0 = new ImageView(image, this.pads[padNumber]); // image.Updated += new EventHandler(this.primitive_Updated); // this.pads[padNumber].AddPrimitive((IChartDrawable)local_0); // local_0.SetInterval(this.leftDateTime, this.rightDateTime); // this.contentUpdated = true; // } // } #endregion } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Linq; using EventStore.Core.Data; using EventStore.Core.Messaging; using EventStore.Projections.Core.Messages; using EventStore.Projections.Core.Services.Management; using NUnit.Framework; namespace EventStore.Projections.Core.Tests.Services.projections_manager.continuous { public class a_running_projection { public abstract class Base : a_new_posted_projection.Base { protected Guid _reader; protected override void Given() { base.Given(); } protected override IEnumerable<WhenStep> When() { foreach (var m in base.When()) yield return m; var readerAssignedMessage = _consumer.HandledMessages.OfType<EventReaderSubscriptionMessage.ReaderAssignedReader>().LastOrDefault(); if (_projectionEnabled) { Assert.IsNotNull(readerAssignedMessage); _reader = readerAssignedMessage.ReaderId; yield return (ReaderSubscriptionMessage.CommittedEventDistributed.Sample( _reader, new TFPos(100, 50), new TFPos(100, 50), "stream", 1, "stream", 1, false, Guid.NewGuid(), "type", false, new byte[0], new byte[0], 100, 33.3f)); } else _reader = Guid.Empty; } } [TestFixture] public class when_stopping : Base { protected override IEnumerable<WhenStep> When() { foreach (var m in base.When()) yield return m; yield return (new ProjectionManagementMessage.Disable( new PublishEnvelope(_bus), _projectionName, ProjectionManagementMessage.RunAs.System)); for (var i = 0; i < 50; i++) { yield return (ReaderSubscriptionMessage.CommittedEventDistributed.Sample( _reader, new TFPos(100*i + 200, 150), new TFPos(100*i + 200, 150), "stream", 1 + i + 1, "stream", 1 + i + 1, false, Guid.NewGuid(), "type", false, new byte[0], new byte[0], 100*i + 200, 33.3f)); } } [Test] public void pause_message_is_published() { Assert.Inconclusive("actually in unsubscribes..."); } [Test] public void unsubscribe_message_is_published() { Assert.Inconclusive("actually in unsubscribes..."); } [Test] public void the_projection_status_becomes_stopped_disabled() { _manager.Handle( new ProjectionManagementMessage.GetStatistics( new PublishEnvelope(_bus), null, _projectionName, false)); Assert.AreEqual(1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>().Count()); Assert.AreEqual( 1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Length); Assert.AreEqual( _projectionName, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Single() .Name); Assert.AreEqual( ManagedProjectionState.Stopped, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Single() .MasterStatus); Assert.AreEqual( false, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Single() .Enabled); } } [TestFixture] public class when_handling_event : Base { protected override IEnumerable<WhenStep> When() { foreach (var m in base.When()) yield return m; yield return (ReaderSubscriptionMessage.CommittedEventDistributed.Sample( _reader, new TFPos(200, 150), new TFPos(200, 150), "stream", 2, "stream", 2, false, Guid.NewGuid(), "type", false, new byte[0], new byte[0], 100, 33.3f)); } [Test] public void the_projection_status_remains_running_enabled() { _manager.Handle( new ProjectionManagementMessage.GetStatistics( new PublishEnvelope(_bus), null, _projectionName, false)); Assert.AreEqual(1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>().Count()); Assert.AreEqual( 1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Length); Assert.AreEqual( _projectionName, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Single() .Name); Assert.AreEqual( ManagedProjectionState.Running, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Single() .MasterStatus); Assert.AreEqual( true, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Single() .Enabled); } } [TestFixture] public class when_resetting : Base { protected override void Given() { base.Given(); _projectionEnabled = false; } protected override IEnumerable<WhenStep> When() { foreach (var m in base.When()) yield return m; yield return (new ProjectionManagementMessage.Reset( new PublishEnvelope(_bus), _projectionName, ProjectionManagementMessage.RunAs.System)); } [Test] public void the_projection_epoch_changes() { _manager.Handle( new ProjectionManagementMessage.GetStatistics( new PublishEnvelope(_bus), null, _projectionName, false)); Assert.AreEqual(1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>().Count()); Assert.AreEqual( 1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Length); Assert.AreEqual( 1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Single() .Epoch); Assert.AreEqual( 1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Single() .Version); } [Test] public void the_projection_status_is_enabled_running() { _manager.Handle( new ProjectionManagementMessage.GetStatistics( new PublishEnvelope(_bus), null, _projectionName, false)); Assert.AreEqual(1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>().Count()); Assert.AreEqual( 1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Length); Assert.AreEqual( ManagedProjectionState.Stopped, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Single() .MasterStatus); Assert.AreEqual( false, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Single() .Enabled); } } [TestFixture] public class when_resetting_and_starting : Base { protected override void Given() { base.Given(); _projectionEnabled = false; } protected override IEnumerable<WhenStep> When() { foreach (var m in base.When()) yield return m; yield return (new ProjectionManagementMessage.Reset( new PublishEnvelope(_bus), _projectionName, ProjectionManagementMessage.RunAs.System)); yield return (new ProjectionManagementMessage.Enable( new PublishEnvelope(_bus), _projectionName, ProjectionManagementMessage.RunAs.System)); yield return (ReaderSubscriptionMessage.CommittedEventDistributed.Sample( _reader, new TFPos(100, 150), new TFPos(100, 150), "stream", 1 + 1, "stream", 1 + 1, false, Guid.NewGuid(), "type", false, new byte[0], new byte[0], 200, 33.3f)); } [Test] public void the_projection_epoch_changes() { _manager.Handle( new ProjectionManagementMessage.GetStatistics( new PublishEnvelope(_bus), null, _projectionName, false)); Assert.AreEqual(1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>().Count()); Assert.AreEqual( 1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Length); Assert.AreEqual( 1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Single() .Epoch); Assert.AreEqual( 2, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Single() .Version); } [Test] public void the_projection_status_is_enabled_running() { _manager.Handle( new ProjectionManagementMessage.GetStatistics( new PublishEnvelope(_bus), null, _projectionName, false)); Assert.AreEqual(1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>().Count()); Assert.AreEqual( 1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Length); Assert.AreEqual( ManagedProjectionState.Running, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Single() .MasterStatus); Assert.AreEqual( true, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>() .Single() .Projections.Single() .Enabled); } } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: SampleLMAX.SampleLMAXPublic File: MainWindow.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace SampleLMAX { using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows; using Ecng.Common; using Ecng.Xaml; using MoreLinq; using StockSharp.BusinessEntities; using StockSharp.LMAX; using StockSharp.Localization; public partial class MainWindow { private bool _isConnected; public LmaxTrader Trader; private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow(); private readonly TradesWindow _tradesWindow = new TradesWindow(); private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow(); private readonly OrdersWindow _ordersWindow = new OrdersWindow(); private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow(); private readonly StopOrdersWindow _stopOrdersWindow = new StopOrdersWindow(); public MainWindow() { InitializeComponent(); Title = Title.Put("LMAX"); _ordersWindow.MakeHideable(); _myTradesWindow.MakeHideable(); _tradesWindow.MakeHideable(); _securitiesWindow.MakeHideable(); _stopOrdersWindow.MakeHideable(); _portfoliosWindow.MakeHideable(); Instance = this; } protected override void OnClosing(CancelEventArgs e) { _ordersWindow.DeleteHideable(); _myTradesWindow.DeleteHideable(); _tradesWindow.DeleteHideable(); _securitiesWindow.DeleteHideable(); _stopOrdersWindow.DeleteHideable(); _portfoliosWindow.DeleteHideable(); _securitiesWindow.Close(); _tradesWindow.Close(); _myTradesWindow.Close(); _stopOrdersWindow.Close(); _ordersWindow.Close(); _portfoliosWindow.Close(); if (Trader != null) Trader.Dispose(); base.OnClosing(e); } public static MainWindow Instance { get; private set; } private void ConnectClick(object sender, RoutedEventArgs e) { if (!_isConnected) { if (Login.Text.IsEmpty()) { MessageBox.Show(this, LocalizedStrings.Str2974); return; } else if (Password.Password.IsEmpty()) { MessageBox.Show(this, LocalizedStrings.Str2975); return; } if (Trader == null) { // create connector Trader = new LmaxTrader(); Trader.Restored += () => this.GuiAsync(() => { // update gui labes ChangeConnectStatus(true); MessageBox.Show(this, LocalizedStrings.Str2958); }); // subscribe on connection successfully event Trader.Connected += () => { // set flag (connection is established) _isConnected = true; // update gui labes this.GuiAsync(() => ChangeConnectStatus(true)); }; Trader.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false)); // subscribe on connection error event Trader.ConnectionError += error => this.GuiAsync(() => { // update gui labes ChangeConnectStatus(false); MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959); }); // subscribe on error event Trader.Error += error => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955)); // subscribe on error of market data subscription event Trader.MarketDataSubscriptionFailed += (security, msg, error) => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security))); Trader.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities); Trader.NewMyTrades += trades => _myTradesWindow.TradeGrid.Trades.AddRange(trades); Trader.NewTrades += trades => _tradesWindow.TradeGrid.Trades.AddRange(trades); Trader.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewStopOrders += orders => _stopOrdersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewPortfolios += portfolios => { // subscribe on portfolio updates portfolios.ForEach(Trader.RegisterPortfolio); _portfoliosWindow.PortfolioGrid.Portfolios.AddRange(portfolios); }; Trader.NewPositions += positions => _portfoliosWindow.PortfolioGrid.Positions.AddRange(positions); // subscribe on error of order registration event Trader.OrdersRegisterFailed += OrdersFailed; // subscribe on error of order cancelling event Trader.OrdersCancelFailed += OrdersFailed; // subscribe on error of stop-order registration event Trader.StopOrdersRegisterFailed += OrdersFailed; // subscribe on error of stop-order cancelling event Trader.StopOrdersCancelFailed += OrdersFailed; Trader.MassOrderCancelFailed += (transId, error) => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716)); // set market data provider _securitiesWindow.SecurityPicker.MarketDataProvider = Trader; ShowSecurities.IsEnabled = ShowTrades.IsEnabled = ShowMyTrades.IsEnabled = ShowOrders.IsEnabled = ShowPortfolios.IsEnabled = ShowStopOrders.IsEnabled = true; } Trader.Login = Login.Text; Trader.Password = Password.Password; Trader.IsDemo = IsDemo.IsChecked == true; // in sandbox security identifies may be different than uploaded on the site Trader.IsDownloadSecurityFromSite = !Trader.IsDemo; // clear password box for security reason //Password.Clear(); Trader.Connect(); } else { Trader.Disconnect(); } } private void OrdersFailed(IEnumerable<OrderFail> fails) { this.GuiAsync(() => { foreach (var fail in fails) MessageBox.Show(this, fail.Error.ToString(), LocalizedStrings.Str153); }); } private void ChangeConnectStatus(bool isConnected) { _isConnected = isConnected; ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect; } private void ShowSecuritiesClick(object sender, RoutedEventArgs e) { ShowOrHide(_securitiesWindow); } private void ShowTradesClick(object sender, RoutedEventArgs e) { ShowOrHide(_tradesWindow); } private void ShowMyTradesClick(object sender, RoutedEventArgs e) { ShowOrHide(_myTradesWindow); } private void ShowOrdersClick(object sender, RoutedEventArgs e) { ShowOrHide(_ordersWindow); } private void ShowPortfoliosClick(object sender, RoutedEventArgs e) { ShowOrHide(_portfoliosWindow); } private void ShowStopOrdersClick(object sender, RoutedEventArgs e) { ShowOrHide(_stopOrdersWindow); } private static void ShowOrHide(Window window) { if (window == null) throw new ArgumentNullException(nameof(window)); if (window.Visibility == Visibility.Visible) window.Hide(); else window.Show(); } } }
/* ==================================================================== 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 NPOI.HSSF.Record.CF { using System; using System.Collections; using NPOI.SS.Util; using System.Collections.Generic; /** * * @author Dmitriy Kumshayev */ public class CellRangeUtil { private CellRangeUtil() { // no instance of this class } public const int NO_INTERSECTION = 1; public const int OVERLAP = 2; /** first range is within the second range */ public const int INSIDE = 3; /** first range encloses or is equal to the second */ public const int ENCLOSES = 4; /** * Intersect this range with the specified range. * * @param crB - the specified range * @return code which reflects how the specified range is related to this range.<br/> * Possible return codes are: * NO_INTERSECTION - the specified range is outside of this range;<br/> * OVERLAP - both ranges partially overlap;<br/> * INSIDE - the specified range is inside of this one<br/> * ENCLOSES - the specified range encloses (possibly exactly the same as) this range<br/> */ public static int Intersect(CellRangeAddress crA, CellRangeAddress crB) { int firstRow = crB.FirstRow; int lastRow = crB.LastRow; int firstCol = crB.FirstColumn; int lastCol = crB.LastColumn; if ( gt(crA.FirstRow, lastRow) || lt(crA.LastRow, firstRow) || gt(crA.FirstColumn, lastCol) || lt(crA.LastColumn, firstCol) ) { return NO_INTERSECTION; } else if (Contains(crA, crB)) { return INSIDE; } else if (Contains(crB, crA)) { return ENCLOSES; } else { return OVERLAP; } } /** * Do all possible cell merges between cells of the list so that: * if a cell range is completely inside of another cell range, it s removed from the list * if two cells have a shared border, merge them into one bigger cell range * @param cellRangeList * @return updated List of cell ranges */ public static CellRangeAddress[] MergeCellRanges(CellRangeAddress[] cellRanges) { if (cellRanges.Length < 1) { return cellRanges; } //ArrayList temp = MergeCellRanges(NPOI.Util.Arrays.AsList(cellRanges)); List<CellRangeAddress> lst = new List<CellRangeAddress>(cellRanges); List<CellRangeAddress> temp = MergeCellRanges(lst); return temp.ToArray(); } private static List<CellRangeAddress> MergeCellRanges(List<CellRangeAddress> cellRangeList) { // loop until either only one item is left or we did not merge anything any more while (cellRangeList.Count > 1) { bool somethingGotMerged = false; // look at all cell-ranges for (int i = 0; i < cellRangeList.Count; i++) { CellRangeAddress range1 = cellRangeList[i]; // compare each cell range to all other cell-ranges for (int j = i + 1; j < cellRangeList.Count; j++) { CellRangeAddress range2 = cellRangeList[j]; CellRangeAddress[] mergeResult = MergeRanges(range1, range2); if (mergeResult == null) { continue; } somethingGotMerged = true; // overwrite range1 with first result cellRangeList[i] = mergeResult[0]; // remove range2 cellRangeList.RemoveAt(j--); // Add any extra results beyond the first for (int k = 1; k < mergeResult.Length; k++) { j++; cellRangeList.Insert(j, mergeResult[k]); } } } if (!somethingGotMerged) { break; } } return cellRangeList; } /** * @return the new range(s) to replace the supplied ones. <c>null</c> if no merge is possible */ private static CellRangeAddress[] MergeRanges(CellRangeAddress range1, CellRangeAddress range2) { int x = Intersect(range1, range2); switch (x) { // nothing in common: at most they could be adjacent to each other and thus form a single bigger area case CellRangeUtil.NO_INTERSECTION: if (HasExactSharedBorder(range1, range2)) { return new CellRangeAddress[] { CreateEnclosingCellRange(range1, range2), }; } // else - No intersection and no shared border: do nothing return null; case CellRangeUtil.OVERLAP: // commented out the cells overlap implementation, it caused endless loops, see Bug 55380 // disabled for now, the algorithm will not detect some border cases this way currently! //return ResolveRangeOverlap(range1, range2); return null; case CellRangeUtil.INSIDE: // Remove range2, since it is completely inside of range1 return new CellRangeAddress[] { range1 }; case CellRangeUtil.ENCLOSES: // range2 encloses range1, so replace it with the enclosing one return new CellRangeAddress[] { range2 }; } throw new InvalidOperationException("unexpected intersection result (" + x + ")"); } //// TODO - write junit test for this //static CellRangeAddress[] ResolveRangeOverlap(CellRangeAddress rangeA, CellRangeAddress rangeB) //{ // if (rangeA.IsFullColumnRange) // { // if (rangeA.IsFullRowRange) // { // // Excel seems to leave these unresolved // return null; // } // return SliceUp(rangeA, rangeB); // } // if (rangeA.IsFullRowRange) // { // if (rangeB.IsFullColumnRange) // { // // Excel seems to leave these unresolved // return null; // } // return SliceUp(rangeA, rangeB); // } // if (rangeB.IsFullColumnRange) // { // return SliceUp(rangeB, rangeA); // } // if (rangeB.IsFullRowRange) // { // return SliceUp(rangeB, rangeA); // } // return SliceUp(rangeA, rangeB); //} ///** // * @param crB never a full row or full column range // * @return an array including <b>this</b> <c>CellRange</c> and all parts of <c>range</c> // * outside of this range // */ //private static CellRangeAddress[] SliceUp(CellRangeAddress crA, CellRangeAddress crB) //{ // ArrayList temp = new ArrayList(); // // Chop up range horizontally and vertically // temp.Add(crB); // if (!crA.IsFullColumnRange) // { // temp = CutHorizontally(crA.FirstRow, temp); // temp = CutHorizontally(crA.LastRow + 1, temp); // } // if (!crA.IsFullRowRange) // { // temp = CutVertically(crA.FirstColumn, temp); // temp = CutVertically(crA.LastColumn + 1, temp); // } // CellRangeAddress[] crParts = ToArray(temp); // // form result array // temp.Clear(); // temp.Add(crA); // for (int i = 0; i < crParts.Length; i++) // { // CellRangeAddress crPart = crParts[i]; // // only include parts that are not enclosed by this // if (Intersect(crA, crPart) != ENCLOSES) // { // temp.Add(crPart); // } // } // return ToArray(temp); //} //private static ArrayList CutHorizontally(int cutRow, ArrayList input) //{ // ArrayList result = new ArrayList(); // CellRangeAddress[] crs = ToArray(input); // for (int i = 0; i < crs.Length; i++) // { // CellRangeAddress cr = crs[i]; // if (cr.FirstRow < cutRow && cutRow < cr.LastRow) // { // result.Add(new CellRangeAddress(cr.FirstRow, cutRow, cr.FirstColumn, cr.LastColumn)); // result.Add(new CellRangeAddress(cutRow + 1, cr.LastRow, cr.FirstColumn, cr.LastColumn)); // } // else // { // result.Add(cr); // } // } // return result; //} //private static ArrayList CutVertically(int cutColumn, ArrayList input) //{ // ArrayList result = new ArrayList(); // CellRangeAddress[] crs = ToArray(input); // for (int i = 0; i < crs.Length; i++) // { // CellRangeAddress cr = crs[i]; // if (cr.FirstColumn < cutColumn && cutColumn < cr.LastColumn) // { // result.Add(new CellRangeAddress(cr.FirstRow, cr.LastRow, cr.FirstColumn, cutColumn)); // result.Add(new CellRangeAddress(cr.FirstRow, cr.LastRow, cutColumn + 1, cr.LastColumn)); // } // else // { // result.Add(cr); // } // } // return result; //} private static CellRangeAddress[] ToArray(ArrayList temp) { CellRangeAddress[] result = new CellRangeAddress[temp.Count]; result = (CellRangeAddress[])temp.ToArray(typeof(CellRangeAddress)); return result; } /** * Check if the specified range is located inside of this cell range. * * @param crB * @return true if this cell range Contains the argument range inside if it's area */ public static bool Contains(CellRangeAddress crA, CellRangeAddress crB) { int firstRow = crB.FirstRow; int lastRow = crB.LastRow; int firstCol = crB.FirstColumn; int lastCol = crB.LastColumn; return le(crA.FirstRow, firstRow) && ge(crA.LastRow, lastRow) && le(crA.FirstColumn, firstCol) && ge(crA.LastColumn, lastCol); } /** * Check if the specified cell range has a shared border with the current range. * * @return <c>true</c> if the ranges have a complete shared border (i.e. * the two ranges toher make a simple rectangular region. */ public static bool HasExactSharedBorder(CellRangeAddress crA, CellRangeAddress crB) { int oFirstRow = crB.FirstRow; int oLastRow = crB.LastRow; int oFirstCol = crB.FirstColumn; int oLastCol = crB.LastColumn; if (crA.FirstRow > 0 && crA.FirstRow - 1 == oLastRow || oFirstRow > 0 && oFirstRow - 1 == crA.LastRow) { // ranges have a horizontal border in common // make sure columns are identical: return crA.FirstColumn == oFirstCol && crA.LastColumn == oLastCol; } if (crA.FirstColumn > 0 && crA.FirstColumn - 1 == oLastCol || oFirstCol > 0 && crA.LastColumn == oFirstCol - 1) { // ranges have a vertical border in common // make sure rows are identical: return crA.FirstRow == oFirstRow && crA.LastRow == oLastRow; } return false; } /** * Create an enclosing CellRange for the two cell ranges. * * @return enclosing CellRange */ public static CellRangeAddress CreateEnclosingCellRange(CellRangeAddress crA, CellRangeAddress crB) { if (crB == null) { return crA.Copy(); } return new CellRangeAddress( lt(crB.FirstRow, crA.FirstRow) ? crB.FirstRow : crA.FirstRow, gt(crB.LastRow, crA.LastRow) ? crB.LastRow : crA.LastRow, lt(crB.FirstColumn, crA.FirstColumn) ? crB.FirstColumn : crA.FirstColumn, gt(crB.LastColumn, crA.LastColumn) ? crB.LastColumn : crA.LastColumn ); } /** * @return true if a &lt; b */ private static bool lt(int a, int b) { return a == -1 ? false : (b == -1 ? true : a < b); } /** * @return true if a &lt;= b */ private static bool le(int a, int b) { return a == b || lt(a, b); } /** * @return true if a > b */ private static bool gt(int a, int b) { return lt(b, a); } /** * @return true if a >= b */ private static bool ge(int a, int b) { return !lt(a, b); } } }
using J2N.Collections.Generic.Extensions; using Lucene.Net.Diagnostics; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Search; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Analyzer = Lucene.Net.Analysis.Analyzer; using BytesRef = Lucene.Net.Util.BytesRef; using CannedTokenStream = Lucene.Net.Analysis.CannedTokenStream; using Directory = Lucene.Net.Store.Directory; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using Document = Documents.Document; using English = Lucene.Net.Util.English; using Field = Field; using FieldType = FieldType; using Int32Field = Int32Field; using IOUtils = Lucene.Net.Util.IOUtils; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockPayloadAnalyzer = Lucene.Net.Analysis.MockPayloadAnalyzer; using StringField = StringField; using TestUtil = Lucene.Net.Util.TestUtil; using TextField = TextField; using Token = Lucene.Net.Analysis.Token; using TokenStream = Lucene.Net.Analysis.TokenStream; // TODO: we really need to test indexingoffsets, but then getting only docs / docs + freqs. // not all codecs store prx separate... // TODO: fix sep codec to index offsets so we can greatly reduce this list! [SuppressCodecs("Lucene3x", "MockFixedIntBlock", "MockVariableIntBlock", "MockSep", "MockRandom")] [TestFixture] public class TestPostingsOffsets : LuceneTestCase { private IndexWriterConfig iwc; [SetUp] public override void SetUp() { base.SetUp(); iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); } [Test] public virtual void TestBasic() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, dir, iwc); Document doc = new Document(); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); ft.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; if (Random.NextBoolean()) { ft.StoreTermVectors = true; ft.StoreTermVectorPositions = Random.NextBoolean(); ft.StoreTermVectorOffsets = Random.NextBoolean(); } Token[] tokens = new Token[] { MakeToken("a", 1, 0, 6), MakeToken("b", 1, 8, 9), MakeToken("a", 1, 9, 17), MakeToken("c", 1, 19, 50) }; doc.Add(new Field("content", new CannedTokenStream(tokens), ft)); w.AddDocument(doc); IndexReader r = w.GetReader(); w.Dispose(); DocsAndPositionsEnum dp = MultiFields.GetTermPositionsEnum(r, null, "content", new BytesRef("a")); Assert.IsNotNull(dp); Assert.AreEqual(0, dp.NextDoc()); Assert.AreEqual(2, dp.Freq); Assert.AreEqual(0, dp.NextPosition()); Assert.AreEqual(0, dp.StartOffset); Assert.AreEqual(6, dp.EndOffset); Assert.AreEqual(2, dp.NextPosition()); Assert.AreEqual(9, dp.StartOffset); Assert.AreEqual(17, dp.EndOffset); Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dp.NextDoc()); dp = MultiFields.GetTermPositionsEnum(r, null, "content", new BytesRef("b")); Assert.IsNotNull(dp); Assert.AreEqual(0, dp.NextDoc()); Assert.AreEqual(1, dp.Freq); Assert.AreEqual(1, dp.NextPosition()); Assert.AreEqual(8, dp.StartOffset); Assert.AreEqual(9, dp.EndOffset); Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dp.NextDoc()); dp = MultiFields.GetTermPositionsEnum(r, null, "content", new BytesRef("c")); Assert.IsNotNull(dp); Assert.AreEqual(0, dp.NextDoc()); Assert.AreEqual(1, dp.Freq); Assert.AreEqual(3, dp.NextPosition()); Assert.AreEqual(19, dp.StartOffset); Assert.AreEqual(50, dp.EndOffset); Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dp.NextDoc()); r.Dispose(); dir.Dispose(); } [Test] public virtual void TestSkipping() { DoTestNumbers(false); } [Test] public virtual void TestPayloads() { DoTestNumbers(true); } public virtual void DoTestNumbers(bool withPayloads) { Directory dir = NewDirectory(); Analyzer analyzer = withPayloads ? (Analyzer)new MockPayloadAnalyzer() : new MockAnalyzer(Random); iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer); iwc.SetMergePolicy(NewLogMergePolicy()); // will rely on docids a bit for skipping RandomIndexWriter w = new RandomIndexWriter(Random, dir, iwc); FieldType ft = new FieldType(TextField.TYPE_STORED); ft.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; if (Random.NextBoolean()) { ft.StoreTermVectors = true; ft.StoreTermVectorOffsets = Random.NextBoolean(); ft.StoreTermVectorPositions = Random.NextBoolean(); } int numDocs = AtLeast(500); for (int i = 0; i < numDocs; i++) { Document doc = new Document(); doc.Add(new Field("numbers", English.Int32ToEnglish(i), ft)); doc.Add(new Field("oddeven", (i % 2) == 0 ? "even" : "odd", ft)); doc.Add(new StringField("id", "" + i, Field.Store.NO)); w.AddDocument(doc); } IndexReader reader = w.GetReader(); w.Dispose(); string[] terms = new string[] { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "hundred" }; foreach (string term in terms) { DocsAndPositionsEnum dp = MultiFields.GetTermPositionsEnum(reader, null, "numbers", new BytesRef(term)); int doc; while ((doc = dp.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { string storedNumbers = reader.Document(doc).Get("numbers"); int freq = dp.Freq; for (int i = 0; i < freq; i++) { dp.NextPosition(); int start = dp.StartOffset; if (Debugging.AssertsEnabled) Debugging.Assert(start >= 0); int end = dp.EndOffset; if (Debugging.AssertsEnabled) Debugging.Assert(end >= 0 && end >= start); // check that the offsets correspond to the term in the src text Assert.IsTrue(storedNumbers.Substring(start, end - start).Equals(term, StringComparison.Ordinal)); if (withPayloads) { // check that we have a payload and it starts with "pos" Assert.IsNotNull(dp.GetPayload()); BytesRef payload = dp.GetPayload(); Assert.IsTrue(payload.Utf8ToString().StartsWith("pos:", StringComparison.Ordinal)); } // note: withPayloads=false doesnt necessarily mean we dont have them from MockAnalyzer! } } } // check we can skip correctly int numSkippingTests = AtLeast(50); for (int j = 0; j < numSkippingTests; j++) { int num = TestUtil.NextInt32(Random, 100, Math.Min(numDocs - 1, 999)); DocsAndPositionsEnum dp = MultiFields.GetTermPositionsEnum(reader, null, "numbers", new BytesRef("hundred")); int doc = dp.Advance(num); Assert.AreEqual(num, doc); int freq = dp.Freq; for (int i = 0; i < freq; i++) { string storedNumbers = reader.Document(doc).Get("numbers"); dp.NextPosition(); int start = dp.StartOffset; if (Debugging.AssertsEnabled) Debugging.Assert(start >= 0); int end = dp.EndOffset; if (Debugging.AssertsEnabled) Debugging.Assert(end >= 0 && end >= start); // check that the offsets correspond to the term in the src text Assert.IsTrue(storedNumbers.Substring(start, end - start).Equals("hundred", StringComparison.Ordinal)); if (withPayloads) { // check that we have a payload and it starts with "pos" Assert.IsNotNull(dp.GetPayload()); BytesRef payload = dp.GetPayload(); Assert.IsTrue(payload.Utf8ToString().StartsWith("pos:", StringComparison.Ordinal)); } // note: withPayloads=false doesnt necessarily mean we dont have them from MockAnalyzer! } } // check that other fields (without offsets) work correctly for (int i = 0; i < numDocs; i++) { DocsEnum dp = MultiFields.GetTermDocsEnum(reader, null, "id", new BytesRef("" + i), 0); Assert.AreEqual(i, dp.NextDoc()); Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dp.NextDoc()); } reader.Dispose(); dir.Dispose(); } [Test] public virtual void TestRandom() { // token -> docID -> tokens IDictionary<string, IDictionary<int?, IList<Token>>> actualTokens = new Dictionary<string, IDictionary<int?, IList<Token>>>(); Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, dir, iwc); int numDocs = AtLeast(20); //final int numDocs = AtLeast(5); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); // TODO: randomize what IndexOptions we use; also test // changing this up in one IW buffered segment...: ft.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; if (Random.NextBoolean()) { ft.StoreTermVectors = true; ft.StoreTermVectorOffsets = Random.NextBoolean(); ft.StoreTermVectorPositions = Random.NextBoolean(); } for (int docCount = 0; docCount < numDocs; docCount++) { Document doc = new Document(); doc.Add(new Int32Field("id", docCount, Field.Store.NO)); IList<Token> tokens = new List<Token>(); int numTokens = AtLeast(100); //final int numTokens = AtLeast(20); int pos = -1; int offset = 0; //System.out.println("doc id=" + docCount); for (int tokenCount = 0; tokenCount < numTokens; tokenCount++) { string text; if (Random.NextBoolean()) { text = "a"; } else if (Random.NextBoolean()) { text = "b"; } else if (Random.NextBoolean()) { text = "c"; } else { text = "d"; } int posIncr = Random.NextBoolean() ? 1 : Random.Next(5); if (tokenCount == 0 && posIncr == 0) { posIncr = 1; } int offIncr = Random.NextBoolean() ? 0 : Random.Next(5); int tokenOffset = Random.Next(5); Token token = MakeToken(text, posIncr, offset + offIncr, offset + offIncr + tokenOffset); if (!actualTokens.TryGetValue(text, out IDictionary<int?, IList<Token>> postingsByDoc)) { actualTokens[text] = postingsByDoc = new Dictionary<int?, IList<Token>>(); } if (!postingsByDoc.TryGetValue(docCount, out IList<Token> postings)) { postingsByDoc[docCount] = postings = new List<Token>(); } postings.Add(token); tokens.Add(token); pos += posIncr; // stuff abs position into type: token.Type = "" + pos; offset += offIncr + tokenOffset; //System.out.println(" " + token + " posIncr=" + token.getPositionIncrement() + " pos=" + pos + " off=" + token.StartOffset + "/" + token.EndOffset + " (freq=" + postingsByDoc.Get(docCount).Size() + ")"); } doc.Add(new Field("content", new CannedTokenStream(tokens.ToArray()), ft)); w.AddDocument(doc); } DirectoryReader r = w.GetReader(); w.Dispose(); string[] terms = new string[] { "a", "b", "c", "d" }; foreach (AtomicReaderContext ctx in r.Leaves) { // TODO: improve this AtomicReader sub = (AtomicReader)ctx.Reader; //System.out.println("\nsub=" + sub); TermsEnum termsEnum = sub.Fields.GetTerms("content").GetEnumerator(); DocsEnum docs = null; DocsAndPositionsEnum docsAndPositions = null; DocsAndPositionsEnum docsAndPositionsAndOffsets = null; FieldCache.Int32s docIDToID = FieldCache.DEFAULT.GetInt32s(sub, "id", false); foreach (string term in terms) { //System.out.println(" term=" + term); if (termsEnum.SeekExact(new BytesRef(term))) { docs = termsEnum.Docs(null, docs); Assert.IsNotNull(docs); int doc; //System.out.println(" doc/freq"); while ((doc = docs.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { IList<Token> expected = actualTokens[term][docIDToID.Get(doc)]; //System.out.println(" doc=" + docIDToID.Get(doc) + " docID=" + doc + " " + expected.Size() + " freq"); Assert.IsNotNull(expected); Assert.AreEqual(expected.Count, docs.Freq); } // explicitly exclude offsets here docsAndPositions = termsEnum.DocsAndPositions(null, docsAndPositions, DocsAndPositionsFlags.PAYLOADS); Assert.IsNotNull(docsAndPositions); //System.out.println(" doc/freq/pos"); while ((doc = docsAndPositions.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { IList<Token> expected = actualTokens[term][docIDToID.Get(doc)]; //System.out.println(" doc=" + docIDToID.Get(doc) + " " + expected.Size() + " freq"); Assert.IsNotNull(expected); Assert.AreEqual(expected.Count, docsAndPositions.Freq); foreach (Token token in expected) { int pos = Convert.ToInt32(token.Type); //System.out.println(" pos=" + pos); Assert.AreEqual(pos, docsAndPositions.NextPosition()); } } docsAndPositionsAndOffsets = termsEnum.DocsAndPositions(null, docsAndPositions); Assert.IsNotNull(docsAndPositionsAndOffsets); //System.out.println(" doc/freq/pos/offs"); while ((doc = docsAndPositionsAndOffsets.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { IList<Token> expected = actualTokens[term][docIDToID.Get(doc)]; //System.out.println(" doc=" + docIDToID.Get(doc) + " " + expected.Size() + " freq"); Assert.IsNotNull(expected); Assert.AreEqual(expected.Count, docsAndPositionsAndOffsets.Freq); foreach (Token token in expected) { int pos = Convert.ToInt32(token.Type); //System.out.println(" pos=" + pos); Assert.AreEqual(pos, docsAndPositionsAndOffsets.NextPosition()); Assert.AreEqual(token.StartOffset, docsAndPositionsAndOffsets.StartOffset); Assert.AreEqual(token.EndOffset, docsAndPositionsAndOffsets.EndOffset); } } } } // TODO: test advance: } r.Dispose(); dir.Dispose(); } [Test] public virtual void TestWithUnindexedFields() { Directory dir = NewDirectory(); RandomIndexWriter riw = new RandomIndexWriter(Random, dir, iwc); for (int i = 0; i < 100; i++) { Document doc = new Document(); // ensure at least one doc is indexed with offsets if (i < 99 && Random.Next(2) == 0) { // stored only FieldType ft = new FieldType(); ft.IsIndexed = false; ft.IsStored = true; doc.Add(new Field("foo", "boo!", ft)); } else { FieldType ft = new FieldType(TextField.TYPE_STORED); ft.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; if (Random.NextBoolean()) { // store some term vectors for the checkindex cross-check ft.StoreTermVectors = true; ft.StoreTermVectorPositions = true; ft.StoreTermVectorOffsets = true; } doc.Add(new Field("foo", "bar", ft)); } riw.AddDocument(doc); } CompositeReader ir = riw.GetReader(); AtomicReader slow = SlowCompositeReaderWrapper.Wrap(ir); FieldInfos fis = slow.FieldInfos; Assert.AreEqual(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, fis.FieldInfo("foo").IndexOptions); slow.Dispose(); ir.Dispose(); riw.Dispose(); dir.Dispose(); } [Test] public virtual void TestAddFieldTwice() { Directory dir = NewDirectory(); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); FieldType customType3 = new FieldType(TextField.TYPE_STORED); customType3.StoreTermVectors = true; customType3.StoreTermVectorPositions = true; customType3.StoreTermVectorOffsets = true; customType3.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; doc.Add(new Field("content3", "here is more content with aaa aaa aaa", customType3)); doc.Add(new Field("content3", "here is more content with aaa aaa aaa", customType3)); iw.AddDocument(doc); iw.Dispose(); dir.Dispose(); // checkindex } // NOTE: the next two tests aren't that good as we need an EvilToken... [Test] public virtual void TestNegativeOffsets() { try { CheckTokens(new Token[] { MakeToken("foo", 1, -1, -1) }); Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { //expected } } [Test] public virtual void TestIllegalOffsets() { try { CheckTokens(new Token[] { MakeToken("foo", 1, 1, 0) }); Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { //expected } } [Test] public virtual void TestBackwardsOffsets() { try { CheckTokens(new Token[] { MakeToken("foo", 1, 0, 3), MakeToken("foo", 1, 4, 7), MakeToken("foo", 0, 3, 6) }); Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { // expected } } [Test] public virtual void TestStackedTokens() { CheckTokens(new Token[] { MakeToken("foo", 1, 0, 3), MakeToken("foo", 0, 0, 3), MakeToken("foo", 0, 0, 3) }); } [Test] public virtual void TestLegalbutVeryLargeOffsets() { Directory dir = NewDirectory(); IndexWriter iw = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, null)); Document doc = new Document(); Token t1 = new Token("foo", 0, int.MaxValue - 500); if (Random.NextBoolean()) { t1.Payload = new BytesRef("test"); } Token t2 = new Token("foo", int.MaxValue - 500, int.MaxValue); TokenStream tokenStream = new CannedTokenStream(new Token[] { t1, t2 }); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); ft.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; // store some term vectors for the checkindex cross-check ft.StoreTermVectors = true; ft.StoreTermVectorPositions = true; ft.StoreTermVectorOffsets = true; Field field = new Field("foo", tokenStream, ft); doc.Add(field); iw.AddDocument(doc); iw.Dispose(); dir.Dispose(); } // TODO: more tests with other possibilities private void CheckTokens(Token[] tokens) { Directory dir = NewDirectory(); RandomIndexWriter riw = new RandomIndexWriter(Random, dir, iwc); bool success = false; try { FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); ft.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; // store some term vectors for the checkindex cross-check ft.StoreTermVectors = true; ft.StoreTermVectorPositions = true; ft.StoreTermVectorOffsets = true; Document doc = new Document(); doc.Add(new Field("body", new CannedTokenStream(tokens), ft)); riw.AddDocument(doc); success = true; } finally { if (success) { IOUtils.Dispose(riw, dir); } else { IOUtils.DisposeWhileHandlingException(riw, dir); } } } private Token MakeToken(string text, int posIncr, int startOffset, int endOffset) { Token t = new Token(); t.Append(text); t.PositionIncrement = posIncr; t.SetOffset(startOffset, endOffset); return t; } } }
#region License /* * All content copyright Marko Lahma, unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using Quartz.Util; namespace Quartz.Impl.Triggers { /// <summary> /// A concrete <see cref="ITrigger" /> that is used to fire a <see cref="IJobDetail" /> /// based upon repeating calendar time intervals. /// </summary> /// <remarks> /// The trigger will fire every N (see <see cref="RepeatInterval" />) units of calendar time /// (see <see cref="RepeatIntervalUnit" />) as specified in the trigger's definition. /// This trigger can achieve schedules that are not possible with <see cref="ISimpleTrigger" /> (e.g /// because months are not a fixed number of seconds) or <see cref="ICronTrigger" /> (e.g. because /// "every 5 months" is not an even divisor of 12). /// <para> /// If you use an interval unit of <see cref="IntervalUnit.Month" /> then care should be taken when setting /// a <see cref="StartTimeUtc" /> value that is on a day near the end of the month. For example, /// if you choose a start time that occurs on January 31st, and have a trigger with unit /// <see cref="IntervalUnit.Month" /> and interval 1, then the next fire time will be February 28th, /// and the next time after that will be March 28th - and essentially each subsequent firing will /// occur on the 28th of the month, even if a 31st day exists. If you want a trigger that always /// fires on the last day of the month - regardless of the number of days in the month, /// you should use <see cref="ICronTrigger" />. /// </para> /// </remarks> /// <see cref="ITrigger" /> /// <see cref="ICronTrigger" /> /// <see cref="ISimpleTrigger" /> /// <see cref="IDailyTimeIntervalTrigger" /> /// <since>2.0</since> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> [Serializable] public class CalendarIntervalTriggerImpl : AbstractTrigger, ICalendarIntervalTrigger { private static readonly int YearToGiveupSchedulingAt = DateTime.Now.AddYears(100).Year; private DateTimeOffset startTime; private DateTimeOffset? endTime; private DateTimeOffset? nextFireTimeUtc; // Making a public property which called GetNextFireTime/SetNextFireTime would make the json attribute unnecessary private DateTimeOffset? previousFireTimeUtc; // Making a public property which called GetPreviousFireTime/SetPreviousFireTime would make the json attribute unnecessary private int repeatInterval; internal TimeZoneInfo? timeZone; // Serializing TimeZones is tricky in .NET Core. This helper will ensure that we get the same timezone on a given platform, // but there's not yet a good method of serializing/deserializing timezones cross-platform since Windows timezone IDs don't // match IANA tz IDs (https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). This feature is coming, but depending // on timelines, it may be worth doign the mapping here. // More info: https://github.com/dotnet/corefx/issues/7757 private string? timeZoneInfoId { get => timeZone?.Id; set => timeZone = value == null ? null : TimeZoneInfo.FindSystemTimeZoneById(value); } /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> with no settings. /// </summary> public CalendarIntervalTriggerImpl() { } /// <summary> /// Create a <see cref="CalendarIntervalTriggerImpl" /> that will occur immediately, and /// repeat at the given interval. /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, IntervalUnit intervalUnit, int repeatInterval) : this(name, null, intervalUnit, repeatInterval) { } /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> that will occur immediately, and /// repeat at the given interval /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="group">Group for the trigger instance.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, string? group, IntervalUnit intervalUnit, int repeatInterval) : this(name, group, SystemTime.UtcNow(), null, intervalUnit, repeatInterval) { } /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> that will occur at the given time, /// and repeat at the given interval until the given end time. /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param> /// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to quit repeat firing.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, DateTimeOffset startTimeUtc, DateTimeOffset? endTimeUtc, IntervalUnit intervalUnit, int repeatInterval) : this(name, null, startTimeUtc, endTimeUtc, intervalUnit, repeatInterval) { } /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> that will occur at the given time, /// and repeat at the given interval until the given end time. /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="group">Group for the trigger instance.</param> /// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param> /// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to quit repeat firing.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, string? group, DateTimeOffset startTimeUtc, DateTimeOffset? endTimeUtc, IntervalUnit intervalUnit, int repeatInterval) : base(name, group) { StartTimeUtc = startTimeUtc; EndTimeUtc = endTimeUtc; RepeatIntervalUnit = intervalUnit; RepeatInterval = repeatInterval; } /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> that will occur at the given time, /// and repeat at the given interval until the given end time. /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="group">Group for the trigger instance.</param> /// <param name="jobName">Name of the associated job.</param> /// <param name="jobGroup">Group of the associated job.</param> /// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param> /// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to quit repeat firing.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, string group, string jobName, string jobGroup, DateTimeOffset startTimeUtc, DateTimeOffset? endTimeUtc, IntervalUnit intervalUnit, int repeatInterval) : base(name, group, jobName, jobGroup) { StartTimeUtc = startTimeUtc; EndTimeUtc = endTimeUtc; RepeatIntervalUnit = intervalUnit; RepeatInterval = repeatInterval; } /// <summary> /// Get the time at which the <see cref="CalendarIntervalTriggerImpl" /> should occur. /// </summary> public override DateTimeOffset StartTimeUtc { get { if (startTime == DateTimeOffset.MinValue) { startTime = SystemTime.UtcNow(); } return startTime; } set { if (value == DateTimeOffset.MinValue) { throw new ArgumentException("Start time cannot be DateTimeOffset.MinValue"); } DateTimeOffset? eTime = EndTimeUtc; if (eTime != null && eTime < value) { throw new ArgumentException("End time cannot be before start time"); } startTime = value; } } /// <summary> /// Tells whether this Trigger instance can handle events /// in millisecond precision. /// </summary> public override bool HasMillisecondPrecision => true; /// <summary> /// Get the time at which the <see cref="ICalendarIntervalTrigger" /> should quit /// repeating. /// </summary> public override DateTimeOffset? EndTimeUtc { get => endTime; set { DateTimeOffset sTime = StartTimeUtc; if (value != null && sTime > value) { throw new ArgumentException("End time cannot be before start time"); } endTime = value; } } /// <summary> /// Get or set the interval unit - the time unit on with the interval applies. /// </summary> public IntervalUnit RepeatIntervalUnit { get; set; } = IntervalUnit.Day; /// <summary> /// Get the time interval that will be added to the <see cref="ICalendarIntervalTrigger" />'s /// fire time (in the set repeat interval unit) in order to calculate the time of the /// next trigger repeat. /// </summary> public int RepeatInterval { get => repeatInterval; set { if (value < 0) { throw new ArgumentException("Repeat interval must be >= 1"); } repeatInterval = value; } } public TimeZoneInfo TimeZone { get { if (timeZone == null) { timeZone = TimeZoneInfo.Local; } return timeZone; } set => timeZone = value; } ///<summary> /// If intervals are a day or greater, this property (set to true) will /// cause the firing of the trigger to always occur at the same time of day, /// (the time of day of the startTime) regardless of daylight saving time /// transitions. Default value is false. /// </summary> /// <remarks> /// <para> /// For example, without the property set, your trigger may have a start /// time of 9:00 am on March 1st, and a repeat interval of 2 days. But /// after the daylight saving transition occurs, the trigger may start /// firing at 8:00 am every other day. /// </para> /// <para> /// If however, the time of day does not exist on a given day to fire /// (e.g. 2:00 am in the United States on the days of daylight saving /// transition), the trigger will go ahead and fire one hour off on /// that day, and then resume the normal hour on other days. If /// you wish for the trigger to never fire at the "wrong" hour, then /// you should set the property skipDayIfHourDoesNotExist. /// </para> ///</remarks> /// <seealso cref="ICalendarIntervalTrigger.SkipDayIfHourDoesNotExist"/> /// <seealso cref="ICalendarIntervalTrigger.TimeZone"/> /// <seealso cref="TriggerBuilder.StartAt"/> public bool PreserveHourOfDayAcrossDaylightSavings { get; set; } /// <summary> /// If intervals are a day or greater, and /// preserveHourOfDayAcrossDaylightSavings property is set to true, and the /// hour of the day does not exist on a given day for which the trigger /// would fire, the day will be skipped and the trigger advanced a second /// interval if this property is set to true. Defaults to false. /// </summary> /// <remarks> /// <b>CAUTION!</b> If you enable this property, and your hour of day happens /// to be that of daylight savings transition (e.g. 2:00 am in the United /// States) and the trigger's interval would have had the trigger fire on /// that day, then you may actually completely miss a firing on the day of /// transition if that hour of day does not exist on that day! In such a /// case the next fire time of the trigger will be computed as double (if /// the interval is 2 days, then a span of 4 days between firings will /// occur). /// </remarks> /// <seealso cref="ICalendarIntervalTrigger.PreserveHourOfDayAcrossDaylightSavings"/> public bool SkipDayIfHourDoesNotExist { get; set; } /// <summary> /// Get the number of times the <see cref="ICalendarIntervalTrigger" /> has already fired. /// </summary> public int TimesTriggered { get; set; } /// <summary> /// Validates the misfire instruction. /// </summary> /// <param name="misfireInstruction">The misfire instruction.</param> /// <returns></returns> protected override bool ValidateMisfireInstruction(int misfireInstruction) { if (misfireInstruction < Quartz.MisfireInstruction.IgnoreMisfirePolicy) { return false; } if (misfireInstruction > Quartz.MisfireInstruction.CalendarIntervalTrigger.DoNothing) { return false; } return true; } /// <summary> /// Updates the <see cref="ICalendarIntervalTrigger" />'s state based on the /// MisfireInstruction.XXX that was selected when the <see cref="ICalendarIntervalTrigger" /> /// was created. /// </summary> /// <remarks> /// If the misfire instruction is set to <see cref="MisfireInstruction.SmartPolicy" />, /// then the following scheme will be used: /// <ul> /// <li>The instruction will be interpreted as <see cref="MisfireInstruction.CalendarIntervalTrigger.FireOnceNow" /></li> /// </ul> /// </remarks> public override void UpdateAfterMisfire(ICalendar? cal) { int instr = MisfireInstruction; if (instr == Quartz.MisfireInstruction.IgnoreMisfirePolicy) { return; } if (instr == Quartz.MisfireInstruction.SmartPolicy) { instr = Quartz.MisfireInstruction.CalendarIntervalTrigger.FireOnceNow; } if (instr == Quartz.MisfireInstruction.CalendarIntervalTrigger.DoNothing) { DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow()); while (newFireTime != null && cal != null && !cal.IsTimeIncluded(newFireTime.Value)) { newFireTime = GetFireTimeAfter(newFireTime); } SetNextFireTimeUtc(newFireTime); } else if (instr == Quartz.MisfireInstruction.CalendarIntervalTrigger.FireOnceNow) { // fire once now... SetNextFireTimeUtc(SystemTime.UtcNow()); // the new fire time afterward will magically preserve the original // time of day for firing for day/week/month interval triggers, // because of the way getFireTimeAfter() works - in its always restarting // computation from the start time. } } /// <summary> /// This method should not be used by the Quartz client. /// <para> /// Called when the <see cref="IScheduler" /> has decided to 'fire' /// the trigger (Execute the associated <see cref="IJob" />), in order to /// give the <see cref="ITrigger" /> a chance to update itself for its next /// triggering (if any). /// </para> /// </summary> /// <seealso cref="JobExecutionException" /> public override void Triggered(ICalendar? calendar) { TimesTriggered++; previousFireTimeUtc = nextFireTimeUtc; nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); while (nextFireTimeUtc != null && calendar != null && !calendar.IsTimeIncluded(nextFireTimeUtc.Value)) { nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); if (nextFireTimeUtc == null) { break; } //avoid infinite loop if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt) { nextFireTimeUtc = null; } } } /// <summary> /// This method should not be used by the Quartz client. /// <para> /// The implementation should update the <see cref="ITrigger" />'s state /// based on the given new version of the associated <see cref="ICalendar" /> /// (the state should be updated so that it's next fire time is appropriate /// given the Calendar's new settings). /// </para> /// </summary> /// <param name="calendar"> </param> /// <param name="misfireThreshold"></param> public override void UpdateWithNewCalendar(ICalendar calendar, TimeSpan misfireThreshold) { nextFireTimeUtc = GetFireTimeAfter(previousFireTimeUtc); if (nextFireTimeUtc == null || calendar == null) { return; } DateTimeOffset now = SystemTime.UtcNow(); while (nextFireTimeUtc != null && !calendar.IsTimeIncluded(nextFireTimeUtc.Value)) { nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); if (nextFireTimeUtc == null) { break; } //avoid infinite loop if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt) { nextFireTimeUtc = null; } if (nextFireTimeUtc != null && nextFireTimeUtc < now) { TimeSpan diff = now - nextFireTimeUtc.Value; if (diff >= misfireThreshold) { nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); } } } } /// <summary> /// This method should not be used by the Quartz client. /// </summary> /// <remarks> /// <para> /// Called by the scheduler at the time a <see cref="ITrigger" /> is first /// added to the scheduler, in order to have the <see cref="ITrigger" /> /// compute its first fire time, based on any associated calendar. /// </para> /// /// <para> /// After this method has been called, <see cref="ITrigger.GetNextFireTimeUtc" /> /// should return a valid answer. /// </para> /// </remarks> /// <returns> /// The first time at which the <see cref="ITrigger" /> will be fired /// by the scheduler, which is also the same value <see cref="ITrigger.GetNextFireTimeUtc" /> /// will return (until after the first firing of the <see cref="ITrigger" />). /// </returns> public override DateTimeOffset? ComputeFirstFireTimeUtc(ICalendar? calendar) { nextFireTimeUtc = TimeZoneUtil.ConvertTime(StartTimeUtc, TimeZone); while (nextFireTimeUtc != null && calendar != null && !calendar.IsTimeIncluded(nextFireTimeUtc.Value)) { nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); if (nextFireTimeUtc == null) { break; } //avoid infinite loop if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt) { return null; } } return nextFireTimeUtc; } /// <summary> /// Returns the next time at which the <see cref="ITrigger" /> is scheduled to fire. If /// the trigger will not fire again, <see langword="null" /> will be returned. Note that /// the time returned can possibly be in the past, if the time that was computed /// for the trigger to next fire has already arrived, but the scheduler has not yet /// been able to fire the trigger (which would likely be due to lack of resources /// e.g. threads). /// </summary> ///<remarks> /// The value returned is not guaranteed to be valid until after the <see cref="ITrigger" /> /// has been added to the scheduler. /// </remarks> /// <returns></returns> public override DateTimeOffset? GetNextFireTimeUtc() { return nextFireTimeUtc; } /// <summary> /// Returns the previous time at which the <see cref="ICalendarIntervalTrigger" /> fired. /// If the trigger has not yet fired, <see langword="null" /> will be returned. /// </summary> public override DateTimeOffset? GetPreviousFireTimeUtc() { return previousFireTimeUtc; } public override void SetNextFireTimeUtc(DateTimeOffset? value) { nextFireTimeUtc = value; } public override void SetPreviousFireTimeUtc(DateTimeOffset? previousFireTimeUtc) { this.previousFireTimeUtc = previousFireTimeUtc; } /// <summary> /// Returns the next time at which the <see cref="ICalendarIntervalTrigger" /> will fire, /// after the given time. If the trigger will not fire after the given time, /// <see langword="null" /> will be returned. /// </summary> public override DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTime) { return GetFireTimeAfter(afterTime, false); } protected DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTime, bool ignoreEndTime) { // increment afterTime by a second, so that we are // comparing against a time after it! if (afterTime == null) { afterTime = SystemTime.UtcNow().AddSeconds(1); } else { afterTime = afterTime.Value.AddSeconds(1); } DateTimeOffset startMillis = StartTimeUtc; DateTimeOffset afterMillis = afterTime.Value; DateTimeOffset endMillis = EndTimeUtc ?? DateTimeOffset.MaxValue; if (!ignoreEndTime && endMillis <= afterMillis) { return null; } if (afterMillis < startMillis) { return startMillis; } long secondsAfterStart = (long) (afterMillis - startMillis).TotalSeconds; DateTimeOffset? time = null; long repeatLong = RepeatInterval; DateTimeOffset sTime = StartTimeUtc; if (timeZone != null) { sTime = TimeZoneUtil.ConvertTime(sTime, timeZone); } if (RepeatIntervalUnit == IntervalUnit.Second) { long jumpCount = secondsAfterStart/repeatLong; if (secondsAfterStart%repeatLong != 0) { jumpCount++; } time = sTime.AddSeconds(RepeatInterval*(int) jumpCount); } else if (RepeatIntervalUnit == IntervalUnit.Minute) { long jumpCount = secondsAfterStart/(repeatLong*60L); if (secondsAfterStart%(repeatLong*60L) != 0) { jumpCount++; } time = sTime.AddMinutes(RepeatInterval*(int) jumpCount); } else if (RepeatIntervalUnit == IntervalUnit.Hour) { long jumpCount = secondsAfterStart/(repeatLong*60L*60L); if (secondsAfterStart%(repeatLong*60L*60L) != 0) { jumpCount++; } time = sTime.AddHours(RepeatInterval*(int) jumpCount); } else { // intervals a day or greater ... int initialHourOfDay = sTime.Hour; if (RepeatIntervalUnit == IntervalUnit.Day) { // Because intervals greater than an hour have an non-fixed number // of seconds in them (due to daylight savings, variation number of // days in each month, leap year, etc. ) we can't jump forward an // exact number of seconds to calculate the fire time as we can // with the second, minute and hour intervals. But, rather // than slowly crawling our way there by iteratively adding the // increment to the start time until we reach the "after time", // we can first make a big leap most of the way there... long jumpCount = secondsAfterStart/(repeatLong*24L*60L*60L); // if we need to make a big jump, jump most of the way there, // but not all the way because in some cases we may over-shoot or under-shoot if (jumpCount > 20) { if (jumpCount < 50) { jumpCount = (long) (jumpCount*0.80); } else if (jumpCount < 500) { jumpCount = (long) (jumpCount*0.90); } else { jumpCount = (long) (jumpCount*0.95); } sTime = sTime.AddDays(RepeatInterval*jumpCount); } // now baby-step the rest of the way there... while (sTime.UtcDateTime < afterTime.Value.UtcDateTime && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddDays(RepeatInterval); MakeHourAdjustmentIfNeeded(ref sTime, initialHourOfDay); //hours can shift due to DST } while (DaylightSavingHourShiftOccurredAndAdvanceNeeded(ref sTime, initialHourOfDay) && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddDays(RepeatInterval); } time = sTime; } else if (RepeatIntervalUnit == IntervalUnit.Week) { // Because intervals greater than an hour have an non-fixed number // of seconds in them (due to daylight savings, variation number of // days in each month, leap year, etc. ) we can't jump forward an // exact number of seconds to calculate the fire time as we can // with the second, minute and hour intervals. But, rather // than slowly crawling our way there by iteratively adding the // increment to the start time until we reach the "after time", // we can first make a big leap most of the way there... long jumpCount = secondsAfterStart/(repeatLong*7L*24L*60L*60L); // if we need to make a big jump, jump most of the way there, // but not all the way because in some cases we may over-shoot or under-shoot if (jumpCount > 20) { if (jumpCount < 50) { jumpCount = (long) (jumpCount*0.80); } else if (jumpCount < 500) { jumpCount = (long) (jumpCount*0.90); } else { jumpCount = (long) (jumpCount*0.95); } sTime = sTime.AddDays((int) (RepeatInterval*jumpCount*7)); } while (sTime.UtcDateTime < afterTime.Value.UtcDateTime && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddDays(RepeatInterval*7); MakeHourAdjustmentIfNeeded(ref sTime, initialHourOfDay); //hours can shift due to DST } while (DaylightSavingHourShiftOccurredAndAdvanceNeeded(ref sTime, initialHourOfDay) && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddDays(RepeatInterval*7); } time = sTime; } else if (RepeatIntervalUnit == IntervalUnit.Month) { // because of the large variation in size of months, and // because months are already large blocks of time, we will // just advance via brute-force iteration. while (sTime.UtcDateTime < afterTime.Value.UtcDateTime && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddMonths(RepeatInterval); MakeHourAdjustmentIfNeeded(ref sTime, initialHourOfDay); //hours can shift due to DST } while (DaylightSavingHourShiftOccurredAndAdvanceNeeded(ref sTime, initialHourOfDay) && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddMonths(RepeatInterval); } time = sTime; } else if (RepeatIntervalUnit == IntervalUnit.Year) { while (sTime.UtcDateTime < afterTime.Value.UtcDateTime && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddYears(RepeatInterval); MakeHourAdjustmentIfNeeded(ref sTime, initialHourOfDay); //hours can shift due to DST } while (DaylightSavingHourShiftOccurredAndAdvanceNeeded(ref sTime, initialHourOfDay) && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddYears(RepeatInterval); } time = sTime; } } // case of interval of a day or greater if (!ignoreEndTime && endMillis <= time) { return null; } sTime = TimeZoneUtil.ConvertTime(sTime, TimeZone); //apply the timezone before we return the time. return time; } private bool DaylightSavingHourShiftOccurredAndAdvanceNeeded(ref DateTimeOffset newTime, int initialHourOfDay) { //need to apply timezone again to properly check if initialHourOfDay has changed. DateTimeOffset toCheck = TimeZoneUtil.ConvertTime(newTime, TimeZone); if (PreserveHourOfDayAcrossDaylightSavings && toCheck.Hour != initialHourOfDay) { //first apply the date, and then find the proper timezone offset newTime = new DateTimeOffset(newTime.Year, newTime.Month, newTime.Day, initialHourOfDay, newTime.Minute, newTime.Second, newTime.Millisecond, TimeSpan.Zero); newTime = new DateTimeOffset(newTime.DateTime, TimeZoneUtil.GetUtcOffset(newTime.DateTime, TimeZone)); //TimeZone.IsInvalidTime is true, if this hour does not exist in the specified timezone bool isInvalid = TimeZone.IsInvalidTime(newTime.DateTime); if (isInvalid && SkipDayIfHourDoesNotExist) { return SkipDayIfHourDoesNotExist; } //don't skip this day, instead find closest valid time by adding minutes. while (TimeZone.IsInvalidTime(newTime.DateTime)) { newTime = newTime.AddMinutes(1); } //apply proper offset for the adjusted time newTime = new DateTimeOffset(newTime.DateTime, TimeZoneUtil.GetUtcOffset(newTime.DateTime, TimeZone)); } return false; } private void MakeHourAdjustmentIfNeeded(ref DateTimeOffset sTime, int initialHourOfDay) { //this method was made to adjust the time if a DST occurred, this is to stay consistent with the time //we are checking against, which is the afterTime. There were problems the occurred when the DST adjustment //took the time an hour back, leading to the times were not being adjusted properly. //avoid shifts in day, otherwise this will cause an infinite loop in the code. int initalYear = sTime.Year; int initalMonth = sTime.Month; int initialDay = sTime.Day; sTime = TimeZoneUtil.ConvertTime(sTime, TimeZone); if (PreserveHourOfDayAcrossDaylightSavings && sTime.Hour != initialHourOfDay) { //first apply the date, and then find the proper timezone offset sTime = new DateTimeOffset(initalYear, initalMonth, initialDay, initialHourOfDay, sTime.Minute, sTime.Second, sTime.Millisecond, TimeSpan.Zero); sTime = new DateTimeOffset(sTime.DateTime, TimeZoneUtil.GetUtcOffset(sTime.DateTime, TimeZone)); } } /// <summary> /// Returns the final time at which the <see cref="ICalendarIntervalTrigger" /> will /// fire, if there is no end time set, null will be returned. /// </summary> /// <value></value> /// <remarks>Note that the return time may be in the past.</remarks> public override DateTimeOffset? FinalFireTimeUtc { get { if (EndTimeUtc == null) { return null; } // back up a second from end time DateTimeOffset? fTime = EndTimeUtc.Value.AddSeconds(-1); // find the next fire time after that fTime = GetFireTimeAfter(fTime, true); // the trigger fires at the end time, that's it! if (fTime == null || fTime == EndTimeUtc) { return fTime; } // otherwise we have to back up one interval from the fire time after the end time DateTimeOffset lTime = fTime.Value; if (RepeatIntervalUnit == IntervalUnit.Second) { lTime = lTime.AddSeconds(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Minute) { lTime = lTime.AddMinutes(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Hour) { lTime = lTime.AddHours(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Day) { lTime = lTime.AddDays(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Week) { lTime = lTime.AddDays(-1*RepeatInterval*7); } else if (RepeatIntervalUnit == IntervalUnit.Month) { lTime = lTime.AddMonths(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Year) { lTime = lTime.AddYears(-1*RepeatInterval); } return lTime; } } /// <summary> /// Determines whether or not the <see cref="ICalendarIntervalTrigger" /> will occur /// again. /// </summary> /// <returns></returns> public override bool GetMayFireAgain() { return GetNextFireTimeUtc() != null; } /// <summary> /// Validates whether the properties of the <see cref="IJobDetail" /> are /// valid for submission into a <see cref="IScheduler" />. /// </summary> public override void Validate() { base.Validate(); if (RepeatIntervalUnit == IntervalUnit.Millisecond) { throw new SchedulerException("Invalid repeat IntervalUnit (must be Second, Minute, Hour, Day, Month, Week or Year)."); } if (repeatInterval < 1) { throw new SchedulerException("Repeat Interval cannot be zero."); } } public override IScheduleBuilder GetScheduleBuilder() { CalendarIntervalScheduleBuilder cb = CalendarIntervalScheduleBuilder.Create() .WithInterval(RepeatInterval, RepeatIntervalUnit) .InTimeZone(TimeZone) .PreserveHourOfDayAcrossDaylightSavings(PreserveHourOfDayAcrossDaylightSavings) .SkipDayIfHourDoesNotExist(SkipDayIfHourDoesNotExist); switch (MisfireInstruction) { case Quartz.MisfireInstruction.CalendarIntervalTrigger.DoNothing: cb.WithMisfireHandlingInstructionDoNothing(); break; case Quartz.MisfireInstruction.CalendarIntervalTrigger.FireOnceNow: cb.WithMisfireHandlingInstructionFireAndProceed(); break; case Quartz.MisfireInstruction.IgnoreMisfirePolicy: cb.WithMisfireHandlingInstructionIgnoreMisfires(); break; } return cb; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenSim; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.ApplicationPlugins.RegionModulesController { public class RegionModulesControllerPlugin : IRegionModulesController, IApplicationPlugin { // Logger private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); // Config access private OpenSimBase m_openSim; // Our name private string m_name; // Internal lists to collect information about modules present private List<TypeExtensionNode> m_nonSharedModules = new List<TypeExtensionNode>(); private List<TypeExtensionNode> m_sharedModules = new List<TypeExtensionNode>(); // List of shared module instances, for adding to Scenes private List<ISharedRegionModule> m_sharedInstances = new List<ISharedRegionModule>(); #region IApplicationPlugin implementation public void Initialise (OpenSimBase openSim) { m_openSim = openSim; m_openSim.ApplicationRegistry.RegisterInterface<IRegionModulesController>(this); m_log.DebugFormat("[REGIONMODULES]: Initializing..."); // Who we are string id = AddinManager.CurrentAddin.Id; // Make friendly name int pos = id.LastIndexOf("."); if (pos == -1) m_name = id; else m_name = id.Substring(pos + 1); // The [Modules] section in the ini file IConfig modulesConfig = m_openSim.ConfigSource.Source.Configs["Modules"]; if (modulesConfig == null) modulesConfig = m_openSim.ConfigSource.Source.AddConfig("Modules"); // Scan modules and load all that aren't disabled foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes("/OpenSim/RegionModules")) { if (node.Type.GetInterface(typeof(ISharedRegionModule).ToString()) != null) { // Get the config string string moduleString = modulesConfig.GetString("Setup_" + node.Id, String.Empty); // We have a selector if (moduleString != String.Empty) { // Allow disabling modules even if they don't have // support for it if (moduleString == "disabled") continue; // Split off port, if present string[] moduleParts = moduleString.Split(new char[] { '/' }, 2); // Format is [port/][class] string className = moduleParts[0]; if (moduleParts.Length > 1) className = moduleParts[1]; // Match the class name if given if (className != String.Empty && node.Type.ToString() != className) continue; } m_log.DebugFormat("[REGIONMODULES]: Found shared region module {0}, class {1}", node.Id, node.Type); m_sharedModules.Add(node); } else if (node.Type.GetInterface(typeof(INonSharedRegionModule).ToString()) != null) { // Get the config string string moduleString = modulesConfig.GetString("Setup_" + node.Id, String.Empty); // We have a selector if (moduleString != String.Empty) { // Allow disabling modules even if they don't have // support for it if (moduleString == "disabled") continue; // Split off port, if present string[] moduleParts = moduleString.Split(new char[] { '/' }, 2); // Format is [port/][class] string className = moduleParts[0]; if (moduleParts.Length > 1) className = moduleParts[1]; // Match the class name if given if (className != String.Empty && node.Type.ToString() != className) continue; } m_log.DebugFormat("[REGIONMODULES]: Found non-shared region module {0}, class {1}", node.Id, node.Type); m_nonSharedModules.Add(node); } else m_log.DebugFormat("[REGIONMODULES]: Found unknown type of module {0}, class {1}", node.Id, node.Type); } // Load and init the module. We try a constructor with a port // if a port was given, fall back to one without if there is // no port or the more specific constructor fails. // This will be removed, so that any module capable of using a port // must provide a constructor with a port in the future. // For now, we do this so migration is easy. // foreach (TypeExtensionNode node in m_sharedModules) { Object[] ctorArgs = new Object[] { (uint)0 }; // Read the config again string moduleString = modulesConfig.GetString("Setup_" + node.Id, String.Empty); // Get the port number, if there is one if (moduleString != String.Empty) { // Get the port number from the string string[] moduleParts = moduleString.Split(new char[] { '/' }, 2); if (moduleParts.Length > 1) ctorArgs[0] = Convert.ToUInt32(moduleParts[0]); } // Try loading and initilaizing the module, using the // port if appropriate ISharedRegionModule module = null; try { module = (ISharedRegionModule)Activator.CreateInstance( node.Type, ctorArgs); } catch { module = (ISharedRegionModule)Activator.CreateInstance( node.Type); } // OK, we're up and running m_sharedInstances.Add(module); module.Initialise(m_openSim.ConfigSource.Source); } } public void PostInitialise () { m_log.DebugFormat("[REGIONMODULES]: PostInitializing..."); // Immediately run PostInitialise on shared modules foreach (ISharedRegionModule module in m_sharedInstances) { module.PostInitialise(); } } #endregion #region IPlugin implementation // We don't do that here // public void Initialise () { throw new System.NotImplementedException(); } #endregion #region IDisposable implementation // Cleanup // public void Dispose () { // We expect that all regions have been removed already while (m_sharedInstances.Count > 0) { m_sharedInstances[0].Close(); m_sharedInstances.RemoveAt(0); } m_sharedModules.Clear(); m_nonSharedModules.Clear(); } #endregion public string Version { get { return AddinManager.CurrentAddin.Version; } } public string Name { get { return m_name; } } #region IRegionModulesController implementation // The root of all evil. // This is where we handle adding the modules to scenes when they // load. This means that here we deal with replaceable interfaces, // nonshared modules, etc. // public void AddRegionToModules (Scene scene) { Dictionary<Type, ISharedRegionModule> deferredSharedModules = new Dictionary<Type, ISharedRegionModule>(); Dictionary<Type, INonSharedRegionModule> deferredNonSharedModules = new Dictionary<Type, INonSharedRegionModule>(); // We need this to see if a module has already been loaded and // has defined a replaceable interface. It's a generic call, // so this can't be used directly. It will be used later Type s = scene.GetType(); MethodInfo mi = s.GetMethod("RequestModuleInterface"); // This will hold the shared modules we actually load List<ISharedRegionModule> sharedlist = new List<ISharedRegionModule>(); // Iterate over the shared modules that have been loaded // Add them to the new Scene foreach (ISharedRegionModule module in m_sharedInstances) { // Here is where we check if a replaceable interface // is defined. If it is, the module is checked against // the interfaces already defined. If the interface is // defined, we simply skip the module. Else, if the module // defines a replaceable interface, we add it to the deferred // list. Type replaceableInterface = module.ReplaceableInterface; if (replaceableInterface != null) { MethodInfo mii = mi.MakeGenericMethod(replaceableInterface); if (mii.Invoke(scene, new object[0]) != null) { m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString()); continue; } deferredSharedModules[replaceableInterface] = module; m_log.DebugFormat("[REGIONMODULE]: Deferred load of {0}", module.Name); continue; } m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to shared module {1}", scene.RegionInfo.RegionName, module.Name); module.AddRegion(scene); scene.AddRegionModule(module.Name, module); sharedlist.Add(module); } IConfig modulesConfig = m_openSim.ConfigSource.Source.Configs["Modules"]; // Scan for, and load, nonshared modules List<INonSharedRegionModule> list = new List<INonSharedRegionModule>(); foreach (TypeExtensionNode node in m_nonSharedModules) { Object[] ctorArgs = new Object[] {0}; // Read the config string moduleString = modulesConfig.GetString("Setup_" + node.Id, String.Empty); // Get the port number, if there is one if (moduleString != String.Empty) { // Get the port number from the string string[] moduleParts = moduleString.Split(new char[] {'/'}, 2); if (moduleParts.Length > 1) ctorArgs[0] = Convert.ToUInt32(moduleParts[0]); } // Actually load it INonSharedRegionModule module = null; Type[] ctorParamTypes = new Type[ctorArgs.Length]; for (int i = 0; i < ctorParamTypes.Length; i++) ctorParamTypes[i] = ctorArgs[i].GetType(); if (node.Type.GetConstructor(ctorParamTypes) != null) module = (INonSharedRegionModule)Activator.CreateInstance(node.Type, ctorArgs); else module = (INonSharedRegionModule)Activator.CreateInstance(node.Type); // Check for replaceable interfaces Type replaceableInterface = module.ReplaceableInterface; if (replaceableInterface != null) { MethodInfo mii = mi.MakeGenericMethod(replaceableInterface); if (mii.Invoke(scene, new object[0]) != null) { m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString()); continue; } deferredNonSharedModules[replaceableInterface] = module; m_log.DebugFormat("[REGIONMODULE]: Deferred load of {0}", module.Name); continue; } m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to non-shared module {1}", scene.RegionInfo.RegionName, module.Name); // Initialise the module module.Initialise(m_openSim.ConfigSource.Source); list.Add(module); } // Now add the modules that we found to the scene. If a module // wishes to override a replaceable interface, it needs to // register it in Initialise, so that the deferred module // won't load. foreach (INonSharedRegionModule module in list) { module.AddRegion(scene); scene.AddRegionModule(module.Name, module); } // Now all modules without a replaceable base interface are loaded // Replaceable modules have either been skipped, or omitted. // Now scan the deferred modules here foreach (ISharedRegionModule module in deferredSharedModules.Values) { // Determine if the interface has been replaced Type replaceableInterface = module.ReplaceableInterface; MethodInfo mii = mi.MakeGenericMethod(replaceableInterface); if (mii.Invoke(scene, new object[0]) != null) { m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString()); continue; } m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to shared module {1} (deferred)", scene.RegionInfo.RegionName, module.Name); // Not replaced, load the module module.AddRegion(scene); scene.AddRegionModule(module.Name, module); sharedlist.Add(module); } // Same thing for nonshared modules, load them unless overridden List<INonSharedRegionModule> deferredlist = new List<INonSharedRegionModule>(); foreach (INonSharedRegionModule module in deferredNonSharedModules.Values) { // Check interface override Type replaceableInterface = module.ReplaceableInterface; if (replaceableInterface != null) { MethodInfo mii = mi.MakeGenericMethod(replaceableInterface); if (mii.Invoke(scene, new object[0]) != null) { m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString()); continue; } } m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to non-shared module {1} (deferred)", scene.RegionInfo.RegionName, module.Name); module.Initialise(m_openSim.ConfigSource.Source); list.Add(module); deferredlist.Add(module); } // Finally, load valid deferred modules foreach (INonSharedRegionModule module in deferredlist) { module.AddRegion(scene); scene.AddRegionModule(module.Name, module); } // This is needed for all module types. Modules will register // Interfaces with scene in AddScene, and will also need a means // to access interfaces registered by other modules. Without // this extra method, a module attempting to use another modules's // interface would be successful only depending on load order, // which can't be depended upon, or modules would need to resort // to ugly kludges to attempt to request interfaces when needed // and unneccessary caching logic repeated in all modules. // The extra function stub is just that much cleaner // foreach (ISharedRegionModule module in sharedlist) { module.RegionLoaded(scene); } foreach (INonSharedRegionModule module in list) { module.RegionLoaded(scene); } } public void RemoveRegionFromModules (Scene scene) { foreach (IRegionModuleBase module in scene.RegionModules.Values) { m_log.DebugFormat("[REGIONMODULE]: Removing scene {0} from module {1}", scene.RegionInfo.RegionName, module.Name); module.RemoveRegion(scene); if (module is INonSharedRegionModule) { // as we were the only user, this instance has to die module.Close(); } } scene.RegionModules.Clear(); } #endregion } }
// namespace Moq { namespace AutoMocking { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Microsoft.Practices.ObjectBuilder2; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.ObjectBuilder; /// <summary> /// AutoMocking container that leverages the Unity IOC container and the Moq /// mocking library to automatically mock classes resolved from the container. /// </summary> /// <remarks> /// taken from /// http://code.google.com/p/moq-contrib/source/browse/trunk/Source.Silverlight/Moq.Contrib.UnityAutoMocker.Silverlight/UnityAutoMockContainer.cs /// and updated to Enterprise Library 5 /// </remarks> public class UnityAutoMockContainer { /// <summary> /// Value used when the internal Unity plugin needs to decide if an instance /// class is to be created as a Mock(of T) or not. /// </summary> internal const string NameForMocking = "____FOR____MOCKING____57ebd55f-9831-40c7-9a24-b7d450209ad0"; private readonly IAutoMockerBackingContainer _container; /// <summary> /// Same as calling <code>new UnityAutoMockContainer(new MockFactory(MockBehavior.Loose))</code> /// </summary> public UnityAutoMockContainer() : this(new MockFactory(MockBehavior.Loose)) { } /// <summary> /// Allows you to specify the MockFactory that will be used when creating mocked items. /// </summary> public UnityAutoMockContainer(MockFactory factory) { _container = new UnityAutoMockerBackingContainer(factory); } #region Public interface /// <summary> /// This is just a pass through to the underlying Unity Container. It will /// register the instance with the ContainerControlledLifetimeManager (Singleton) /// </summary> public UnityAutoMockContainer RegisterInstance<TService>(TService instance) { _container.RegisterInstance(instance); return this; } /// <summary> /// This is just a pass through to the underlying Unity Container. It will /// register the type with the ContainerControlledLifetimeManager (Singleton) /// </summary> public UnityAutoMockContainer Register<TService, TImplementation>() where TImplementation : TService { _container.RegisterType<TService, TImplementation>(); return this; } /// <summary> /// This will create a Mock(of T) for any Interface or Class requested. /// </summary> /// <remarks>Note: that the Mock returned will live as a Singleton, so if you setup any expectations on the Mock(of T) then they will life for the lifetime of this container.</remarks> /// <typeparam name="T">Interface or Class that to create a Mock(of T) for.</typeparam> /// <returns>Mocked instance of the type T.</returns> public Mock<T> GetMock<T>() where T : class { return _container.ResolveForMocking<T>().Mock; } /// <summary> /// This will resolve an interface or class from the underlying container. /// </summary> /// <remarks> /// 1. If T is an interface it will return the Mock(of T).Object instance /// 2. If T is a class it will just return that class /// - unless the class was first created by using the GetMock(of T) in which case it will return a Mocked instance of the class /// </remarks> public T Resolve<T>() { return _container.Resolve<T>(); } #endregion interface IAutoMockerBackingContainer { void RegisterInstance<TService>(TService instance); void RegisterType<TService, TImplementation>() where TImplementation : TService; T Resolve<T>(); object Resolve(Type type); IMocked<T> ResolveForMocking<T>() where T : class; } private class UnityAutoMockerBackingContainer : IAutoMockerBackingContainer { private readonly IUnityContainer _unityContainer = new UnityContainer(); public UnityAutoMockerBackingContainer(MockFactory factory) { _unityContainer.AddExtension(new MockFactoryContainerExtension(factory, this)); } public void RegisterInstance<TService>(TService instance) { _unityContainer.RegisterInstance(instance, new ContainerControlledLifetimeManager()); } public void RegisterType<TService, TImplementation>() where TImplementation : TService { _unityContainer.RegisterType<TService, TImplementation>(new ContainerControlledLifetimeManager()); } public T Resolve<T>() { return _unityContainer.Resolve<T>(); } public object Resolve(Type type) { return _unityContainer.Resolve(type); } public IMocked<T> ResolveForMocking<T>() where T : class { return (IMocked<T>)_unityContainer.Resolve<T>(NameForMocking); } private class MockFactoryContainerExtension : UnityContainerExtension { private readonly MockFactory _mockFactory; private readonly IAutoMockerBackingContainer _container; public MockFactoryContainerExtension(MockFactory mockFactory, IAutoMockerBackingContainer container) { _mockFactory = mockFactory; _container = container; } protected override void Initialize() { Context.Strategies.Add(new MockExtensibilityStrategy(_mockFactory, _container), UnityBuildStage.PreCreation); } } private class MockExtensibilityStrategy : BuilderStrategy { private readonly MockFactory _factory; private readonly IAutoMockerBackingContainer _container; private readonly MethodInfo _createMethod; private readonly Dictionary<Type, Mock> _alreadyCreatedMocks = new Dictionary<Type, Mock>(); private MethodInfo _createMethodWithParameters; public MockExtensibilityStrategy(MockFactory factory, IAutoMockerBackingContainer container) { _factory = factory; _container = container; _createMethod = factory.GetType().GetMethod("Create", new Type[] { }); Debug.Assert(_createMethod != null); } public override void PreBuildUp(IBuilderContext context) { NamedTypeBuildKey buildKey = (NamedTypeBuildKey)context.BuildKey; bool isToBeAMockedClassInstance = buildKey.Name == NameForMocking; Type mockServiceType = buildKey.Type; if (!mockServiceType.IsInterface && !isToBeAMockedClassInstance) { if (_alreadyCreatedMocks.ContainsKey(mockServiceType)) { var mockedObject = _alreadyCreatedMocks[mockServiceType]; SetBuildObjectAndCompleteIt(context, mockedObject); } else { base.PreBuildUp(context); } } else { Mock mockedObject; if (_alreadyCreatedMocks.ContainsKey(mockServiceType)) { mockedObject = _alreadyCreatedMocks[mockServiceType]; } else { if (isToBeAMockedClassInstance && !mockServiceType.IsInterface) { object[] mockedParametersToInject = GetConstructorParameters(context).ToArray(); _createMethodWithParameters = _factory.GetType().GetMethod("Create", new[] { typeof(object[]) }); MethodInfo specificCreateMethod = _createMethodWithParameters.MakeGenericMethod(new[] { mockServiceType }); var x = specificCreateMethod.Invoke(_factory, new object[] { mockedParametersToInject }); mockedObject = (Mock)x; } else { MethodInfo specificCreateMethod = _createMethod.MakeGenericMethod(new[] { mockServiceType }); mockedObject = (Mock)specificCreateMethod.Invoke(_factory, null); } _alreadyCreatedMocks.Add(mockServiceType, mockedObject); } SetBuildObjectAndCompleteIt(context, mockedObject); } } private static void SetBuildObjectAndCompleteIt(IBuilderContext context, Mock mockedObject) { context.Existing = mockedObject.Object; context.BuildComplete = true; } private List<object> GetConstructorParameters(IBuilderContext context) { var parameters = new List<object>(); var policy = new DefaultUnityConstructorSelectorPolicy(); var constructor = policy.SelectConstructor(context, new PolicyList()); ConstructorInfo constructorInfo; if (constructor == null) { // Unit constructor selector doesn't seem to want to find abstract class protected constructors // quickly find one here... var buildKey = (NamedTypeBuildKey)context.BuildKey; var largestConstructor = buildKey.Type.GetConstructors( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .OrderByDescending(o => o.GetParameters().Length) .FirstOrDefault(); constructorInfo = largestConstructor; } else { constructorInfo = constructor.Constructor; } foreach (var parameterInfo in constructorInfo.GetParameters()) parameters.Add(_container.Resolve(parameterInfo.ParameterType)); return parameters; } } } } } namespace AutoMocking.SelfTesting { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; public class UnityAutoMockContainerFixture { protected UnityAutoMockContainer GetAutoMockContainer(MockFactory factory) { return new UnityAutoMockContainer(factory); } public static void RunAllTests(Action<string> messageWriter) { var fixture = new UnityAutoMockContainerFixture(); RunAllTests(fixture, messageWriter); } public static void RunAllTests(UnityAutoMockContainerFixture fixture, Action<string> messageWriter) { messageWriter("Starting Tests..."); foreach (var assertion in fixture.GetAllAssertions) { assertion(messageWriter); } messageWriter("Completed Tests..."); } public IEnumerable<Action<Action<string>>> GetAllAssertions { get { var tests = new List<Action<Action<string>>>(); Func<string, string> putSpacesBetweenPascalCasedWords = (s) => { var r = new Regex("([A-Z]+[a-z]+)"); return r.Replace(s, m => (m.Value.Length > 3 ? m.Value : m.Value.ToLower()) + " "); }; var methodInfos = this .GetType() .GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(w => w.GetCustomAttributes(typeof(TestAttribute), true).Any()) .OrderBy(ob => ob.Name); foreach (var methodInfo in methodInfos) { MethodInfo info = methodInfo; Action<Action<string>> a = messageWriter => { messageWriter("Testing - " + putSpacesBetweenPascalCasedWords(info.Name)); info.Invoke(this, new object[0]); }; tests.Add(a); } foreach (var action in tests) yield return action; } } [Test] public void CreatesLooseMocksIfFactoryIsMockBehaviorLoose() { var factory = GetAutoMockContainer(new MockFactory(MockBehavior.Loose)); var component = factory.Resolve<TestComponent>(); component.RunAll(); } [Test] public void CanRegisterImplementationAndResolveIt() { var factory = GetAutoMockContainer(new MockFactory(MockBehavior.Loose)); factory.Register<ITestComponent, TestComponent>(); var testComponent = factory.Resolve<ITestComponent>(); Assert.IsNotNull(testComponent); Assert.IsFalse(testComponent is IMocked<ITestComponent>); } [Test] public void ResolveUnregisteredInterfaceReturnsMock() { var factory = GetAutoMockContainer(new MockFactory(MockBehavior.Loose)); var service = factory.Resolve<IServiceA>(); Assert.IsNotNull(service); Assert.IsTrue(service is IMocked<IServiceA>); } [Test] public void DefaultConstructorWorksWithAllTests() { var factory = GetAutoMockContainer(new MockFactory(MockBehavior.Loose)); var a = false; var b = false; factory.GetMock<IServiceA>().Setup(x => x.RunA()).Callback(() => a = true); factory.GetMock<IServiceB>().Setup(x => x.RunB()).Callback(() => b = true); var component = factory.Resolve<TestComponent>(); component.RunAll(); Assert.IsTrue(a); Assert.IsTrue(b); } [Test] public void ThrowsIfStrictMockWithoutExpectation() { var factory = GetAutoMockContainer(new MockFactory(MockBehavior.Strict)); factory.GetMock<IServiceB>().Setup(x => x.RunB()); var component = factory.Resolve<TestComponent>(); Assert.ShouldThrow(typeof(MockException), component.RunAll); } [Test] public void StrictWorksWithAllExpectationsMet() { var factory = GetAutoMockContainer(new MockFactory(MockBehavior.Strict)); factory.GetMock<IServiceA>().Setup(x => x.RunA()); factory.GetMock<IServiceB>().Setup(x => x.RunB()); var component = factory.Resolve<TestComponent>(); component.RunAll(); } [Test] public void GetMockedInstanceOfConcreteClass() { var factory = GetAutoMockContainer(new MockFactory(MockBehavior.Loose)); var mockedInstance = factory.GetMock<TestComponent>(); Assert.IsNotNull(mockedInstance); Assert.IsNotNull(mockedInstance.Object.ServiceA); Assert.IsNotNull(mockedInstance.Object.ServiceB); } [Test] public void GetMockedInstanceOfConcreteClassWithInterfaceConstructorParameter() { var factory = GetAutoMockContainer(new MockFactory(MockBehavior.Loose)); var mockedInstance = factory.GetMock<TestComponent>(); Assert.IsNotNull(mockedInstance); } [Test] public void WhenMockedInstanceIsRetrievedAnyFutureResolvesOfTheSameConcreteClassShouldReturnedTheMockedInstance() { var factory = GetAutoMockContainer(new MockFactory(MockBehavior.Loose)); var mockedInstance = factory.GetMock<TestComponent>(); var resolvedInstance = factory.Resolve<TestComponent>(); Assert.IsTrue(Object.ReferenceEquals(resolvedInstance, mockedInstance.Object)); } [Test] public void ShouldBeAbleToGetMockedInstanceOfAbstractClass() { var factory = new UnityAutoMockContainer(); var mock = factory.GetMock<AbstractTestComponent>(); Assert.IsNotNull(mock); } public interface IServiceA { void RunA(); } public interface IServiceB { void RunB(); } public class ServiceA : IServiceA { public ServiceA() { } public ServiceA(int count) { Count = count; } public ServiceA(IServiceB b) { ServiceB = b; } public IServiceB ServiceB { get; private set; } public int Count { get; private set; } public string Value { get; set; } public void RunA() { } } public interface ITestComponent { void RunAll(); IServiceA ServiceA { get; } IServiceB ServiceB { get; } } public abstract class AbstractTestComponent { private readonly IServiceA _serviceA; private readonly IServiceB _serviceB; protected AbstractTestComponent(IServiceA serviceA, IServiceB serviceB) { _serviceA = serviceA; _serviceB = serviceB; } public abstract void RunAll(); public IServiceA ServiceA { get { return _serviceA; } } public IServiceB ServiceB { get { return _serviceB; } } } public class TestComponent : ITestComponent { public TestComponent(IServiceA serviceA, IServiceB serviceB) { ServiceA = serviceA; ServiceB = serviceB; } public IServiceA ServiceA { get; private set; } public IServiceB ServiceB { get; private set; } public void RunAll() { ServiceA.RunA(); ServiceB.RunB(); } } } [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] public class TestAttribute : Attribute { } internal static class Assert { public static void IsNotNull(object component) { Debug.Assert(component != null); } private static void IsNotNull(object component, string message) { Debug.Assert(component != null, message); } public static void IsFalse(bool condition) { Debug.Assert(condition == false); } public static void IsTrue(bool condition) { Debug.Assert(condition); } public static void ShouldThrow(Type exceptionType, Action method) { Exception exception = GetException(method); IsNotNull(exception, string.Format("Exception of type[{0}] was not thrown.", exceptionType.FullName)); Debug.Assert(exceptionType == exception.GetType()); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private static Exception GetException(Action method) { Exception exception = null; try { method(); } catch (Exception e) { exception = e; } return exception; } } } }
// 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.ObjectModel; using System.Runtime; using System.Runtime.Serialization; using System.Xml; using System.Xml.Serialization; using System.Runtime.CompilerServices; using System.Diagnostics; namespace System.ServiceModel.Syndication { // sealed because the ctor results in a call to the virtual InsertItem method public sealed class SyndicationElementExtensionCollection : Collection<SyndicationElementExtension> { private XmlBuffer _buffer; private bool _initialized; internal SyndicationElementExtensionCollection() : this((XmlBuffer)null) { } internal SyndicationElementExtensionCollection(XmlBuffer buffer) : base() { _buffer = buffer; if (_buffer != null) { PopulateElements(); } _initialized = true; } internal SyndicationElementExtensionCollection(SyndicationElementExtensionCollection source) : base() { _buffer = source._buffer; for (int i = 0; i < source.Items.Count; ++i) { base.Add(source.Items[i]); } _initialized = true; } public void Add(object extension) { if (extension is SyndicationElementExtension) { base.Add((SyndicationElementExtension)extension); } else { this.Add(extension, (DataContractSerializer)null); } } public void Add(string outerName, string outerNamespace, object dataContractExtension) { this.Add(outerName, outerNamespace, dataContractExtension, null); } public void Add(object dataContractExtension, DataContractSerializer serializer) { this.Add(null, null, dataContractExtension, serializer); } public void Add(string outerName, string outerNamespace, object dataContractExtension, XmlObjectSerializer dataContractSerializer) { if (dataContractExtension == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dataContractExtension"); } if (dataContractSerializer == null) { dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType()); } base.Add(new SyndicationElementExtension(outerName, outerNamespace, dataContractExtension, dataContractSerializer)); } public void Add(object xmlSerializerExtension, XmlSerializer serializer) { if (xmlSerializerExtension == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("xmlSerializerExtension"); } if (serializer == null) { serializer = new XmlSerializer(xmlSerializerExtension.GetType()); } base.Add(new SyndicationElementExtension(xmlSerializerExtension, serializer)); } public void Add(XmlReader xmlReader) { if (xmlReader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("xmlReader"); } base.Add(new SyndicationElementExtension(xmlReader)); } public XmlReader GetReaderAtElementExtensions() { XmlBuffer extensionsBuffer = GetOrCreateBufferOverExtensions(); XmlReader reader = extensionsBuffer.GetReader(0); reader.ReadStartElement(); return reader; } public Collection<TExtension> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace) { return ReadElementExtensions<TExtension>(extensionName, extensionNamespace, new DataContractSerializer(typeof(TExtension))); } public Collection<TExtension> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace, XmlObjectSerializer serializer) { if (serializer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer"); } return ReadExtensions<TExtension>(extensionName, extensionNamespace, serializer, null); } public Collection<TExtension> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace, XmlSerializer serializer) { if (serializer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer"); } return ReadExtensions<TExtension>(extensionName, extensionNamespace, null, serializer); } internal void WriteTo(XmlWriter writer) { if (_buffer != null) { using (XmlDictionaryReader reader = _buffer.GetReader(0)) { reader.ReadStartElement(); while (reader.IsStartElement()) { writer.WriteNode(reader, false); } } } else { for (int i = 0; i < this.Items.Count; ++i) { this.Items[i].WriteTo(writer); } } } protected override void ClearItems() { base.ClearItems(); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) { _buffer = null; } } protected override void InsertItem(int index, SyndicationElementExtension item) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); } base.InsertItem(index, item); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) { _buffer = null; } } protected override void RemoveItem(int index) { base.RemoveItem(index); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) { _buffer = null; } } protected override void SetItem(int index, SyndicationElementExtension item) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); } base.SetItem(index, item); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) { _buffer = null; } } private XmlBuffer GetOrCreateBufferOverExtensions() { if (_buffer != null) { return _buffer; } XmlBuffer newBuffer = new XmlBuffer(int.MaxValue); using (XmlWriter writer = newBuffer.OpenSection(XmlDictionaryReaderQuotas.Max)) { writer.WriteStartElement(Rss20Constants.ExtensionWrapperTag); for (int i = 0; i < this.Count; ++i) { this[i].WriteTo(writer); } writer.WriteEndElement(); } newBuffer.CloseSection(); newBuffer.Close(); _buffer = newBuffer; return newBuffer; } private void PopulateElements() { using (XmlDictionaryReader reader = _buffer.GetReader(0)) { reader.ReadStartElement(); int index = 0; while (reader.IsStartElement()) { base.Add(new SyndicationElementExtension(_buffer, index, reader.LocalName, reader.NamespaceURI)); reader.Skip(); ++index; } } } private Collection<TExtension> ReadExtensions<TExtension>(string extensionName, string extensionNamespace, XmlObjectSerializer dcSerializer, XmlSerializer xmlSerializer) { if (string.IsNullOrEmpty(extensionName)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.ExtensionNameNotSpecified)); } Debug.Assert((dcSerializer == null) != (xmlSerializer == null), "exactly one serializer should be supplied"); // normalize the null and empty namespace if (extensionNamespace == null) { extensionNamespace = string.Empty; } Collection<TExtension> results = new Collection<TExtension>(); for (int i = 0; i < this.Count; ++i) { if (extensionName != this[i].OuterName || extensionNamespace != this[i].OuterNamespace) { continue; } if (dcSerializer != null) { results.Add(this[i].GetObject<TExtension>(dcSerializer)); } else { results.Add(this[i].GetObject<TExtension>(xmlSerializer)); } } return results; } } }