context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System.Collections.Generic; using System.Globalization; using SKON.Internal.Utils; #region LICENSE // -------------------------------------------------------------------------------------------------------------------- // <copyright file="Parser.cs" company="SpaceKrakens"> // MIT License // Copyright (c) 2016 SpaceKrakens // </copyright> // -------------------------------------------------------------------------------------------------------------------- #endregion using System; namespace SKON.Internal { public class Parser { public const int _EOF = 0; public const int _dash = 1; public const int _colon = 2; public const int _comma = 3; public const int _lbrace = 4; public const int _rbrace = 5; public const int _lbracket = 6; public const int _rbracket = 7; public const int _ident = 8; public const int _version = 9; public const int _docver = 10; public const int _skema = 11; public const int _string_ = 12; public const int _badString = 13; public const int _integer_ = 14; public const int _float_ = 15; public const int _datetime_ = 16; public const int maxT = 19; const bool _T = true; const bool _x = false; const int minErrDist = 2; public Scanner scanner; public Errors errors; public Token t; // last recognized token public Token la; // lookahead token int errDist = minErrDist; public SKONMetadata metadata = new SKONMetadata(); public SKONObject data = new SKONObject(); private string[] dateTimeFormats = { "yyyy-MM-dd", "hh:mm:ssZ", "hh:mm:ss.fffZ", "hh:mm:sszzz", "hh:mm:ss.fffzzz", "yyyy-MM-ddThh:mm:ssZ", "yyyy-MM-ddThh:mm:ss.fffZ", "yyyy-MM-ddThh:mm:sszzz", "yyyy-MM-ddThh:mm:ss.fffzzz" }; private DateTime ParseDatetime(string value) { DateTime dateTime; if (DateTime.TryParseExact(value, dateTimeFormats, null, DateTimeStyles.None, out dateTime)) { return dateTime; } else { errors.errorStream.WriteLine("Could not parse DateTime: " + value); errors.count++; return default(DateTime); } } /*-------------------------------------------------------------------------*/ public Parser(Scanner scanner) { this.scanner = scanner; errors = new Errors(); } void SynErr (int n) { if (errDist >= minErrDist) errors.SynErr(la.line, la.col, n); errDist = 0; } public void SemErr (string msg) { if (errDist >= minErrDist) errors.SemErr(t.line, t.col, msg); errDist = 0; } void Get () { for (;;) { t = la; la = scanner.Scan(); if (la.kind <= maxT) { ++errDist; break; } la = t; } } void Expect (int n) { if (la.kind==n) Get(); else { SynErr(n); } } bool StartOf (int s) { return set[s, la.kind]; } void ExpectWeak (int n, int follow) { if (la.kind == n) Get(); else { SynErr(n); while (!StartOf(follow)) Get(); } } bool WeakSeparator(int n, int syFol, int repFol) { int kind = la.kind; if (kind == n) {Get(); return true;} else if (StartOf(repFol)) {return false;} else { SynErr(n); while (!(set[syFol, kind] || set[repFol, kind] || set[0, kind])) { Get(); kind = la.kind; } return StartOf(syFol); } } void SKON() { Dictionary<string, SKONObject> mapElements = new Dictionary<string, SKONObject>(); int version; string docVersion; string skema; meta_version(out version); metadata.LanguageVersion = version; meta_docVersion(out docVersion); metadata.DocuemntVersion = docVersion; if (la.kind == 11) { meta_SKEMA(out skema); metadata.SKEMA = skema; } open_map(out mapElements); this.data = new SKONObject(mapElements); } void meta_version(out int ver) { Expect(9); Expect(2); Expect(14); if (int.TryParse(t.val, out ver) == false) ver = -1; Expect(1); } void meta_docVersion(out string ver) { Expect(10); Expect(2); Expect(12); if (t.val.Length > 2) ver = ParserUtils.EscapeString(t.val.Substring(1, t.val.Length - 2)); else ver = "INVALID"; Expect(1); } void meta_SKEMA(out string skema) { Expect(11); Expect(2); Expect(12); if (t.val.Length > 2) skema = ParserUtils.EscapeString(t.val.Substring(1, t.val.Length - 2)); else skema = "INVALID"; Expect(1); } void open_map(out Dictionary<string, SKONObject> mapElements ) { string key; SKONObject value; mapElements = new Dictionary<string, SKONObject>(); while (la.kind == 8) { map_element(out key, out value); mapElements[key] = value; ExpectWeak(3, 1); } } void skon_map(out SKONObject map) { Dictionary<string, SKONObject> mapElements; Expect(4); open_map(out mapElements); map = new SKONObject(mapElements); Expect(5); } void skon_array(out SKONObject array) { List<SKONObject> arrayElements; Expect(6); open_array(out arrayElements); array = new SKONObject(arrayElements); Expect(7); } void open_array(out List<SKONObject> arrayElements ) { SKONObject skonObject; arrayElements = new List<SKONObject>(); while (StartOf(2)) { value(out skonObject); arrayElements.Add(skonObject); ExpectWeak(3, 3); } } void map_element(out string key, out SKONObject obj) { string name; SKONObject skonObject; Ident(out name); key = name; Expect(2); value(out skonObject); obj = skonObject; } void Ident(out string name) { Expect(8); name = t.val; } void value(out SKONObject skonObject) { skonObject = null; switch (la.kind) { case 12: { Get(); skonObject = new SKONObject(ParserUtils.EscapeString(t.val.Substring(1, t.val.Length - 2))); break; } case 14: { Get(); skonObject = new SKONObject(int.Parse(t.val)); break; } case 15: { Get(); skonObject = new SKONObject(double.Parse(t.val, CultureInfo.InvariantCulture)); break; } case 16: { Get(); skonObject = new SKONObject(ParseDatetime(t.val)); break; } case 4: { skon_map(out skonObject); break; } case 6: { skon_array(out skonObject); break; } case 17: { Get(); skonObject = new SKONObject(true); break; } case 18: { Get(); skonObject = new SKONObject(false); break; } default: SynErr(20); break; } } public void Parse() { la = new Token(); la.val = ""; Get(); SKON(); Expect(0); } static readonly bool[,] set = { {_T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x}, {_T,_x,_x,_x, _x,_T,_x,_x, _T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x}, {_x,_x,_x,_x, _T,_x,_T,_x, _x,_x,_x,_x, _T,_x,_T,_T, _T,_T,_T,_x, _x}, {_T,_x,_x,_x, _T,_x,_T,_T, _x,_x,_x,_x, _T,_x,_T,_T, _T,_T,_T,_x, _x} }; } // end Parser public class Errors { public int count = 0; // number of errors detected public System.IO.TextWriter errorStream = Console.Out; // error messages go to this stream public string errMsgFormat = "-- line {0} col {1}: {2}"; // 0=line, 1=column, 2=text public virtual void SynErr (int line, int col, int n) { string s; switch (n) { case 0: s = "EOF expected"; break; case 1: s = "dash expected"; break; case 2: s = "colon expected"; break; case 3: s = "comma expected"; break; case 4: s = "lbrace expected"; break; case 5: s = "rbrace expected"; break; case 6: s = "lbracket expected"; break; case 7: s = "rbracket expected"; break; case 8: s = "ident expected"; break; case 9: s = "version expected"; break; case 10: s = "docver expected"; break; case 11: s = "skema expected"; break; case 12: s = "string_ expected"; break; case 13: s = "badString expected"; break; case 14: s = "integer_ expected"; break; case 15: s = "float_ expected"; break; case 16: s = "datetime_ expected"; break; case 17: s = "\"true\" expected"; break; case 18: s = "\"false\" expected"; break; case 19: s = "??? expected"; break; case 20: s = "invalid value"; break; default: s = "error " + n; break; } errorStream.WriteLine(errMsgFormat, line, col, s); count++; } public virtual void SemErr (int line, int col, string s) { errorStream.WriteLine(errMsgFormat, line, col, s); count++; } public virtual void SemErr (string s) { errorStream.WriteLine(s); count++; } public virtual void Warning (int line, int col, string s) { errorStream.WriteLine(errMsgFormat, line, col, s); } public virtual void Warning(string s) { errorStream.WriteLine(s); } } // Errors public class FatalError: Exception { public FatalError(string m): base(m) {} } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; using System.Globalization; #if HAVE_BIG_INTEGER using System.Numerics; #endif using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data. /// </summary> public partial class JTokenWriter : JsonWriter { private JContainer? _token; private JContainer? _parent; // used when writer is writing single value and the value has no containing parent private JValue? _value; private JToken? _current; /// <summary> /// Gets the <see cref="JToken"/> at the writer's current position. /// </summary> public JToken? CurrentToken => _current; /// <summary> /// Gets the token being written. /// </summary> /// <value>The token being written.</value> public JToken? Token { get { if (_token != null) { return _token; } return _value; } } /// <summary> /// Initializes a new instance of the <see cref="JTokenWriter"/> class writing to the given <see cref="JContainer"/>. /// </summary> /// <param name="container">The container being written to.</param> public JTokenWriter(JContainer container) { ValidationUtils.ArgumentNotNull(container, nameof(container)); _token = container; _parent = container; } /// <summary> /// Initializes a new instance of the <see cref="JTokenWriter"/> class. /// </summary> public JTokenWriter() { } /// <summary> /// Flushes whatever is in the buffer to the underlying <see cref="JContainer"/>. /// </summary> public override void Flush() { } /// <summary> /// Closes this writer. /// If <see cref="JsonWriter.AutoCompleteOnClose"/> is set to <c>true</c>, the JSON is auto-completed. /// </summary> /// <remarks> /// Setting <see cref="JsonWriter.CloseOutput"/> to <c>true</c> has no additional effect, since the underlying <see cref="JContainer"/> is a type that cannot be closed. /// </remarks> public override void Close() { base.Close(); } /// <summary> /// Writes the beginning of a JSON object. /// </summary> public override void WriteStartObject() { base.WriteStartObject(); AddParent(new JObject()); } private void AddParent(JContainer container) { if (_parent == null) { _token = container; } else { _parent.AddAndSkipParentCheck(container); } _parent = container; _current = container; } private void RemoveParent() { _current = _parent; _parent = _parent!.Parent; if (_parent != null && _parent.Type == JTokenType.Property) { _parent = _parent.Parent; } } /// <summary> /// Writes the beginning of a JSON array. /// </summary> public override void WriteStartArray() { base.WriteStartArray(); AddParent(new JArray()); } /// <summary> /// Writes the start of a constructor with the given name. /// </summary> /// <param name="name">The name of the constructor.</param> public override void WriteStartConstructor(string name) { base.WriteStartConstructor(name); AddParent(new JConstructor(name)); } /// <summary> /// Writes the end. /// </summary> /// <param name="token">The token.</param> protected override void WriteEnd(JsonToken token) { RemoveParent(); } /// <summary> /// Writes the property name of a name/value pair on a JSON object. /// </summary> /// <param name="name">The name of the property.</param> public override void WritePropertyName(string name) { // avoid duplicate property name exception // last property name wins (_parent as JObject)?.Remove(name); AddParent(new JProperty(name)); // don't set state until after in case of an error // incorrect state will cause issues if writer is disposed when closing open properties base.WritePropertyName(name); } private void AddValue(object? value, JsonToken token) { AddValue(new JValue(value), token); } internal void AddValue(JValue? value, JsonToken token) { if (_parent != null) { // TryAdd will return false if an invalid JToken type is added. // For example, a JComment can't be added to a JObject. // If there is an invalid JToken type then skip it. if (_parent.TryAdd(value)) { _current = _parent.Last; if (_parent.Type == JTokenType.Property) { _parent = _parent.Parent; } } } else { _value = value ?? JValue.CreateNull(); _current = _value; } } #region WriteValue methods /// <summary> /// Writes a <see cref="Object"/> value. /// An error will be raised if the value cannot be written as a single JSON token. /// </summary> /// <param name="value">The <see cref="Object"/> value to write.</param> public override void WriteValue(object? value) { #if HAVE_BIG_INTEGER if (value is BigInteger) { InternalWriteValue(JsonToken.Integer); AddValue(value, JsonToken.Integer); } else #endif { base.WriteValue(value); } } /// <summary> /// Writes a null value. /// </summary> public override void WriteNull() { base.WriteNull(); AddValue(null, JsonToken.Null); } /// <summary> /// Writes an undefined value. /// </summary> public override void WriteUndefined() { base.WriteUndefined(); AddValue(null, JsonToken.Undefined); } /// <summary> /// Writes raw JSON. /// </summary> /// <param name="json">The raw JSON to write.</param> public override void WriteRaw(string? json) { base.WriteRaw(json); AddValue(new JRaw(json), JsonToken.Raw); } /// <summary> /// Writes a comment <c>/*...*/</c> containing the specified text. /// </summary> /// <param name="text">Text to place inside the comment.</param> public override void WriteComment(string? text) { base.WriteComment(text); AddValue(JValue.CreateComment(text), JsonToken.Comment); } /// <summary> /// Writes a <see cref="String"/> value. /// </summary> /// <param name="value">The <see cref="String"/> value to write.</param> public override void WriteValue(string? value) { base.WriteValue(value); AddValue(value, JsonToken.String); } /// <summary> /// Writes a <see cref="Int32"/> value. /// </summary> /// <param name="value">The <see cref="Int32"/> value to write.</param> public override void WriteValue(int value) { base.WriteValue(value); AddValue(value, JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt32"/> value. /// </summary> /// <param name="value">The <see cref="UInt32"/> value to write.</param> [CLSCompliant(false)] public override void WriteValue(uint value) { base.WriteValue(value); AddValue(value, JsonToken.Integer); } /// <summary> /// Writes a <see cref="Int64"/> value. /// </summary> /// <param name="value">The <see cref="Int64"/> value to write.</param> public override void WriteValue(long value) { base.WriteValue(value); AddValue(value, JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt64"/> value. /// </summary> /// <param name="value">The <see cref="UInt64"/> value to write.</param> [CLSCompliant(false)] public override void WriteValue(ulong value) { base.WriteValue(value); AddValue(value, JsonToken.Integer); } /// <summary> /// Writes a <see cref="Single"/> value. /// </summary> /// <param name="value">The <see cref="Single"/> value to write.</param> public override void WriteValue(float value) { base.WriteValue(value); AddValue(value, JsonToken.Float); } /// <summary> /// Writes a <see cref="Double"/> value. /// </summary> /// <param name="value">The <see cref="Double"/> value to write.</param> public override void WriteValue(double value) { base.WriteValue(value); AddValue(value, JsonToken.Float); } /// <summary> /// Writes a <see cref="Boolean"/> value. /// </summary> /// <param name="value">The <see cref="Boolean"/> value to write.</param> public override void WriteValue(bool value) { base.WriteValue(value); AddValue(value, JsonToken.Boolean); } /// <summary> /// Writes a <see cref="Int16"/> value. /// </summary> /// <param name="value">The <see cref="Int16"/> value to write.</param> public override void WriteValue(short value) { base.WriteValue(value); AddValue(value, JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt16"/> value. /// </summary> /// <param name="value">The <see cref="UInt16"/> value to write.</param> [CLSCompliant(false)] public override void WriteValue(ushort value) { base.WriteValue(value); AddValue(value, JsonToken.Integer); } /// <summary> /// Writes a <see cref="Char"/> value. /// </summary> /// <param name="value">The <see cref="Char"/> value to write.</param> public override void WriteValue(char value) { base.WriteValue(value); string s; #if HAVE_CHAR_TO_STRING_WITH_CULTURE s = value.ToString(CultureInfo.InvariantCulture); #else s = value.ToString(); #endif AddValue(s, JsonToken.String); } /// <summary> /// Writes a <see cref="Byte"/> value. /// </summary> /// <param name="value">The <see cref="Byte"/> value to write.</param> public override void WriteValue(byte value) { base.WriteValue(value); AddValue(value, JsonToken.Integer); } /// <summary> /// Writes a <see cref="SByte"/> value. /// </summary> /// <param name="value">The <see cref="SByte"/> value to write.</param> [CLSCompliant(false)] public override void WriteValue(sbyte value) { base.WriteValue(value); AddValue(value, JsonToken.Integer); } /// <summary> /// Writes a <see cref="Decimal"/> value. /// </summary> /// <param name="value">The <see cref="Decimal"/> value to write.</param> public override void WriteValue(decimal value) { base.WriteValue(value); AddValue(value, JsonToken.Float); } /// <summary> /// Writes a <see cref="DateTime"/> value. /// </summary> /// <param name="value">The <see cref="DateTime"/> value to write.</param> public override void WriteValue(DateTime value) { base.WriteValue(value); value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling); AddValue(value, JsonToken.Date); } #if HAVE_DATE_TIME_OFFSET /// <summary> /// Writes a <see cref="DateTimeOffset"/> value. /// </summary> /// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param> public override void WriteValue(DateTimeOffset value) { base.WriteValue(value); AddValue(value, JsonToken.Date); } #endif /// <summary> /// Writes a <see cref="Byte"/>[] value. /// </summary> /// <param name="value">The <see cref="Byte"/>[] value to write.</param> public override void WriteValue(byte[]? value) { base.WriteValue(value); AddValue(value, JsonToken.Bytes); } /// <summary> /// Writes a <see cref="TimeSpan"/> value. /// </summary> /// <param name="value">The <see cref="TimeSpan"/> value to write.</param> public override void WriteValue(TimeSpan value) { base.WriteValue(value); AddValue(value, JsonToken.String); } /// <summary> /// Writes a <see cref="Guid"/> value. /// </summary> /// <param name="value">The <see cref="Guid"/> value to write.</param> public override void WriteValue(Guid value) { base.WriteValue(value); AddValue(value, JsonToken.String); } /// <summary> /// Writes a <see cref="Uri"/> value. /// </summary> /// <param name="value">The <see cref="Uri"/> value to write.</param> public override void WriteValue(Uri? value) { base.WriteValue(value); AddValue(value, JsonToken.String); } #endregion internal override void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate, bool writeComments) { // cloning the token rather than reading then writing it doesn't lose some type information, e.g. Guid, byte[], etc if (reader is JTokenReader tokenReader && writeChildren && writeDateConstructorAsDate && writeComments) { if (tokenReader.TokenType == JsonToken.None) { if (!tokenReader.Read()) { return; } } JToken value = tokenReader.CurrentToken!.CloneToken(); if (_parent != null) { _parent.Add(value); _current = _parent.Last; // if the writer was in a property then move out of it and up to its parent object if (_parent.Type == JTokenType.Property) { _parent = _parent.Parent; InternalWriteValue(JsonToken.Null); } } else { _current = value; if (_token == null && _value == null) { _token = value as JContainer; _value = value as JValue; } } tokenReader.Skip(); } else { base.WriteToken(reader, writeChildren, writeDateConstructorAsDate, writeComments); } } } }
// 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 Internal.Cryptography.Pal.Native; using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography; using NTSTATUS = Interop.BCrypt.NTSTATUS; using SafeBCryptKeyHandle = Microsoft.Win32.SafeHandles.SafeBCryptKeyHandle; using static Interop.Crypt32; namespace Internal.Cryptography.Pal { /// <summary> /// A singleton class that encapsulates the native implementation of various X509 services. (Implementing this as a singleton makes it /// easier to split the class into abstract and implementation classes if desired.) /// </summary> internal sealed partial class X509Pal : IX509Pal { private const string BCRYPT_ECC_CURVE_NAME_PROPERTY = "ECCCurveName"; private const string BCRYPT_ECC_PARAMETERS_PROPERTY = "ECCParameters"; public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters, ICertificatePal certificatePal) { if (oid.Value == Oids.EcPublicKey && certificatePal != null) { return DecodeECDsaPublicKey((CertificatePal)certificatePal); } int algId = Interop.Crypt32.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, oid.Value, OidGroup.PublicKeyAlgorithm, fallBackToAllGroups: true).AlgId; switch (algId) { case AlgId.CALG_RSA_KEYX: case AlgId.CALG_RSA_SIGN: { byte[] keyBlob = DecodeKeyBlob(CryptDecodeObjectStructType.CNG_RSA_PUBLIC_KEY_BLOB, encodedKeyValue); CngKey cngKey = CngKey.Import(keyBlob, CngKeyBlobFormat.GenericPublicBlob); return new RSACng(cngKey); } case AlgId.CALG_DSS_SIGN: { byte[] keyBlob = ConstructDSSPublicKeyCspBlob(encodedKeyValue, encodedParameters); DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(); dsa.ImportCspBlob(keyBlob); return dsa; } default: throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } } private static ECDsa DecodeECDsaPublicKey(CertificatePal certificatePal) { ECDsa ecdsa; using (SafeBCryptKeyHandle bCryptKeyHandle = ImportPublicKeyInfo(certificatePal.CertContext)) { CngKeyBlobFormat blobFormat; byte[] keyBlob; string curveName = GetCurveName(bCryptKeyHandle); if (curveName == null) { if (HasExplicitParameters(bCryptKeyHandle)) { blobFormat = CngKeyBlobFormat.EccFullPublicBlob; } else { blobFormat = CngKeyBlobFormat.EccPublicBlob; } keyBlob = ExportKeyBlob(bCryptKeyHandle, blobFormat); using (CngKey cngKey = CngKey.Import(keyBlob, blobFormat)) { ecdsa = new ECDsaCng(cngKey); } } else { blobFormat = CngKeyBlobFormat.EccPublicBlob; keyBlob = ExportKeyBlob(bCryptKeyHandle, blobFormat); ECParameters ecparams = new ECParameters(); ExportNamedCurveParameters(ref ecparams, keyBlob, false); ecparams.Curve = ECCurve.CreateFromFriendlyName(curveName); ecdsa = new ECDsaCng(); ecdsa.ImportParameters(ecparams); } } return ecdsa; } private static SafeBCryptKeyHandle ImportPublicKeyInfo(SafeCertContextHandle certContext) { unsafe { SafeBCryptKeyHandle bCryptKeyHandle; bool mustRelease = false; certContext.DangerousAddRef(ref mustRelease); try { unsafe { bool success = Interop.crypt32.CryptImportPublicKeyInfoEx2(CertEncodingType.X509_ASN_ENCODING, &(certContext.CertContext->pCertInfo->SubjectPublicKeyInfo), 0, null, out bCryptKeyHandle); if (!success) throw Marshal.GetHRForLastWin32Error().ToCryptographicException(); return bCryptKeyHandle; } } finally { if (mustRelease) certContext.DangerousRelease(); } } } private static byte[] ExportKeyBlob(SafeBCryptKeyHandle bCryptKeyHandle, CngKeyBlobFormat blobFormat) { string blobFormatString = blobFormat.Format; int numBytesNeeded = 0; NTSTATUS ntStatus = Interop.BCrypt.BCryptExportKey(bCryptKeyHandle, IntPtr.Zero, blobFormatString, null, 0, out numBytesNeeded, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw new CryptographicException(Interop.Kernel32.GetMessage((int)ntStatus)); byte[] keyBlob = new byte[numBytesNeeded]; ntStatus = Interop.BCrypt.BCryptExportKey(bCryptKeyHandle, IntPtr.Zero, blobFormatString, keyBlob, keyBlob.Length, out numBytesNeeded, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw new CryptographicException(Interop.Kernel32.GetMessage((int)ntStatus)); Array.Resize(ref keyBlob, numBytesNeeded); return keyBlob; } private static void ExportNamedCurveParameters(ref ECParameters ecParams, byte[] ecBlob, bool includePrivateParameters) { // We now have a buffer laid out as follows: // BCRYPT_ECCKEY_BLOB header // byte[cbKey] Q.X // byte[cbKey] Q.Y // -- Private only -- // byte[cbKey] D unsafe { Debug.Assert(ecBlob.Length >= sizeof(Interop.BCrypt.BCRYPT_ECCKEY_BLOB)); fixed (byte* pEcBlob = &ecBlob[0]) { Interop.BCrypt.BCRYPT_ECCKEY_BLOB* pBcryptBlob = (Interop.BCrypt.BCRYPT_ECCKEY_BLOB*)pEcBlob; int offset = sizeof(Interop.BCrypt.BCRYPT_ECCKEY_BLOB); ecParams.Q = new ECPoint { X = Interop.BCrypt.Consume(ecBlob, ref offset, pBcryptBlob->cbKey), Y = Interop.BCrypt.Consume(ecBlob, ref offset, pBcryptBlob->cbKey) }; if (includePrivateParameters) { ecParams.D = Interop.BCrypt.Consume(ecBlob, ref offset, pBcryptBlob->cbKey); } } } } private static byte[] DecodeKeyBlob(CryptDecodeObjectStructType lpszStructType, byte[] encodedKeyValue) { int cbDecoded = 0; if (!Interop.crypt32.CryptDecodeObject(CertEncodingType.All, lpszStructType, encodedKeyValue, encodedKeyValue.Length, CryptDecodeObjectFlags.None, null, ref cbDecoded)) throw Marshal.GetLastWin32Error().ToCryptographicException(); byte[] keyBlob = new byte[cbDecoded]; if (!Interop.crypt32.CryptDecodeObject(CertEncodingType.All, lpszStructType, encodedKeyValue, encodedKeyValue.Length, CryptDecodeObjectFlags.None, keyBlob, ref cbDecoded)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return keyBlob; } private static byte[] ConstructDSSPublicKeyCspBlob(byte[] encodedKeyValue, byte[] encodedParameters) { byte[] decodedKeyValue = DecodeDssKeyValue(encodedKeyValue); byte[] p, q, g; DecodeDssParameters(encodedParameters, out p, out q, out g); const byte PUBLICKEYBLOB = 0x6; const byte CUR_BLOB_VERSION = 2; int cbKey = p.Length; if (cbKey == 0) throw ErrorCode.NTE_BAD_PUBLIC_KEY.ToCryptographicException(); const int DSS_Q_LEN = 20; int capacity = 8 /* sizeof(CAPI.BLOBHEADER) */ + 8 /* sizeof(CAPI.DSSPUBKEY) */ + cbKey + DSS_Q_LEN + cbKey + cbKey + 24 /* sizeof(CAPI.DSSSEED) */; MemoryStream keyBlob = new MemoryStream(capacity); BinaryWriter bw = new BinaryWriter(keyBlob); // PUBLICKEYSTRUC bw.Write((byte)PUBLICKEYBLOB); // pPubKeyStruc->bType = PUBLICKEYBLOB bw.Write((byte)CUR_BLOB_VERSION); // pPubKeyStruc->bVersion = CUR_BLOB_VERSION bw.Write((short)0); // pPubKeyStruc->reserved = 0; bw.Write((uint)AlgId.CALG_DSS_SIGN); // pPubKeyStruc->aiKeyAlg = CALG_DSS_SIGN; // DSSPUBKEY bw.Write((int)(PubKeyMagic.DSS_MAGIC)); // pCspPubKey->magic = DSS_MAGIC; We are constructing a DSS1 Csp blob. bw.Write((int)(cbKey * 8)); // pCspPubKey->bitlen = cbKey * 8; // rgbP[cbKey] bw.Write(p); // rgbQ[20] int cb = q.Length; if (cb == 0 || cb > DSS_Q_LEN) throw ErrorCode.NTE_BAD_PUBLIC_KEY.ToCryptographicException(); bw.Write(q); if (DSS_Q_LEN > cb) bw.Write(new byte[DSS_Q_LEN - cb]); // rgbG[cbKey] cb = g.Length; if (cb == 0 || cb > cbKey) throw ErrorCode.NTE_BAD_PUBLIC_KEY.ToCryptographicException(); bw.Write(g); if (cbKey > cb) bw.Write(new byte[cbKey - cb]); // rgbY[cbKey] cb = decodedKeyValue.Length; if (cb == 0 || cb > cbKey) throw ErrorCode.NTE_BAD_PUBLIC_KEY.ToCryptographicException(); bw.Write(decodedKeyValue); if (cbKey > cb) bw.Write(new byte[cbKey - cb]); // DSSSEED: set counter to 0xFFFFFFFF to indicate not available bw.Write((uint)0xFFFFFFFF); bw.Write(new byte[20]); return keyBlob.ToArray(); } private static byte[] DecodeDssKeyValue(byte[] encodedKeyValue) { unsafe { byte[] decodedKeyValue = null; encodedKeyValue.DecodeObject( CryptDecodeObjectStructType.X509_DSS_PUBLICKEY, delegate (void* pvDecoded, int cbDecoded) { Debug.Assert(cbDecoded >= sizeof(CRYPTOAPI_BLOB)); CRYPTOAPI_BLOB* pBlob = (CRYPTOAPI_BLOB*)pvDecoded; decodedKeyValue = pBlob->ToByteArray(); } ); return decodedKeyValue; } } private static void DecodeDssParameters(byte[] encodedParameters, out byte[] p, out byte[] q, out byte[] g) { byte[] pLocal = null; byte[] qLocal = null; byte[] gLocal = null; unsafe { encodedParameters.DecodeObject( CryptDecodeObjectStructType.X509_DSS_PARAMETERS, delegate (void* pvDecoded, int cbDecoded) { Debug.Assert(cbDecoded >= sizeof(CERT_DSS_PARAMETERS)); CERT_DSS_PARAMETERS* pCertDssParameters = (CERT_DSS_PARAMETERS*)pvDecoded; pLocal = pCertDssParameters->p.ToByteArray(); qLocal = pCertDssParameters->q.ToByteArray(); gLocal = pCertDssParameters->g.ToByteArray(); } ); } p = pLocal; q = qLocal; g = gLocal; } private static bool HasExplicitParameters(SafeBCryptKeyHandle bcryptHandle) { byte[] explicitParams = GetProperty(bcryptHandle, BCRYPT_ECC_PARAMETERS_PROPERTY); return (explicitParams != null && explicitParams.Length > 0); } private static string GetCurveName(SafeBCryptKeyHandle bcryptHandle) { return GetPropertyAsString(bcryptHandle, BCRYPT_ECC_CURVE_NAME_PROPERTY); } private static string GetPropertyAsString(SafeBCryptKeyHandle cryptHandle, string propertyName) { Debug.Assert(!cryptHandle.IsInvalid); byte[] value = GetProperty(cryptHandle, propertyName); if (value == null || value.Length == 0) return null; unsafe { fixed (byte* pValue = &value[0]) { string valueAsString = Marshal.PtrToStringUni((IntPtr)pValue); return valueAsString; } } } private static byte[] GetProperty(SafeBCryptKeyHandle cryptHandle, string propertyName) { Debug.Assert(!cryptHandle.IsInvalid); unsafe { int numBytesNeeded; NTSTATUS errorCode = Interop.BCrypt.BCryptGetProperty(cryptHandle, propertyName, null, 0, out numBytesNeeded, 0); if (errorCode != NTSTATUS.STATUS_SUCCESS) return null; byte[] propertyValue = new byte[numBytesNeeded]; fixed (byte* pPropertyValue = propertyValue) { errorCode = Interop.BCrypt.BCryptGetProperty(cryptHandle, propertyName, pPropertyValue, propertyValue.Length, out numBytesNeeded, 0); } if (errorCode != NTSTATUS.STATUS_SUCCESS) return null; Array.Resize(ref propertyValue, numBytesNeeded); return propertyValue; } } } }
using System.Collections.Generic; using System.Reflection.Metadata; using Microsoft.CodeAnalysis; using Wyam.Common.Documents; namespace Wyam.CodeAnalysis { /// <summary> /// Common metadata keys for code analysis modules. /// </summary> public static class CodeAnalysisKeys { // Note that if we ever introduce code analysis for other formats (such as Java or CSS), the metadata should be kept as similar as possible /// <summary> /// The name of the assembly for each input document. Used to group input documents by assembly (if provided). If this is /// not provided for each input source document, then analysis that depends on both source files and assemblies may not /// correctly bind symbols across multiple inputs. /// </summary> /// <type><see cref="string"/></type> public const string AssemblyName = nameof(AssemblyName); /// <summary> /// By default only certain symbols are processed as part of the initial /// result set(such as those that match the specified predicate). If this value is <c>true</c>, then this /// symbol was part of the initial result set. If it is <c>false</c>, the symbol was lazily processed later /// while fetching related symbols and may not contain the full set of metadata. /// </summary> /// <type><see cref="bool"/></type> public const string IsResult = nameof(IsResult); /// <summary> /// A unique ID that identifies the symbol (can be used for generating folder paths, for example). /// </summary> /// <type><see cref="string"/></type> public const string SymbolId = nameof(SymbolId); /// <summary> /// The Roslyn <c>ISymbol</c> from which this document is derived. If the document represents a namespace, this metadata might contain more than one /// symbol since the namespaces documents consolidate same-named namespaces across input code and assemblies. /// </summary> /// <type><see cref="ISymbol"/> (or <see cref="IEnumerable{ISymbol}"/> if a namespace)</type> public const string Symbol = nameof(Symbol); /// <summary> /// The name of the symbol, or an empty string if the symbol has no name (like the global namespace). /// </summary> /// <type><see cref="string"/></type> public const string Name = nameof(Name); /// <summary> /// The full name of the symbol. For namespaces, this is the name of the namespace. For types, this includes all generic type parameters. /// </summary> /// <type><see cref="string"/></type> public const string FullName = nameof(FullName); /// <summary> /// The qualified name of the symbol which includes all containing namespaces. /// </summary> /// <type><see cref="string"/></type> public const string QualifiedName = nameof(QualifiedName); /// <summary> /// A display name for the symbol. For namespaces, this is the same as <see cref="QualifiedName"/>. /// For types, this is the same as <see cref="FullName"/>. /// </summary> /// <type><see cref="string"/></type> public const string DisplayName = nameof(DisplayName); /// <summary> /// This is the general kind of symbol. For example, the for a namespace this is "Namespace" and for a type this is "NamedType". /// </summary> /// <type><see cref="string"/></type> public const string Kind = nameof(Kind); /// <summary> /// The more specific kind of the symbol ("Class", "Struct", etc.) This is the same as <c>Kind</c> if there is no more specific kind. /// </summary> /// <type><see cref="string"/></type> public const string SpecificKind = nameof(SpecificKind); /// <summary> /// The document that represents the containing namespace (or null if this symbol is not nested). /// </summary> /// <type><see cref="IDocument"/></type> public const string ContainingNamespace = nameof(ContainingNamespace); /// <summary> /// The document that represents the containing assembly (or null if this symbol is not from an assembly). /// </summary> /// <type><see cref="IDocument"/></type> public const string ContainingAssembly = nameof(ContainingAssembly); /// <summary> /// Indicates if the symbol is static. /// </summary> /// <type><see cref="bool"/></type> public const string IsStatic = nameof(IsStatic); /// <summary> /// Indicates if the symbol is abstract. /// </summary> /// <type><see cref="bool"/></type> public const string IsAbstract = nameof(IsAbstract); /// <summary> /// Indicates if the symbol is virtual. /// </summary> /// <type><see cref="bool"/></type> public const string IsVirtual = nameof(IsVirtual); /// <summary> /// Indicates if the symbol is an override. /// </summary> /// <type><see cref="bool"/></type> public const string IsOverride = nameof(IsOverride); /// <summary> /// A unique ID that identifies the symbol for documentation purposes. /// </summary> /// <type><see cref="string"/></type> public const string CommentId = nameof(CommentId); /// <summary> /// This is available for namespace and type symbols and contains a collection of the documents that represent all member types. /// It only contains direct children (as opposed to all nested types). /// </summary> /// <type><c>IReadOnlyList&lt;IDocument&gt;</c></type> public const string MemberTypes = nameof(MemberTypes); /// <summary> /// This is available for namespace symbols and contains a collection of the documents that represent all member namespaces. /// The collection is empty if there are no member namespaces. /// </summary> /// <type><c>IReadOnlyList&lt;IDocument&gt;</c></type> public const string MemberNamespaces = nameof(MemberNamespaces); /// <summary> /// This is available for type, method, field, event, property, and parameter symbols and contains a document /// representing the containing type(or<c>null</c> if no containing type). /// </summary> /// <type><see cref="IDocument"/></type> public const string ContainingType = nameof(ContainingType); /// <summary> /// This is available for type symbols and contains a collection of the documents that represent all base types (inner-most first). /// </summary> /// <type><c>IReadOnlyList&lt;IDocument&gt;</c></type> public const string BaseTypes = nameof(BaseTypes); /// <summary> /// This is available for type symbols and contains a collection of the documents that represent all implemented interfaces. The collection /// is empty if the type doesn't implement any interfaces. /// </summary> /// <type><c>IReadOnlyList&lt;IDocument&gt;</c></type> public const string AllInterfaces = nameof(AllInterfaces); /// <summary> /// This is available for type symbols and contains a collection of the documents that represent all members of the type, including inherited ones. The collection /// is empty if the type doesn't have any members. /// </summary> /// <type><c>IReadOnlyList&lt;IDocument&gt;</c></type> public const string Members = nameof(Members); /// <summary> /// This is available for type symbols and contains a collection of the documents that represent all operators of the type, including inherited ones. The collection /// is empty if the type doesn't have any operators. /// </summary> /// <type><c>IReadOnlyList&lt;IDocument&gt;</c></type> public const string Operators = nameof(Operators); /// <summary> /// This is available for type symbols and contains a collection of the documents that represent all extension members applicable to the type. /// </summary> /// <type><c>IReadOnlyList&lt;IDocument&gt;</c></type> public const string ExtensionMethods = nameof(ExtensionMethods); /// <summary> /// This is available for type symbols and contains a collection of the documents that represent all types derived from the type. The collection /// is empty if the type doesn't have any derived types. /// </summary> /// <type><c>IReadOnlyList&lt;IDocument&gt;</c></type> public const string DerivedTypes = nameof(DerivedTypes); /// <summary> /// This is available for interface symbols and contains a collection of the documents that represent all types that implement the interface. The collection /// is empty if no other types implement the interface. /// </summary> /// <type><c>IReadOnlyList&lt;IDocument&gt;</c></type> public const string ImplementingTypes = nameof(ImplementingTypes); /// <summary> /// This is available for type symbols and contains a collection of the documents that represent all constructors of the type. The collection /// is empty if the type doesn't have any explicit constructors. /// </summary> /// <type><c>IReadOnlyList&lt;IDocument&gt;</c></type> public const string Constructors = nameof(Constructors); /// <summary> /// This is available for type and method symbols and contains a collection of the documents that represent all generic type parameters of the type or method. The collection /// is empty if the type or method doesn't have any generic type parameters. /// </summary> /// <type><c>IReadOnlyList&lt;IDocument&gt;</c></type> public const string TypeParameters = nameof(TypeParameters); /// <summary> /// This is available for type and method symbols and contains a collection of the documents that represent all generic type arguments of the type or method. The collection /// is empty if the type or method doesn't have any generic type parameters. /// </summary> /// <type><c>IReadOnlyList&lt;IDocument&gt;</c></type> public const string TypeArguments = nameof(TypeArguments); /// <summary> /// This is available for type, method, field, event, and property symbols and contains the declared accessibility of the symbol. /// </summary> /// <type><see cref="string"/></type> public const string Accessibility = nameof(Accessibility); /// <summary> /// This is available for type, method, field, event, property, parameter, and type parameter symbols and contains the type symbol documents for attributes applied to the symbol. /// </summary> /// <type><c>IReadOnlyList&lt;IDocument&gt;</c></type> public const string Attributes = nameof(Attributes); /// <summary> /// This is available for method and property (I.e., indexer) symbols and contains a collection of the documents that represent the parameters of the method or property. /// </summary> /// <type><c>IReadOnlyList&lt;IDocument&gt;</c></type> public const string Parameters = nameof(Parameters); /// <summary> /// This is available for method symbols and contains a document that represents the return type of the method (or <c>null</c> if the method returns <c>void</c>). /// </summary> /// <type><see cref="IDocument"/></type> public const string ReturnType = nameof(ReturnType); /// <summary> /// This is available for method symbols and contains a document that represents the method being overridden (or <c>null</c> if no method is overriden by this one). /// </summary> /// <type><see cref="IDocument"/></type> public const string OverriddenMethod = nameof(OverriddenMethod); /// <summary> /// This is available for field, event, property, and parameter symbols and contains the document that represents the type of the symbol. /// </summary> /// <type><see cref="IDocument"/></type> public const string Type = nameof(Type); /// <summary> /// If this symbol is derived from another symbol, by type substitution for instance, this gets a document representing the original definition. /// If this symbol is not derived from another symbol, this gets a document representing the current definition. /// </summary> /// <type><see cref="IDocument"/></type> public const string OriginalDefinition = nameof(OriginalDefinition); /// <summary> /// This is available for field symbols and indicates whether a constant value is available for the field. /// </summary> /// <type><see cref="bool"/></type> public const string HasConstantValue = nameof(HasConstantValue); /// <summary> /// This is available for field symbols and contains the constant value (if one exists). /// </summary> /// <type><see cref="object"/></type> public const string ConstantValue = nameof(ConstantValue); /// <summary> /// This is available for type parameter symbols and contains a document that represents the declaring type of the type parameter. /// </summary> /// <type><see cref="IDocument"/></type> public const string DeclaringType = nameof(DeclaringType); /// <summary> /// This is available for attribute symbols and contains the Roslyn <see cref="Microsoft.CodeAnalysis.AttributeData"/> instance for the attribute. /// </summary> /// <type><see cref="Microsoft.CodeAnalysis.AttributeData"/></type> public const string AttributeData = nameof(AttributeData); // Documentation keys (not present for external symbols) /// <summary> /// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains /// the full unprocessed XML documentation comments content for this symbol. In addition, special metadata keys /// may be added for custom comment elements with the name <c>[ElementName]Comments</c>. These special metadata /// keys contain a <see cref="OtherComment"/> instance with the rendered HTML content (and any attributes) of the /// custom XML documentation comments with the given <c>[ElementName]</c>. /// </summary> /// <type><see cref="string"/></type> public const string CommentXml = nameof(CommentXml); /// <summary> /// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains /// the rendered HTML content from all<c>example</c> XML documentation comments for this symbol. /// </summary> /// <type><see cref="string"/></type> public const string Example = nameof(Example); /// <summary> /// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains /// the rendered HTML content from all<c>remarks</c> XML documentation comments for this symbol. /// </summary> /// <type><see cref="string"/></type> public const string Remarks = nameof(Remarks); /// <summary> /// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains /// the rendered HTML content from all<c>summary</c> XML documentation comments for this symbol. /// </summary> /// <type><see cref="string"/></type> public const string Summary = nameof(Summary); /// <summary> /// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains /// the rendered HTML content from all<c>returns</c> XML documentation comments for this symbol. /// </summary> /// <type><see cref="string"/></type> public const string Returns = nameof(Returns); /// <summary> /// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains /// the rendered HTML content from all<c>value</c> XML documentation comments for this symbol. /// </summary> /// <type><see cref="string"/></type> public const string Value = nameof(Value); /// <summary> /// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains /// a collection of all<c>exception</c> XML documentation comments for this symbol with their name, link, and/or rendered HTML content. /// </summary> /// <type><see cref="IReadOnlyList{ReferenceComment}"/></type> public const string Exceptions = nameof(Exceptions); /// <summary> /// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains /// a collection of all<c>permission</c> XML documentation comments for this symbol with their name, link, and/or rendered HTML content. /// </summary> /// <type><see cref="IReadOnlyList{ReferenceComment}"/></type> public const string Permissions = nameof(Permissions); /// <summary> /// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains /// a collection of all<c>param</c> XML documentation comments for this symbol with their name, link, and/or rendered HTML content. /// </summary> /// <type><see cref="IReadOnlyList{ReferenceComment}"/></type> public const string Params = nameof(Params); /// <summary> /// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains /// a collection of all<c>typeparam</c> XML documentation comments for this symbol with their name, link, and/or rendered HTML content. /// </summary> /// <type><see cref="IReadOnlyList{ReferenceComment}"/></type> public const string TypeParams = nameof(TypeParams); /// <summary> /// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains /// a collection of all<c>seealso</c> XML documentation comments for this symbol with their rendered HTML link (or just name if no link could be generated). /// </summary> /// <type><c>IReadOnlyList&lt;string&gt;</c></type> public const string SeeAlso = nameof(SeeAlso); /// <summary> /// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains /// a generated syntax example for the symbol. /// </summary> /// <type><see cref="string"/></type> public const string Syntax = nameof(Syntax); /// <summary> /// Set this to <c>true</c> in the global settings to generate a binary build log when analyzing projects or solutions. The log will /// be output alongside the project file. /// </summary> /// <type><see cref="bool"/></type> public const string OutputBuildLog = nameof(OutputBuildLog); } }
// Copyright 2007-2010 The Apache Software Foundation. // // 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 dropkick.FileSystem; namespace dropkick.Configuration.Dsl.RoundhousE { using System; using DeploymentModel; using Tasks.RoundhousE; using Tasks; public class RoundhousEProtoTask : BaseProtoTask, RoundhousEOptions { private readonly Path _path = new DotNetPath(); string _environmentName; string _instanceName; string _databaseName; string _scriptsLocation; private RoundhousEMode _roundhouseMode; private DatabaseRecoveryMode _recoveryMode; private string _restorePath; private string _restoreCustomOptions; private string _userName; private string _password; private string _repositoryPath; private string _versionFile; private string _versionXPath; private int _commandTimeout; private int _restoreTimeout; private int _commandTimeoutAdmin; private string _functionsFolderName; private string _sprocsFolderName; private string _viewsFolderName; private string _upFolderName; private string _versionTable; private string _scriptsRunTable; private string _scriptsRunErrorTable; private bool? _warnOnOneTimeScriptChanges; private string _outputPath; public RoundhousEOptions OnInstance(string name) { _instanceName = ReplaceTokens(name); return this; } public RoundhousEOptions OnDatabase(string name) { _databaseName = ReplaceTokens(name); return this; } public RoundhousEOptions WithRoundhousEMode(RoundhousEMode roundhouseMode) { _roundhouseMode = roundhouseMode; return this; } public RoundhousEOptions WithScriptsFolder(string scriptsLocation) { _scriptsLocation = ReplaceTokens(scriptsLocation); return this; } public RoundhousEOptions WithFunctionsFolder(string functionsFolderName) { _functionsFolderName = ReplaceTokens(functionsFolderName); return this; } public RoundhousEOptions WithSprocsFolder(string sprocsFolderName) { _sprocsFolderName = ReplaceTokens(sprocsFolderName); return this; } public RoundhousEOptions WithViewsFolder(string viewsFolderName) { _viewsFolderName = ReplaceTokens(viewsFolderName); return this; } public RoundhousEOptions WithUpFolder(string upFolderName) { _upFolderName = ReplaceTokens(upFolderName); return this; } public RoundhousEOptions WithVersionTable(string versionTable) { _versionTable = ReplaceTokens(versionTable); return this; } public RoundhousEOptions WithScriptsRunTable(string scriptsRunTable) { _scriptsRunTable = ReplaceTokens(scriptsRunTable); return this; } public RoundhousEOptions WithScriptsRunErrorTable(string scriptsRunErrorTable) { _scriptsRunErrorTable = ReplaceTokens(scriptsRunErrorTable); return this; } public RoundhousEOptions ForEnvironment(string environment) { _environmentName = ReplaceTokens(environment); return this; } public RoundhousEOptions WithDatabaseRecoveryMode(DatabaseRecoveryMode recoveryMode) { _recoveryMode = recoveryMode; return this; } public RoundhousEOptions WithUserName(string userName) { _userName = userName; return this; } public RoundhousEOptions WithPassword(string password) { _password = password; return this; } public RoundhousEOptions WithRestorePath(string restorePath) { _restorePath = ReplaceTokens(restorePath); return this; } public RoundhousEOptions WithRestoreTimeout(int timeout) { _restoreTimeout = timeout; return this; } public RoundhousEOptions WithRepositoryPath(string repositoryPath) { _repositoryPath = ReplaceTokens(repositoryPath); return this; } public RoundhousEOptions WithVersionFile(string versionFile) { _versionFile = ReplaceTokens(versionFile); return this; } public RoundhousEOptions WithVersionXPath(string versionXPath) { _versionXPath = versionXPath; return this; } public RoundhousEOptions WithCommandTimeout(int timeout) { _commandTimeout = timeout; return this; } public RoundhousEOptions WithCommandTimeoutAdmin(int timeout) { _commandTimeoutAdmin = timeout; return this; } public RoundhousEOptions WithRestoreCustomOptions(string options) { _restoreCustomOptions = options; return this; } public RoundhousEOptions WarnAndContinueOnOneTimeScriptChanges() { _warnOnOneTimeScriptChanges = true; return this; } public RoundhousEOptions ErrorOnOneTimeScriptChanges() { _warnOnOneTimeScriptChanges = false; return this; } public RoundhousEOptions WithOutputPath(string outputPath) { _outputPath = ReplaceTokens(outputPath); return this; } public override void RegisterRealTasks(PhysicalServer site) { var connectionInfo = new DbConnectionInfo{ Server = site.Name, Instance = _instanceName, DatabaseName = _databaseName, UserName = _userName, Password = _password }; // string scriptsLocation = PathConverter.Convert(site, _path.GetFullPath(_scriptsLocation)); var task = new RoundhousETask(connectionInfo, _scriptsLocation, _environmentName, _roundhouseMode, _recoveryMode, _restorePath, _restoreTimeout, _restoreCustomOptions, _repositoryPath, _versionFile, _versionXPath, _commandTimeout, _commandTimeoutAdmin, _functionsFolderName, _sprocsFolderName, _viewsFolderName, _upFolderName, _versionTable, _scriptsRunTable, _scriptsRunErrorTable, _warnOnOneTimeScriptChanges, _outputPath); site.AddTask(task); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: This class will encapsulate a byte and provide an ** Object representation of it. ** ** ===========================================================*/ using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System { // The Byte class extends the Value class and // provides object representation of the byte primitive type. // [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct Byte : IComparable, IFormattable, IComparable<Byte>, IEquatable<Byte>, IConvertible { private byte _value; // The maximum value that a Byte may represent: 255. public const byte MaxValue = (byte)0xFF; // The minimum value that a Byte may represent: 0. public const byte MinValue = 0; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type byte, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (!(value is Byte)) { throw new ArgumentException(SR.Arg_MustBeByte); } return _value - (((Byte)value)._value); } public int CompareTo(Byte value) { return _value - value; } // Determines whether two Byte objects are equal. public override bool Equals(Object obj) { if (!(obj is Byte)) { return false; } return _value == ((Byte)obj)._value; } [NonVersionable] public bool Equals(Byte obj) { return _value == obj; } // Gets a hash code for this instance. public override int GetHashCode() { return _value; } [Pure] public static byte Parse(String s) { return Parse(s, NumberStyles.Integer, null); } [Pure] public static byte Parse(String s, NumberStyles style) { UInt32.ValidateParseStyleInteger(style); return Parse(s, style, null); } [Pure] public static byte Parse(String s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, provider); } // Parses an unsigned byte from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. [Pure] public static byte Parse(String s, NumberStyles style, IFormatProvider provider) { UInt32.ValidateParseStyleInteger(style); int i = 0; try { i = FormatProvider.ParseInt32(s, style, provider); } catch (OverflowException e) { throw new OverflowException(SR.Overflow_Byte, e); } if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_Byte); return (byte)i; } public static bool TryParse(String s, out Byte result) { return TryParse(s, NumberStyles.Integer, null /* NumberFormatInfo.CurrentInfo */, out result); } public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Byte result) { UInt32.ValidateParseStyleInteger(style); result = 0; int i; if (!FormatProvider.TryParseInt32(s, style, provider, out i)) { return false; } if (i < MinValue || i > MaxValue) { return false; } result = (byte)i; return true; } [Pure] public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatInt32(_value, null, null); } [Pure] public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatInt32(_value, format, null); } [Pure] public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); // if (provider == null) // throw new ArgumentNullException("provider"); return FormatProvider.FormatInt32(_value, null, provider); } [Pure] public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); // if (provider == null) // throw new ArgumentNullException("provider"); return FormatProvider.FormatInt32(_value, format, provider); } // // IConvertible implementation // [Pure] public TypeCode GetTypeCode() { return TypeCode.Byte; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(_value); } byte IConvertible.ToByte(IFormatProvider provider) { return _value; } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Byte", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Sync.V1.Service.Document { /// <summary> /// Fetch a specific Sync Document Permission. /// </summary> public class FetchDocumentPermissionOptions : IOptions<DocumentPermissionResource> { /// <summary> /// The SID of the Sync Service with the Document Permission resource to fetch /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Sync Document with the Document Permission resource to fetch /// </summary> public string PathDocumentSid { get; } /// <summary> /// The application-defined string that uniquely identifies the User's Document Permission resource to fetch /// </summary> public string PathIdentity { get; } /// <summary> /// Construct a new FetchDocumentPermissionOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Sync Service with the Document Permission resource to fetch </param> /// <param name="pathDocumentSid"> The SID of the Sync Document with the Document Permission resource to fetch </param> /// <param name="pathIdentity"> The application-defined string that uniquely identifies the User's Document Permission /// resource to fetch </param> public FetchDocumentPermissionOptions(string pathServiceSid, string pathDocumentSid, string pathIdentity) { PathServiceSid = pathServiceSid; PathDocumentSid = pathDocumentSid; PathIdentity = pathIdentity; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// Delete a specific Sync Document Permission. /// </summary> public class DeleteDocumentPermissionOptions : IOptions<DocumentPermissionResource> { /// <summary> /// The SID of the Sync Service with the Document Permission resource to delete /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Sync Document with the Document Permission resource to delete /// </summary> public string PathDocumentSid { get; } /// <summary> /// The application-defined string that uniquely identifies the User's Document Permission resource to delete /// </summary> public string PathIdentity { get; } /// <summary> /// Construct a new DeleteDocumentPermissionOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Sync Service with the Document Permission resource to delete </param> /// <param name="pathDocumentSid"> The SID of the Sync Document with the Document Permission resource to delete </param> /// <param name="pathIdentity"> The application-defined string that uniquely identifies the User's Document Permission /// resource to delete </param> public DeleteDocumentPermissionOptions(string pathServiceSid, string pathDocumentSid, string pathIdentity) { PathServiceSid = pathServiceSid; PathDocumentSid = pathDocumentSid; PathIdentity = pathIdentity; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// Retrieve a list of all Permissions applying to a Sync Document. /// </summary> public class ReadDocumentPermissionOptions : ReadOptions<DocumentPermissionResource> { /// <summary> /// The SID of the Sync Service with the Document Permission resources to read /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Sync Document with the Document Permission resources to read /// </summary> public string PathDocumentSid { get; } /// <summary> /// Construct a new ReadDocumentPermissionOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Sync Service with the Document Permission resources to read </param> /// <param name="pathDocumentSid"> The SID of the Sync Document with the Document Permission resources to read </param> public ReadDocumentPermissionOptions(string pathServiceSid, string pathDocumentSid) { PathServiceSid = pathServiceSid; PathDocumentSid = pathDocumentSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// Update an identity's access to a specific Sync Document. /// </summary> public class UpdateDocumentPermissionOptions : IOptions<DocumentPermissionResource> { /// <summary> /// The SID of the Sync Service with the Document Permission resource to update /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Sync Document with the Document Permission resource to update /// </summary> public string PathDocumentSid { get; } /// <summary> /// The application-defined string that uniquely identifies the User's Document Permission resource to update /// </summary> public string PathIdentity { get; } /// <summary> /// Read access /// </summary> public bool? Read { get; } /// <summary> /// Write access /// </summary> public bool? Write { get; } /// <summary> /// Manage access /// </summary> public bool? Manage { get; } /// <summary> /// Construct a new UpdateDocumentPermissionOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Sync Service with the Document Permission resource to update </param> /// <param name="pathDocumentSid"> The SID of the Sync Document with the Document Permission resource to update </param> /// <param name="pathIdentity"> The application-defined string that uniquely identifies the User's Document Permission /// resource to update </param> /// <param name="read"> Read access </param> /// <param name="write"> Write access </param> /// <param name="manage"> Manage access </param> public UpdateDocumentPermissionOptions(string pathServiceSid, string pathDocumentSid, string pathIdentity, bool? read, bool? write, bool? manage) { PathServiceSid = pathServiceSid; PathDocumentSid = pathDocumentSid; PathIdentity = pathIdentity; Read = read; Write = write; Manage = manage; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Read != null) { p.Add(new KeyValuePair<string, string>("Read", Read.Value.ToString().ToLower())); } if (Write != null) { p.Add(new KeyValuePair<string, string>("Write", Write.Value.ToString().ToLower())); } if (Manage != null) { p.Add(new KeyValuePair<string, string>("Manage", Manage.Value.ToString().ToLower())); } return p; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsSubscriptionIdApiVersion { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; 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 Microsoft.Rest.Azure; using Models; /// <summary> /// Some cool documentation. /// </summary> public partial class MicrosoftAzureTestUrl : ServiceClient<MicrosoftAzureTestUrl>, IMicrosoftAzureTestUrl, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Subscription Id. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// API Version with value '2014-04-01-preview'. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IGroupOperations. /// </summary> public virtual IGroupOperations Group { get; private set; } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected MicrosoftAzureTestUrl(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected MicrosoftAzureTestUrl(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected MicrosoftAzureTestUrl(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected MicrosoftAzureTestUrl(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MicrosoftAzureTestUrl(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MicrosoftAzureTestUrl(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MicrosoftAzureTestUrl(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MicrosoftAzureTestUrl(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Group = new GroupOperations(this); this.BaseUri = new Uri("https://management.azure.com/"); this.ApiVersion = "2014-04-01-preview"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
namespace Orleans.CodeGenerator.Utilities { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.Runtime; using System.Globalization; /// <summary> /// The syntax factory extensions. /// </summary> internal static class SyntaxFactoryExtensions { /// <summary> /// Returns <see cref="TypeSyntax"/> for the provided <paramref name="type"/>. /// </summary> /// <param name="type"> /// The type. /// </param> /// <param name="includeNamespace"> /// A value indicating whether or not to include the namespace name. /// </param> /// <param name="includeGenericParameters"> /// Whether or not to include the names of generic parameters in the result. /// </param> /// <returns> /// <see cref="TypeSyntax"/> for the provided <paramref name="type"/>. /// </returns> public static TypeSyntax GetTypeSyntax( this Type type, bool includeNamespace = true, bool includeGenericParameters = true) { if (type == typeof(void)) { return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)); } return SyntaxFactory.ParseTypeName( type.GetParseableName( new TypeFormattingOptions( includeNamespace: includeNamespace, includeGenericParameters: includeGenericParameters))); } /// <summary> /// Returns <see cref="NameSyntax"/> specified <paramref name="type"/>. /// </summary> /// <param name="type"> /// The type. /// </param> /// <param name="includeNamespace"> /// A value indicating whether or not to include the namespace name. /// </param> /// <returns> /// <see cref="NameSyntax"/> specified <paramref name="type"/>. /// </returns> public static NameSyntax GetNameSyntax(this Type type, bool includeNamespace = true) { return SyntaxFactory.ParseName( type.GetParseableName(new TypeFormattingOptions(includeNamespace: includeNamespace))); } /// <summary> /// Returns <see cref="NameSyntax"/> specified <paramref name="method"/>. /// </summary> /// <param name="method"> /// The method. /// </param> /// <returns> /// <see cref="NameSyntax"/> specified <paramref name="method"/>. /// </returns> public static SimpleNameSyntax GetNameSyntax(this MethodInfo method) { var plainName = method.GetUnadornedMethodName(); if (method.IsGenericMethod) { var args = method.GetGenericArguments().Select(arg => arg.GetTypeSyntax()); return plainName.ToGenericName().AddTypeArgumentListArguments(args.ToArray()); } return plainName.ToIdentifierName(); } /// <summary> /// Returns <see cref="ParenthesizedExpressionSyntax"/> representing parenthesized binary expression of <paramref name="bindingFlags"/>. /// </summary> /// <param name="operationKind"> /// The kind of the binary expression. /// </param> /// <param name="bindingFlags"> /// The binding flags. /// </param> /// <returns> /// <see cref="ParenthesizedExpressionSyntax"/> representing parenthesized binary expression of <paramref name="bindingFlags"/>. /// </returns> public static ParenthesizedExpressionSyntax GetBindingFlagsParenthesizedExpressionSyntax(SyntaxKind operationKind, params BindingFlags[] bindingFlags) { if (bindingFlags.Length < 2) { throw new ArgumentOutOfRangeException( "bindingFlags", string.Format("Can't create parenthesized binary expression with {0} arguments", bindingFlags.Length)); } var flags = SyntaxFactory.IdentifierName("System").Member("Reflection").Member("BindingFlags"); var bindingFlagsBinaryExpression = SyntaxFactory.BinaryExpression( operationKind, flags.Member(bindingFlags[0].ToString()), flags.Member(bindingFlags[1].ToString())); for (var i = 2; i < bindingFlags.Length; i++) { bindingFlagsBinaryExpression = SyntaxFactory.BinaryExpression( operationKind, bindingFlagsBinaryExpression, flags.Member(bindingFlags[i].ToString())); } return SyntaxFactory.ParenthesizedExpression(bindingFlagsBinaryExpression); } /// <summary> /// Returns <see cref="ArrayTypeSyntax"/> representing the array form of <paramref name="type"/>. /// </summary> /// <param name="type"> /// The type. /// </param> /// <param name="includeNamespace"> /// A value indicating whether or not to include the namespace name. /// </param> /// <returns> /// <see cref="ArrayTypeSyntax"/> representing the array form of <paramref name="type"/>. /// </returns> public static ArrayTypeSyntax GetArrayTypeSyntax(this Type type, bool includeNamespace = true) { return SyntaxFactory.ArrayType( SyntaxFactory.ParseTypeName( type.GetParseableName(new TypeFormattingOptions(includeNamespace: includeNamespace)))) .AddRankSpecifiers( SyntaxFactory.ArrayRankSpecifier().AddSizes(SyntaxFactory.OmittedArraySizeExpression())); } /// <summary> /// Returns the method declaration syntax for the provided method. /// </summary> /// <param name="method"> /// The method. /// </param> /// <returns> /// The method declaration syntax for the provided method. /// </returns> public static MethodDeclarationSyntax GetDeclarationSyntax(this MethodInfo method) { var syntax = SyntaxFactory.MethodDeclaration(method.ReturnType.GetTypeSyntax(), method.Name.ToIdentifier()) .WithParameterList(SyntaxFactory.ParameterList().AddParameters(method.GetParameterListSyntax())); if (method.IsPublic) { syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); } else if (method.IsPrivate) { syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); } else if (method.IsFamily) { syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); } return syntax; } /// <summary> /// Returns the method declaration syntax for the provided constructor. /// </summary> /// <param name="constructor"> /// The constructor. /// </param> /// <param name="typeName"> /// The name of the type which the constructor will reside on. /// </param> /// <returns> /// The method declaration syntax for the provided constructor. /// </returns> public static ConstructorDeclarationSyntax GetDeclarationSyntax(this ConstructorInfo constructor, string typeName) { var syntax = SyntaxFactory.ConstructorDeclaration(typeName.ToIdentifier()) .WithParameterList(SyntaxFactory.ParameterList().AddParameters(constructor.GetParameterListSyntax())); if (constructor.IsPublic) { syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); } else if (constructor.IsPrivate) { syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); } else if (constructor.IsFamily) { syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); } return syntax; } /// <summary> /// Returns the name of the provided parameter. /// If the parameter has no name (possible in F#), /// it returns a name computed by suffixing "arg" with the parameter's index /// </summary> /// <param name="parameter"> The parameter. </param> /// <param name="parameterIndex"> The parameter index in the list of parameters. </param> /// <returns> The parameter name. </returns> public static string GetOrCreateName(this ParameterInfo parameter, int parameterIndex) { var argName = parameter.Name; if (String.IsNullOrWhiteSpace(argName)) { argName = String.Format(CultureInfo.InvariantCulture, "arg{0:G}", parameterIndex); } return argName; } /// <summary> /// Returns the parameter list syntax for the provided method. /// </summary> /// <param name="method"> /// The method. /// </param> /// <returns> /// The parameter list syntax for the provided method. /// </returns> public static ParameterSyntax[] GetParameterListSyntax(this MethodInfo method) { return method.GetParameters() .Select( (parameter, parameterIndex) => SyntaxFactory.Parameter(parameter.GetOrCreateName(parameterIndex).ToIdentifier()) .WithType(parameter.ParameterType.GetTypeSyntax())) .ToArray(); } /// <summary> /// Returns the parameter list syntax for the provided constructor /// </summary> /// <param name="constructor"> /// The constructor. /// </param> /// <returns> /// The parameter list syntax for the provided constructor. /// </returns> public static ParameterSyntax[] GetParameterListSyntax(this ConstructorInfo constructor) { return constructor.GetParameters() .Select( parameter => SyntaxFactory.Parameter(parameter.Name.ToIdentifier()) .WithType(parameter.ParameterType.GetTypeSyntax())) .ToArray(); } /// <summary> /// Returns type constraint syntax for the provided generic type argument. /// </summary> /// <param name="type"> /// The type. /// </param> /// <returns> /// Type constraint syntax for the provided generic type argument. /// </returns> public static TypeParameterConstraintClauseSyntax[] GetTypeConstraintSyntax(this Type type) { var typeInfo = type.GetTypeInfo(); if (typeInfo.IsGenericTypeDefinition) { var constraints = new List<TypeParameterConstraintClauseSyntax>(); foreach (var genericParameter in typeInfo.GetGenericArguments()) { var parameterConstraints = new List<TypeParameterConstraintSyntax>(); var attributes = genericParameter.GenericParameterAttributes; // The "class" or "struct" constraints must come first. if (attributes.HasFlag(GenericParameterAttributes.ReferenceTypeConstraint)) { parameterConstraints.Add(SyntaxFactory.ClassOrStructConstraint(SyntaxKind.ClassConstraint)); } else if (attributes.HasFlag(GenericParameterAttributes.NotNullableValueTypeConstraint)) { parameterConstraints.Add(SyntaxFactory.ClassOrStructConstraint(SyntaxKind.StructConstraint)); } // Follow with the base class or interface constraints. foreach (var genericType in genericParameter.GetGenericParameterConstraints()) { // If the "struct" constraint was specified, skip the corresponding "ValueType" constraint. if (genericType == typeof(ValueType)) { continue; } parameterConstraints.Add(SyntaxFactory.TypeConstraint(genericType.GetTypeSyntax())); } // The "new()" constraint must be the last constraint in the sequence. if (attributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint) && !attributes.HasFlag(GenericParameterAttributes.NotNullableValueTypeConstraint)) { parameterConstraints.Add(SyntaxFactory.ConstructorConstraint()); } if (parameterConstraints.Count > 0) { constraints.Add( SyntaxFactory.TypeParameterConstraintClause(genericParameter.Name) .AddConstraints(parameterConstraints.ToArray())); } } return constraints.ToArray(); } return new TypeParameterConstraintClauseSyntax[0]; } /// <summary> /// Returns member access syntax. /// </summary> /// <param name="instance"> /// The instance. /// </param> /// <param name="member"> /// The member. /// </param> /// <returns> /// The resulting <see cref="MemberAccessExpressionSyntax"/>. /// </returns> public static MemberAccessExpressionSyntax Member(this ExpressionSyntax instance, string member) { return instance.Member(member.ToIdentifierName()); } /// <summary> /// Returns qualified name syntax. /// </summary> /// <param name="instance"> /// The instance. /// </param> /// <param name="member"> /// The member. /// </param> /// <returns> /// The resulting <see cref="MemberAccessExpressionSyntax"/>. /// </returns> public static QualifiedNameSyntax Qualify(this NameSyntax instance, string member) { return instance.Qualify(member.ToIdentifierName()); } /// <summary> /// Returns member access syntax. /// </summary> /// <param name="instance"> /// The instance. /// </param> /// <param name="member"> /// The member. /// </param> /// <param name="genericTypes"> /// The generic type parameters. /// </param> /// <returns> /// The resulting <see cref="MemberAccessExpressionSyntax"/>. /// </returns> public static MemberAccessExpressionSyntax Member( this ExpressionSyntax instance, string member, params Type[] genericTypes) { return instance.Member( member.ToGenericName() .AddTypeArgumentListArguments(genericTypes.Select(_ => _.GetTypeSyntax()).ToArray())); } /// <summary> /// Returns member access syntax. /// </summary> /// <typeparam name="TInstance"> /// The class type. /// </typeparam> /// <typeparam name="T"> /// The member return type. /// </typeparam> /// <param name="instance"> /// The instance. /// </param> /// <param name="member"> /// The member. /// </param> /// <param name="genericTypes"> /// The generic type parameters. /// </param> /// <returns> /// The resulting <see cref="MemberAccessExpressionSyntax"/>. /// </returns> public static MemberAccessExpressionSyntax Member<TInstance, T>( this ExpressionSyntax instance, Expression<Func<TInstance, T>> member, params Type[] genericTypes) { var methodCall = member.Body as MethodCallExpression; if (methodCall != null) { if (genericTypes != null && genericTypes.Length > 0) { return instance.Member(methodCall.Method.Name, genericTypes); } return instance.Member(methodCall.Method.Name.ToIdentifierName()); } var memberAccess = member.Body as MemberExpression; if (memberAccess != null) { if (genericTypes != null && genericTypes.Length > 0) { return instance.Member(memberAccess.Member.Name, genericTypes); } return instance.Member(memberAccess.Member.Name.ToIdentifierName()); } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns method invocation syntax. /// </summary> /// <typeparam name="T"> /// The method return type. /// </typeparam> /// <param name="expression"> /// The invocation expression. /// </param> /// <returns> /// The resulting <see cref="InvocationExpressionSyntax"/>. /// </returns> public static InvocationExpressionSyntax Invoke<T>(this Expression<Func<T>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { var decl = methodCall.Method.DeclaringType; return SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, decl.GetNameSyntax(), methodCall.Method.GetNameSyntax())); } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns method invocation syntax. /// </summary> /// <param name="expression"> /// The invocation expression. /// </param> /// <param name="instance"> /// The instance to invoke this method on, or <see langword="null"/> for static invocation. /// </param> /// <returns> /// The resulting <see cref="InvocationExpressionSyntax"/>. /// </returns> public static InvocationExpressionSyntax Invoke(this Expression<Action> expression, ExpressionSyntax instance = null) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { if (instance == null && methodCall.Method.IsStatic) { instance = methodCall.Method.DeclaringType.GetNameSyntax(); } return SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, instance, methodCall.Method.Name.ToIdentifierName())); } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns method invocation syntax. /// </summary> /// <typeparam name="T">The argument type of <paramref name="expression"/>.</typeparam> /// <param name="expression"> /// The invocation expression. /// </param> /// <param name="instance"> /// The instance to invoke this method on, or <see langword="null"/> for static invocation. /// </param> /// <returns> /// The resulting <see cref="InvocationExpressionSyntax"/>. /// </returns> public static InvocationExpressionSyntax Invoke<T>(this Expression<Action<T>> expression, ExpressionSyntax instance = null) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { var decl = methodCall.Method.DeclaringType; return SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, instance ?? decl.GetNameSyntax(), methodCall.Method.Name.ToIdentifierName())); } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns member access syntax. /// </summary> /// <param name="instance"> /// The instance. /// </param> /// <param name="member"> /// The member. /// </param> /// <returns> /// The resulting <see cref="MemberAccessExpressionSyntax"/>. /// </returns> public static MemberAccessExpressionSyntax Member(this ExpressionSyntax instance, IdentifierNameSyntax member) { return SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, instance, member); } /// <summary> /// Returns member access syntax. /// </summary> /// <param name="instance"> /// The instance. /// </param> /// <param name="member"> /// The member. /// </param> /// <returns> /// The resulting <see cref="MemberAccessExpressionSyntax"/>. /// </returns> public static MemberAccessExpressionSyntax Member(this ExpressionSyntax instance, GenericNameSyntax member) { return SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, instance, member); } /// <summary> /// Returns member access syntax. /// </summary> /// <param name="instance"> /// The instance. /// </param> /// <param name="member"> /// The member. /// </param> /// <returns> /// The resulting <see cref="MemberAccessExpressionSyntax"/>. /// </returns> public static QualifiedNameSyntax Qualify(this NameSyntax instance, IdentifierNameSyntax member) { return SyntaxFactory.QualifiedName(instance, member).WithDotToken(SyntaxFactory.Token(SyntaxKind.DotToken)); } } }
using System; using System.Collections.Concurrent; #nullable enable namespace NBitcoin { /// <summary> /// Interface for injecting security sensitive stuffs to other objects. /// This is equivalent to `SigningProvider` class in bitcoin core. /// Currently used in OutputDescriptor to safely inject private key information /// </summary> public interface ISigningRepository { /// <summary> /// In case of Witness Script, use HashForLookup Property as a key. /// </summary> /// <param name="scriptId"></param> /// <param name="script"></param> /// <returns></returns> bool TryGetScript(ScriptId scriptId, out Script script); bool TryGetPubKey(KeyId keyId, out PubKey pubkey); bool TryGetKeyOrigin(KeyId keyId, out RootedKeyPath keyorigin); bool TryGetSecret(KeyId keyId, out ISecret secret); /// <summary> /// In case of Witness Script, use HashForLookup property as a key. /// </summary> /// <param name="scriptId"></param> /// <param name="script"></param> /// <returns></returns> void SetScript(ScriptId scriptId, Script script); void SetPubKey(KeyId keyId, PubKey pubkey); void SetSecret(KeyId keyId, ISecret secret); void SetKeyOrigin(KeyId keyId, RootedKeyPath keyOrigin); /// <summary> /// Consume the argument and take everything it holds. /// This method should at least support consuming `FlatSigningRepository`. /// </summary> /// <param name="other"></param> void Merge(ISigningRepository other); } public static class ISigningRepositoryExtensions { public static bool IsSolvable(this ISigningRepository repo, Script scriptPubKey) { var temp = scriptPubKey.FindTemplate(); if (temp is PayToPubkeyTemplate p2pkT) { var pk = p2pkT.ExtractScriptPubKeyParameters(scriptPubKey); if (repo.TryGetPubKey(pk.Hash, out var _)) return true; } if (temp is PayToPubkeyHashTemplate p2pkhT) { var keyId = p2pkhT.ExtractScriptPubKeyParameters(scriptPubKey); if (repo.TryGetPubKey(keyId, out var _)) return true; } PubKey[]? pks = null; if (temp is PayToMultiSigTemplate p2multiT) { pks = p2multiT.ExtractScriptPubKeyParameters(scriptPubKey).PubKeys; } if (temp is PayToScriptHashTemplate p2shT) { var scriptId = p2shT.ExtractScriptPubKeyParameters(scriptPubKey); // This will give us witness script directly in case of p2sh-p2wsh if (repo.TryGetScript(scriptId, out var sc)) { scriptPubKey = sc; pks = sc.GetAllPubKeys(); } } if (temp is PayToWitTemplate) { var witId = PayToWitScriptHashTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey); if (witId != null) { if (repo.TryGetScript(witId.HashForLookUp, out var sc)) pks = sc.GetAllPubKeys(); } var wpkh = PayToWitPubKeyHashTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey); if (wpkh != null) { var witKeyId = wpkh.AsKeyId(); if (repo.TryGetPubKey(witKeyId, out var _)) return true; } } if (pks != null) { foreach (var pk in pks) { if (!repo.TryGetPubKey(pk.Hash, out var _)) return false; } return true; } return false; } public static Key? GetPrivateKey(this ISigningRepository repo, KeyId id) { if (!repo.TryGetSecret(id, out var res)) return null; return res.PrivateKey; } } public class FlatSigningRepository : ISigningRepository { public ConcurrentDictionary<KeyId, ISecret> Secrets {get;} public ConcurrentDictionary<KeyId, PubKey> Pubkeys { get; } public ConcurrentDictionary<KeyId, RootedKeyPath> KeyOrigins { get; } public ConcurrentDictionary<ScriptId, Script> Scripts { get; } public FlatSigningRepository() { Secrets = new ConcurrentDictionary<KeyId, ISecret>(); Pubkeys = new ConcurrentDictionary<KeyId, PubKey>(); KeyOrigins = new ConcurrentDictionary<KeyId, RootedKeyPath>(); Scripts = new ConcurrentDictionary<ScriptId, Script>(); } public bool TryGetScript(ScriptId scriptId, out Script script) => Scripts.TryGetValue(scriptId, out script); public bool TryGetPubKey(KeyId keyId, out PubKey pubkey) => Pubkeys.TryGetValue(keyId, out pubkey); public bool TryGetKeyOrigin(KeyId keyId, out RootedKeyPath keyOrigin) => KeyOrigins.TryGetValue(keyId, out keyOrigin); public bool TryGetSecret(KeyId keyId, out ISecret key) => Secrets.TryGetValue(keyId, out key); public void SetScript(ScriptId scriptId, Script script) { if (scriptId == null) { throw new ArgumentNullException(nameof(scriptId)); } if (script == null) { throw new ArgumentNullException(nameof(script)); } Scripts.AddOrReplace(scriptId, script); } public void SetPubKey(KeyId keyId, PubKey pubkey) { if (keyId == null) { throw new ArgumentNullException(nameof(keyId)); } if (pubkey == null) { throw new ArgumentNullException(nameof(pubkey)); } Pubkeys.AddOrReplace(keyId, pubkey); } public void SetSecret(KeyId keyId, ISecret secret) { if (keyId == null) { throw new ArgumentNullException(nameof(keyId)); } if (secret == null) { throw new ArgumentNullException(nameof(secret)); } Secrets.AddOrReplace(keyId, secret); } public void SetKeyOrigin(KeyId keyId, RootedKeyPath keyOrigin) { if (keyId == null) { throw new ArgumentNullException(nameof(keyId)); } if (keyOrigin == null) { throw new ArgumentNullException(nameof(keyOrigin)); } KeyOrigins.AddOrReplace(keyId, keyOrigin); } public void Merge(ISigningRepository other) { if (!(other is FlatSigningRepository)) { throw new NotSupportedException($"{nameof(FlatSigningRepository)} can be merged only with the same type"); } var otherRepo = (FlatSigningRepository) other; MergeDict(Secrets, otherRepo.Secrets); MergeDict(Pubkeys, otherRepo.Pubkeys); MergeDict(Scripts, otherRepo.Scripts); MergeDict(KeyOrigins, otherRepo.KeyOrigins); } private void MergeDict<U, T>(ConcurrentDictionary<U, T> a, ConcurrentDictionary<U, T> b) { foreach (var bItem in b) { a.AddOrReplace(bItem.Key, bItem.Value); } } } } #nullable disable
#region Namespaces using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using mshtml; using System.Net; #endregion //Namespaces namespace Epi.Windows.MakeView.Dialogs { public partial class HelpDialog : CommandDesignDialog { #region Private Attributes private bool showSaveOnly = false; #endregion Private Attributes #region Constructors /// <summary> /// Default Constructor /// </summary> [Obsolete("Use of default constructor not allowed", true)] public HelpDialog() { InitializeComponent(); } /// <summary> /// Constructor for AssignDialog /// </summary> /// <param name="frm">The main form</param> public HelpDialog(Epi.Windows.MakeView.Forms.MakeViewMainForm frm) : base(frm) { InitializeComponent(); Construct(); } /// <summary> /// Constructor for AssignDialog. if showSave, enable the SaveOnly button /// </summary> /// <param name="frm">The main form</param> /// <param name="showSave">True or False to show Save Only button</param> public HelpDialog(Epi.Windows.MakeView.Forms.MakeViewMainForm frm, bool showSave) : base(frm) { InitializeComponent(); if (showSave) { showSaveOnly = true; this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click); Construct(); } } #endregion Constructors #region Public Methods /// <summary> /// Checks if input is sufficient and Enables control buttons accordingly /// </summary> public override void CheckForInputSufficiency() { bool inputValid = ValidateInput(); btnOK.Enabled = inputValid; btnSaveOnly.Enabled = inputValid; } #endregion Public Methods #region Protected methods /// <summary> /// Validates user input /// </summary> /// <returns>true if ErrorMessages.Count is 0; otherwise false</returns> protected override bool ValidateInput() { base.ValidateInput(); if (string.IsNullOrEmpty(this.txtFilename.Text)) { ErrorMessages.Add(SharedStrings.NO_FILENAME); } return (ErrorMessages.Count == 0); } /// <summary> /// Generates command text /// </summary> protected override void GenerateCommand() { StringBuilder command = new StringBuilder(); command.Append(CommandNames.HELP).Append(StringLiterals.SPACE); command.Append(StringLiterals.SINGLEQUOTES).Append(txtFilename.Text.Trim()).Append(StringLiterals.SINGLEQUOTES); command.Append(StringLiterals.SPACE); command.Append(StringLiterals.DOUBLEQUOTES).Append(this.cmbAnchor.Text.Trim()).Append(StringLiterals.DOUBLEQUOTES); CommandText = command.ToString(); } #endregion Protected methods #region Private Methods /// <summary> /// Repositions buttons on dialog /// </summary> private void RepositionButtons() { int x = this.btnClear.Left; int y = btnClear.Top; btnClear.Location = new Point(btnCancel.Left, y); btnCancel.Location = new Point(btnOK.Left, y); btnOK.Location = new Point(btnSaveOnly.Left, y); btnSaveOnly.Location = new Point(x, y); } /// <summary> /// Construct the dialog /// </summary> private void Construct() { this.btnOK.Click += new System.EventHandler(this.btnOK_Click); } /// <summary> /// Loads the anchors for a specified html file /// </summary> /// <param name="fileName">The file name in which anchors are to be retrieved from</param> private void LoadAnchors(string fileName) { WebClient client = new WebClient(); byte[] data = client.DownloadData(fileName); mshtml.HTMLDocumentClass ms = new mshtml.HTMLDocumentClass(); string strHTML = Encoding.ASCII.GetString(data); mshtml.IHTMLDocument2 mydoc = (mshtml.IHTMLDocument2)ms; //mydoc.write(!--saved from url=(0014)about:internet -->); mydoc.write(strHTML); mshtml.IHTMLElementCollection ec = (mshtml.IHTMLElementCollection)mydoc.all.tags("a"); if (ec != null) { for (int i = 0; i < ec.length - 1; i++) { mshtml.HTMLAnchorElementClass anchor; anchor = (mshtml.HTMLAnchorElementClass)ec.item(i, 0); if (!string.IsNullOrEmpty(anchor.name)) { cmbAnchor.Items.Add(anchor.name); } } } } #endregion Private Methods #region Event Handlers /// <summary> /// Loads the dialog /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void HelpDialog_Load(object sender, EventArgs e) { btnSaveOnly.Visible = showSaveOnly; if (showSaveOnly) { RepositionButtons(); } } /// <summary> /// Handles the Text Changed event of the filename textbox /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void txtFilename_TextChanged(object sender, EventArgs e) { CheckForInputSufficiency(); } /// <summary> /// Handles the Click event of the Browse button /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void btnBrowse_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "HTML files (*.htm)|*.htm*|CHM Help Files (*.chm)|*.chm"; if (dlg.ShowDialog(this) == DialogResult.OK) { this.txtFilename.Text = dlg.FileName; LoadAnchors(this.txtFilename.Text); } dlg.Dispose(); } #endregion Event Handlers } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Client.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. #pragma warning disable 1717 namespace Org.Apache.Http.Client { /// <summary> /// <para><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/client/AuthenticationHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/AuthenticationHandler", AccessFlags = 1537)] public partial interface IAuthenticationHandler /* scope: __dot42__ */ { /// <java-name> /// isAuthenticationRequested /// </java-name> [Dot42.DexImport("isAuthenticationRequested", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)] bool IsAuthenticationRequested(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <java-name> /// getChallenges /// </java-name> [Dot42.DexImport("getChallenges", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/util/" + "Map;", AccessFlags = 1025, Signature = "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/util/" + "Map<Ljava/lang/String;Lorg/apache/http/Header;>;")] global::Java.Util.IMap<string, global::Org.Apache.Http.IHeader> GetChallenges(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <java-name> /// selectScheme /// </java-name> [Dot42.DexImport("selectScheme", "(Ljava/util/Map;Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpConte" + "xt;)Lorg/apache/http/auth/AuthScheme;", AccessFlags = 1025, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/Header;>;Lorg/apache/http/Http" + "Response;Lorg/apache/http/protocol/HttpContext;)Lorg/apache/http/auth/AuthScheme" + ";")] global::Org.Apache.Http.Auth.IAuthScheme SelectScheme(global::Java.Util.IMap<string, global::Org.Apache.Http.IHeader> challenges, global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>A client-side request director. The director decides which steps are necessary to execute a request. It establishes connections and optionally processes redirects and authentication challenges. The director may therefore generate and send a sequence of requests in order to execute one initial request.</para><para><br></br><b>Note:</b> It is most likely that implementations of this interface will allocate connections, and return responses that depend on those connections for reading the response entity. Such connections MUST be released, but that is out of the scope of a request director.</para><para><para></para><para></para><title>Revision:</title><para>676020 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/RequestDirector /// </java-name> [Dot42.DexImport("org/apache/http/client/RequestDirector", AccessFlags = 1537)] public partial interface IRequestDirector /* scope: __dot42__ */ { /// <summary> /// <para>Executes a request. <br></br><b>Note:</b> For the time being, a new director is instantiated for each request. This is the same behavior as for <code>HttpMethodDirector</code> in HttpClient 3.</para><para></para> /// </summary> /// <returns> /// <para>the final response to the request. This is never an intermediate response with status code 1xx.</para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol" + "/HttpContext;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Handler that encapsulates the process of generating a response object from a HttpResponse.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/ResponseHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/ResponseHandler", AccessFlags = 1537, Signature = "<T:Ljava/lang/Object;>Ljava/lang/Object;")] public partial interface IResponseHandler<T> /* scope: __dot42__ */ { /// <summary> /// <para>Processes an HttpResponse and returns some value corresponding to that response.</para><para></para> /// </summary> /// <returns> /// <para>A value determined by the response</para> /// </returns> /// <java-name> /// handleResponse /// </java-name> [Dot42.DexImport("handleResponse", "(Lorg/apache/http/HttpResponse;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "(Lorg/apache/http/HttpResponse;)TT;")] T HandleResponse(global::Org.Apache.Http.IHttpResponse response) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Signals violation of HTTP specification caused by an invalid redirect</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/RedirectException /// </java-name> [Dot42.DexImport("org/apache/http/client/RedirectException", AccessFlags = 33)] public partial class RedirectException : global::Org.Apache.Http.ProtocolException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new RedirectException with a <code>null</code> detail message. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RedirectException() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new RedirectException with the specified detail message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public RedirectException(string message) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new RedirectException with the specified detail message and cause.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)] public RedirectException(string message, global::System.Exception cause) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Abstract cookie store.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/CookieStore /// </java-name> [Dot42.DexImport("org/apache/http/client/CookieStore", AccessFlags = 1537)] public partial interface ICookieStore /* scope: __dot42__ */ { /// <summary> /// <para>Adds an HTTP cookie, replacing any existing equivalent cookies. If the given cookie has already expired it will not be added, but existing values will still be removed.</para><para></para> /// </summary> /// <java-name> /// addCookie /// </java-name> [Dot42.DexImport("addCookie", "(Lorg/apache/http/cookie/Cookie;)V", AccessFlags = 1025)] void AddCookie(global::Org.Apache.Http.Cookie.ICookie cookie) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns all cookies contained in this store.</para><para></para> /// </summary> /// <returns> /// <para>all cookies </para> /// </returns> /// <java-name> /// getCookies /// </java-name> [Dot42.DexImport("getCookies", "()Ljava/util/List;", AccessFlags = 1025, Signature = "()Ljava/util/List<Lorg/apache/http/cookie/Cookie;>;")] global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> GetCookies() /* MethodBuilder.Create */ ; /// <summary> /// <para>Removes all of cookies in this store that have expired by the specified date.</para><para></para> /// </summary> /// <returns> /// <para>true if any cookies were purged. </para> /// </returns> /// <java-name> /// clearExpired /// </java-name> [Dot42.DexImport("clearExpired", "(Ljava/util/Date;)Z", AccessFlags = 1025)] bool ClearExpired(global::Java.Util.Date date) /* MethodBuilder.Create */ ; /// <summary> /// <para>Clears all cookies. </para> /// </summary> /// <java-name> /// clear /// </java-name> [Dot42.DexImport("clear", "()V", AccessFlags = 1025)] void Clear() /* MethodBuilder.Create */ ; } /// <summary> /// <para>Signals an error in the HTTP protocol. </para> /// </summary> /// <java-name> /// org/apache/http/client/ClientProtocolException /// </java-name> [Dot42.DexImport("org/apache/http/client/ClientProtocolException", AccessFlags = 33)] public partial class ClientProtocolException : global::System.IO.IOException /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public ClientProtocolException() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public ClientProtocolException(string @string) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/Throwable;)V", AccessFlags = 1)] public ClientProtocolException(global::System.Exception exception) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)] public ClientProtocolException(string message, global::System.Exception cause) /* MethodBuilder.Create */ { } } /// <summary> /// <para>A handler for determining if an HttpRequest should be retried after a recoverable exception during execution.</para><para>Classes implementing this interface must synchronize access to shared data as methods of this interfrace may be executed from multiple threads </para><para><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/client/HttpRequestRetryHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/HttpRequestRetryHandler", AccessFlags = 1537)] public partial interface IHttpRequestRetryHandler /* scope: __dot42__ */ { /// <summary> /// <para>Determines if a method should be retried after an IOException occurs during execution.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the method should be retried, <code>false</code> otherwise </para> /// </returns> /// <java-name> /// retryRequest /// </java-name> [Dot42.DexImport("retryRequest", "(Ljava/io/IOException;ILorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)] bool RetryRequest(global::System.IO.IOException exception, int executionCount, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>A handler for determining if the given execution context is user specific or not. The token object returned by this handler is expected to uniquely identify the current user if the context is user specific or to be <code>null</code> if the context does not contain any resources or details specific to the current user. </para><para>The user token will be used to ensure that user specific resouces will not shared with or reused by other users.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/UserTokenHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/UserTokenHandler", AccessFlags = 1537)] public partial interface IUserTokenHandler /* scope: __dot42__ */ { /// <summary> /// <para>The token object returned by this method is expected to uniquely identify the current user if the context is user specific or to be <code>null</code> if it is not.</para><para></para> /// </summary> /// <returns> /// <para>user token that uniquely identifies the user or <code>null&lt;/null&gt; if the context is not user specific. </code></para> /// </returns> /// <java-name> /// getUserToken /// </java-name> [Dot42.DexImport("getUserToken", "(Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025)] object GetUserToken(global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Signals a circular redirect</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/CircularRedirectException /// </java-name> [Dot42.DexImport("org/apache/http/client/CircularRedirectException", AccessFlags = 33)] public partial class CircularRedirectException : global::Org.Apache.Http.Client.RedirectException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new CircularRedirectException with a <code>null</code> detail message. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CircularRedirectException() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new CircularRedirectException with the specified detail message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public CircularRedirectException(string message) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new CircularRedirectException with the specified detail message and cause.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)] public CircularRedirectException(string message, global::System.Exception cause) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Signals failure to retry the request due to non-repeatable request entity.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/NonRepeatableRequestException /// </java-name> [Dot42.DexImport("org/apache/http/client/NonRepeatableRequestException", AccessFlags = 33)] public partial class NonRepeatableRequestException : global::Org.Apache.Http.ProtocolException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new NonRepeatableEntityException with a <code>null</code> detail message. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public NonRepeatableRequestException() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new NonRepeatableEntityException with the specified detail message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public NonRepeatableRequestException(string message) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Abstract credentials provider.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/CredentialsProvider /// </java-name> [Dot42.DexImport("org/apache/http/client/CredentialsProvider", AccessFlags = 1537)] public partial interface ICredentialsProvider /* scope: __dot42__ */ { /// <summary> /// <para>Sets the credentials for the given authentication scope. Any previous credentials for the given scope will be overwritten.</para><para><para>getCredentials(AuthScope) </para></para> /// </summary> /// <java-name> /// setCredentials /// </java-name> [Dot42.DexImport("setCredentials", "(Lorg/apache/http/auth/AuthScope;Lorg/apache/http/auth/Credentials;)V", AccessFlags = 1025)] void SetCredentials(global::Org.Apache.Http.Auth.AuthScope authscope, global::Org.Apache.Http.Auth.ICredentials credentials) /* MethodBuilder.Create */ ; /// <summary> /// <para>Get the credentials for the given authentication scope.</para><para><para>setCredentials(AuthScope, Credentials) </para></para> /// </summary> /// <returns> /// <para>the credentials</para> /// </returns> /// <java-name> /// getCredentials /// </java-name> [Dot42.DexImport("getCredentials", "(Lorg/apache/http/auth/AuthScope;)Lorg/apache/http/auth/Credentials;", AccessFlags = 1025)] global::Org.Apache.Http.Auth.ICredentials GetCredentials(global::Org.Apache.Http.Auth.AuthScope authscope) /* MethodBuilder.Create */ ; /// <summary> /// <para>Clears all credentials. </para> /// </summary> /// <java-name> /// clear /// </java-name> [Dot42.DexImport("clear", "()V", AccessFlags = 1025)] void Clear() /* MethodBuilder.Create */ ; } /// <summary> /// <para>Signals a non 2xx HTTP response. </para> /// </summary> /// <java-name> /// org/apache/http/client/HttpResponseException /// </java-name> [Dot42.DexImport("org/apache/http/client/HttpResponseException", AccessFlags = 33)] public partial class HttpResponseException : global::Org.Apache.Http.Client.ClientProtocolException /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(ILjava/lang/String;)V", AccessFlags = 1)] public HttpResponseException(int statusCode, string s) /* MethodBuilder.Create */ { } /// <java-name> /// getStatusCode /// </java-name> [Dot42.DexImport("getStatusCode", "()I", AccessFlags = 1)] public virtual int GetStatusCode() /* MethodBuilder.Create */ { return default(int); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal HttpResponseException() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getStatusCode /// </java-name> public int StatusCode { [Dot42.DexImport("getStatusCode", "()I", AccessFlags = 1)] get{ return GetStatusCode(); } } } /// <summary> /// <para>Interface for an HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests while handling cookies, authentication, connection management, and other features. Thread safety of HTTP clients depends on the implementation and configuration of the specific client.</para><para><para></para><para></para><title>Revision:</title><para>676020 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/HttpClient /// </java-name> [Dot42.DexImport("org/apache/http/client/HttpClient", AccessFlags = 1537)] public partial interface IHttpClient /* scope: __dot42__ */ { /// <summary> /// <para>Obtains the parameters for this client. These parameters will become defaults for all requests being executed with this client, and for the parameters of dependent objects in this client.</para><para></para> /// </summary> /// <returns> /// <para>the default parameters </para> /// </returns> /// <java-name> /// getParams /// </java-name> [Dot42.DexImport("getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams GetParams() /* MethodBuilder.Create */ ; /// <summary> /// <para>Obtains the connection manager used by this client.</para><para></para> /// </summary> /// <returns> /// <para>the connection manager </para> /// </returns> /// <java-name> /// getConnectionManager /// </java-name> [Dot42.DexImport("getConnectionManager", "()Lorg/apache/http/conn/ClientConnectionManager;", AccessFlags = 1025)] global::Org.Apache.Http.Conn.IClientConnectionManager GetConnectionManager() /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request using the default context.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/protocol/HttpCon" + "text;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;)Lorg/apache/http/HttpRes" + "ponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost request, global::Org.Apache.Http.IHttpRequest context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request to the target using the given context.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol" + "/HttpContext;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/client/ResponseH" + "andler;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache" + "/http/client/ResponseHandler<+TT;>;)TT;")] T Execute<T>(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request to the target using the given context.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/client/ResponseH" + "andler;Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache" + "/http/client/ResponseHandler<+TT;>;Lorg/apache/http/protocol/HttpContext;)TT;")] T Execute<T>(global::Org.Apache.Http.Client.Methods.IHttpUriRequest target, global::Org.Apache.Http.Client.IResponseHandler<T> request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request to the target using the given context.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/client/R" + "esponseHandler;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lor" + "g/apache/http/client/ResponseHandler<+TT;>;)TT;")] T Execute<T>(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request to the target using the given context and processes the response using the given response handler.</para><para></para> /// </summary> /// <returns> /// <para>the response object as generated by the response handler. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/client/R" + "esponseHandler;Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lor" + "g/apache/http/client/ResponseHandler<+TT;>;Lorg/apache/http/protocol/HttpContext" + ";)TT;")] T Execute<T>(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> responseHandler, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>A handler for determining if an HTTP request should be redirected to a new location in response to an HTTP response received from the target server.</para><para>Classes implementing this interface must synchronize access to shared data as methods of this interfrace may be executed from multiple threads </para><para><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/client/RedirectHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/RedirectHandler", AccessFlags = 1537)] public partial interface IRedirectHandler /* scope: __dot42__ */ { /// <summary> /// <para>Determines if a request should be redirected to a new location given the response from the target server.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the request should be redirected, <code>false</code> otherwise </para> /// </returns> /// <java-name> /// isRedirectRequested /// </java-name> [Dot42.DexImport("isRedirectRequested", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)] bool IsRedirectRequested(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Determines the location request is expected to be redirected to given the response from the target server and the current request execution context.</para><para></para> /// </summary> /// <returns> /// <para>redirect URI </para> /// </returns> /// <java-name> /// getLocationURI /// </java-name> [Dot42.DexImport("getLocationURI", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/net/U" + "RI;", AccessFlags = 1025)] global::System.Uri GetLocationURI(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Monitor.Fluent { using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using System.Collections.Generic; internal partial class ActivityLogAlertImpl { /// <summary> /// Gets the actions that will activate when the condition is met. /// </summary> /// <summary> /// Gets the actions value. /// </summary> System.Collections.Generic.IReadOnlyCollection<string> Microsoft.Azure.Management.Monitor.Fluent.IActivityLogAlert.ActionGroupIds { get { return this.ActionGroupIds(); } } /// <summary> /// Gets a description of this activity log alert. /// </summary> /// <summary> /// Gets the description value. /// </summary> string Microsoft.Azure.Management.Monitor.Fluent.IActivityLogAlert.Description { get { return this.Description(); } } /// <summary> /// Gets indicates whether this activity log alert is enabled. If an activity log alert is not enabled, then none of its actions will be activated. /// </summary> /// <summary> /// Gets the enabled value. /// </summary> bool Microsoft.Azure.Management.Monitor.Fluent.IActivityLogAlert.Enabled { get { return this.Enabled(); } } /// <summary> /// Gets the condition that will cause this alert to activate. /// </summary> /// <summary> /// Gets the condition value. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string, string> Microsoft.Azure.Management.Monitor.Fluent.IActivityLogAlert.EqualsConditions { get { return this.EqualsConditions(); } } /// <summary> /// Gets a list of resourceIds that will be used as prefixes. The alert will only apply to activityLogs with resourceIds that fall under one of these prefixes. This list must include at least one item. /// </summary> /// <summary> /// Gets the scopes value. /// </summary> System.Collections.Generic.IReadOnlyCollection<string> Microsoft.Azure.Management.Monitor.Fluent.IActivityLogAlert.Scopes { get { return this.Scopes(); } } /// <summary> /// Sets the actions that will activate when the condition is met. /// </summary> /// <param name="actionGroupId">Resource Ids of the ActionGroup.</param> /// <return>The next stage of activity log alert definition.</return> ActivityLogAlert.Definition.IWithCriteriaDefinition ActivityLogAlert.Definition.IWithActionGroup.WithActionGroups(params string[] actionGroupId) { return this.WithActionGroups(actionGroupId); } /// <summary> /// Sets the actions that will activate when the condition is met. /// </summary> /// <param name="actionGroupId">Resource Ids of the ActionGroup.</param> /// <return>The next stage of the activity log alert update.</return> ActivityLogAlert.Update.IUpdate ActivityLogAlert.Update.IWithActivityLogUpdate.WithActionGroups(params string[] actionGroupId) { return this.WithActionGroups(actionGroupId); } /// <summary> /// Sets description for activity log alert. /// </summary> /// <param name="description">Human readable text description of the activity log alert.</param> /// <return>The next stage of activity log alert definition.</return> ActivityLogAlert.Definition.IWithAlertEnabled ActivityLogAlert.Definition.IWithDescription.WithDescription(string description) { return this.WithDescription(description); } /// <summary> /// Sets description for activity log alert. /// </summary> /// <param name="description">Human readable text description of the activity log alert.</param> /// <return>The next stage of the activity log alert update.</return> ActivityLogAlert.Update.IUpdate ActivityLogAlert.Update.IWithActivityLogUpdate.WithDescription(string description) { return this.WithDescription(description); } /// <summary> /// Adds a condition that will cause this alert to activate. /// </summary> /// <param name="field">Set the name of the field that this condition will examine. The possible values for this field are (case-insensitive): 'resourceId', 'category', 'caller', 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', 'subStatus', 'resourceType', or anything beginning with 'properties.'.</param> /// <param name="equals">Set the field value will be compared to this value (case-insensitive) to determine if the condition is met.</param> /// <return>The next stage of the activity log alert update.</return> ActivityLogAlert.Update.IUpdate ActivityLogAlert.Update.IWithActivityLogUpdate.WithEqualsCondition(string field, string equals) { return this.WithEqualsCondition(field, equals); } /// <summary> /// Adds a condition that will cause this alert to activate. /// </summary> /// <param name="field">Set the name of the field that this condition will examine. The possible values for this field are (case-insensitive): 'resourceId', 'category', 'caller', 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', 'subStatus', 'resourceType', or anything beginning with 'properties.'.</param> /// <param name="equals">Set the field value will be compared to this value (case-insensitive) to determine if the condition is met.</param> /// <return>The next stage of activity log alert definition.</return> ActivityLogAlert.Definition.IWithCreate ActivityLogAlert.Definition.IWithCriteriaDefinition.WithEqualsCondition(string field, string equals) { return this.WithEqualsCondition(field, equals); } /// <summary> /// Sets all the conditions that will cause this alert to activate. /// </summary> /// <param name="fieldEqualsMap">Set the names of the field that this condition will examine and their values to be compared to.</param> /// <return>The next stage of the activity log alert update.</return> ActivityLogAlert.Update.IUpdate ActivityLogAlert.Update.IWithActivityLogUpdate.WithEqualsConditions(IDictionary<string, string> fieldEqualsMap) { return this.WithEqualsConditions(fieldEqualsMap); } /// <summary> /// Sets all the conditions that will cause this alert to activate. /// </summary> /// <param name="fieldEqualsMap">Set the names of the field that this condition will examine and their values to be compared to.</param> /// <return>The next stage of activity log alert definition.</return> ActivityLogAlert.Definition.IWithCreate ActivityLogAlert.Definition.IWithCriteriaDefinition.WithEqualsConditions(IDictionary<string, string> fieldEqualsMap) { return this.WithEqualsConditions(fieldEqualsMap); } /// <summary> /// Removes the specified action group from the actions list. /// </summary> /// <param name="actionGroupId">Resource Id of the ActionGroup to remove.</param> /// <return>The next stage of the activity log alert update.</return> ActivityLogAlert.Update.IUpdate ActivityLogAlert.Update.IWithActivityLogUpdate.WithoutActionGroup(string actionGroupId) { return this.WithoutActionGroup(actionGroupId); } /// <summary> /// Removes a condition from the list of conditions. /// </summary> /// <param name="field">The name of the field that was used for condition examination.</param> /// <return>The next stage of the activity log alert update.</return> ActivityLogAlert.Update.IUpdate ActivityLogAlert.Update.IWithActivityLogUpdate.WithoutEqualsCondition(string field) { return this.WithoutEqualsCondition(field); } /// <summary> /// Sets activity log alert as disabled. /// </summary> /// <return>The next stage of the activity log alert update.</return> ActivityLogAlert.Update.IUpdate ActivityLogAlert.Update.IWithActivityLogUpdate.WithRuleDisabled() { return this.WithRuleDisabled(); } /// <summary> /// Sets activity log alert as disabled during the creation. /// </summary> /// <return>The next stage of activity log alert definition.</return> ActivityLogAlert.Definition.IWithActionGroup ActivityLogAlert.Definition.IWithAlertEnabled.WithRuleDisabled() { return this.WithRuleDisabled(); } /// <summary> /// Sets activity log alert as enabled. /// </summary> /// <return>The next stage of the activity log alert update.</return> ActivityLogAlert.Update.IUpdate ActivityLogAlert.Update.IWithActivityLogUpdate.WithRuleEnabled() { return this.WithRuleEnabled(); } /// <summary> /// Sets activity log alert as enabled during the creation. /// </summary> /// <return>The next stage of activity log alert definition.</return> ActivityLogAlert.Definition.IWithActionGroup ActivityLogAlert.Definition.IWithAlertEnabled.WithRuleEnabled() { return this.WithRuleEnabled(); } /// <summary> /// Sets specified resource as a target to alert on activity log. /// </summary> /// <param name="resourceId">Resource Id string.</param> /// <return>The next stage of activity log alert definition.</return> ActivityLogAlert.Definition.IWithDescription ActivityLogAlert.Definition.IWithScopes.WithTargetResource(string resourceId) { return this.WithTargetResource(resourceId); } /// <summary> /// Sets specified resource as a target to alert on activity log. /// </summary> /// <param name="resource">Resource type that is inherited from HasId interface.</param> /// <return>The next stage of activity log alert definition.</return> ActivityLogAlert.Definition.IWithDescription ActivityLogAlert.Definition.IWithScopes.WithTargetResource(IHasId resource) { return this.WithTargetResource(resource); } /// <summary> /// Sets specified subscription as a target to alert on activity log. /// </summary> /// <param name="targetSubscriptionId">Subscription Id.</param> /// <return>The next stage of activity log alert definition.</return> ActivityLogAlert.Definition.IWithDescription ActivityLogAlert.Definition.IWithScopes.WithTargetSubscription(string targetSubscriptionId) { return this.WithTargetSubscription(targetSubscriptionId); } } }
// 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; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; namespace System.Diagnostics { /// <summary> /// Provides interaction with Windows event logs. /// </summary> [DefaultEvent("EntryWritten")] public class EventLog : Component, ISupportInitialize { private const string EventLogKey = "SYSTEM\\CurrentControlSet\\Services\\EventLog"; internal const string DllName = "EventLogMessages.dll"; private const string eventLogMutexName = "netfxeventlog.1.0"; private const int DefaultMaxSize = 512 * 1024; private const int DefaultRetention = 7 * SecondsPerDay; private const int SecondsPerDay = 60 * 60 * 24; private EventLogInternal _underlyingEventLog; public EventLog() : this(string.Empty, ".", string.Empty) { } public EventLog(string logName) : this(logName, ".", string.Empty) { } public EventLog(string logName, string machineName) : this(logName, machineName, string.Empty) { } public EventLog(string logName, string machineName, string source) { _underlyingEventLog = new EventLogInternal(logName, machineName, source, this); } /// <summary> /// The contents of the log. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public EventLogEntryCollection Entries { get { return _underlyingEventLog.Entries; } } [Browsable(false)] public string LogDisplayName { get { return _underlyingEventLog.LogDisplayName; } } /// <summary> /// Gets or sets the name of the log to read from and write to. /// </summary> [ReadOnly(true)] [DefaultValue("")] [SettingsBindable(true)] public string Log { get { return _underlyingEventLog.Log; } set { EventLogInternal newLog = new EventLogInternal(value, _underlyingEventLog.MachineName, _underlyingEventLog.Source, this); EventLogInternal oldLog = _underlyingEventLog; if (oldLog.EnableRaisingEvents) { newLog.onEntryWrittenHandler = oldLog.onEntryWrittenHandler; newLog.EnableRaisingEvents = true; } _underlyingEventLog = newLog; oldLog.Close(); } } /// <summary> /// The machine on which this event log resides. /// </summary> [ReadOnly(true)] [DefaultValue(".")] [SettingsBindable(true)] public string MachineName { get { return _underlyingEventLog.MachineName; } set { EventLogInternal newLog = new EventLogInternal(_underlyingEventLog.logName, value, _underlyingEventLog.sourceName, this); EventLogInternal oldLog = _underlyingEventLog; if (oldLog.EnableRaisingEvents) { newLog.onEntryWrittenHandler = oldLog.onEntryWrittenHandler; newLog.EnableRaisingEvents = true; } _underlyingEventLog = newLog; oldLog.Close(); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Browsable(false)] public long MaximumKilobytes { get => _underlyingEventLog.MaximumKilobytes; set => _underlyingEventLog.MaximumKilobytes = value; } [Browsable(false)] public OverflowAction OverflowAction { get => _underlyingEventLog.OverflowAction; } [Browsable(false)] public int MinimumRetentionDays { get => _underlyingEventLog.MinimumRetentionDays; } internal bool ComponentDesignMode { get => this.DesignMode; } internal object ComponentGetService(Type service) { return GetService(service); } /// <summary> /// Indicates if the component monitors the event log for changes. /// </summary> [Browsable(false)] [DefaultValue(false)] public bool EnableRaisingEvents { get => _underlyingEventLog.EnableRaisingEvents; set => _underlyingEventLog.EnableRaisingEvents = value; } /// <summary> /// The object used to marshal the event handler calls issued as a result of an EventLog change. /// </summary> [Browsable(false)] [DefaultValue(null)] public ISynchronizeInvoke SynchronizingObject { get => _underlyingEventLog.SynchronizingObject; set => _underlyingEventLog.SynchronizingObject = value; } /// <summary> /// The application name (source name) to use when writing to the event log. /// </summary> [ReadOnly(true)] [DefaultValue("")] [SettingsBindable(true)] public string Source { get => _underlyingEventLog.Source; set { EventLogInternal newLog = new EventLogInternal(_underlyingEventLog.Log, _underlyingEventLog.MachineName, CheckAndNormalizeSourceName(value), this); EventLogInternal oldLog = _underlyingEventLog; if (oldLog.EnableRaisingEvents) { newLog.onEntryWrittenHandler = oldLog.onEntryWrittenHandler; newLog.EnableRaisingEvents = true; } _underlyingEventLog = newLog; oldLog.Close(); } } /// <summary> /// Raised each time any application writes an entry to the event log. /// </summary> public event EntryWrittenEventHandler EntryWritten { add { _underlyingEventLog.EntryWritten += value; } remove { _underlyingEventLog.EntryWritten -= value; } } public void BeginInit() { _underlyingEventLog.BeginInit(); } public void Clear() { _underlyingEventLog.Clear(); } public void Close() { _underlyingEventLog.Close(); } public static void CreateEventSource(string source, string logName) { CreateEventSource(new EventSourceCreationData(source, logName, ".")); } [Obsolete("This method has been deprecated. Please use System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData) instead. http://go.microsoft.com/fwlink/?linkid=14202")] public static void CreateEventSource(string source, string logName, string machineName) { CreateEventSource(new EventSourceCreationData(source, logName, machineName)); } public static void CreateEventSource(EventSourceCreationData sourceData) { if (sourceData == null) throw new ArgumentNullException(nameof(sourceData)); string logName = sourceData.LogName; string source = sourceData.Source; string machineName = sourceData.MachineName; Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Checking arguments"); if (!SyntaxCheck.CheckMachineName(machineName)) { throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); } if (logName == null || logName.Length == 0) logName = "Application"; if (!ValidLogName(logName, false)) throw new ArgumentException(SR.BadLogName); if (source == null || source.Length == 0) throw new ArgumentException(SR.Format(SR.MissingParameter, nameof(source))); if (source.Length + EventLogKey.Length > 254) throw new ArgumentException(SR.Format(SR.ParameterTooLong, nameof(source), 254 - EventLogKey.Length)); Mutex mutex = null; RuntimeHelpers.PrepareConstrainedRegions(); try { SharedUtils.EnterMutex(eventLogMutexName, ref mutex); Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Calling SourceExists"); if (SourceExists(source, machineName, true)) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: SourceExists returned true"); if (".".Equals(machineName)) throw new ArgumentException(SR.Format(SR.LocalSourceAlreadyExists, source)); else throw new ArgumentException(SR.Format(SR.SourceAlreadyExists, source, machineName)); } Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Getting DllPath"); RegistryKey baseKey = null; RegistryKey eventKey = null; RegistryKey logKey = null; RegistryKey sourceLogKey = null; RegistryKey sourceKey = null; try { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Getting local machine regkey"); if (machineName == ".") baseKey = Registry.LocalMachine; else baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName); eventKey = baseKey.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\EventLog", true); if (eventKey == null) { if (!".".Equals(machineName)) throw new InvalidOperationException(SR.Format(SR.RegKeyMissing, "SYSTEM\\CurrentControlSet\\Services\\EventLog", logName, source, machineName)); else throw new InvalidOperationException(SR.Format(SR.LocalRegKeyMissing, "SYSTEM\\CurrentControlSet\\Services\\EventLog", logName, source)); } logKey = eventKey.OpenSubKey(logName, true); if (logKey == null && logName.Length >= 8) { string logNameFirst8 = logName.Substring(0, 8); if (string.Compare(logNameFirst8, "AppEvent", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(logNameFirst8, "SecEvent", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(logNameFirst8, "SysEvent", StringComparison.OrdinalIgnoreCase) == 0) throw new ArgumentException(SR.Format(SR.InvalidCustomerLogName, logName)); string sameLogName = FindSame8FirstCharsLog(eventKey, logName); if (sameLogName != null) throw new ArgumentException(SR.Format(SR.DuplicateLogName, logName, sameLogName)); } bool createLogKey = (logKey == null); if (createLogKey) { if (SourceExists(logName, machineName, true)) { if (".".Equals(machineName)) throw new ArgumentException(SR.Format(SR.LocalLogAlreadyExistsAsSource, logName)); else throw new ArgumentException(SR.Format(SR.LogAlreadyExistsAsSource, logName, machineName)); } logKey = eventKey.CreateSubKey(logName); SetSpecialLogRegValues(logKey, logName); // A source with the same name as the log has to be created // by default. It is the behavior expected by EventLog API. sourceLogKey = logKey.CreateSubKey(logName); SetSpecialSourceRegValues(sourceLogKey, sourceData); } if (logName != source) { if (!createLogKey) { SetSpecialLogRegValues(logKey, logName); } sourceKey = logKey.CreateSubKey(source); SetSpecialSourceRegValues(sourceKey, sourceData); } } finally { baseKey?.Close(); eventKey?.Close(); logKey?.Close(); sourceLogKey?.Close(); sourceKey?.Close(); } } finally { mutex?.ReleaseMutex(); mutex?.Close(); } } public static void Delete(string logName) { Delete(logName, "."); } public static void Delete(string logName, string machineName) { if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.InvalidParameterFormat, nameof(machineName)); if (logName == null || logName.Length == 0) throw new ArgumentException(SR.NoLogName); if (!ValidLogName(logName, false)) throw new InvalidOperationException(SR.BadLogName); RegistryKey eventlogkey = null; Mutex mutex = null; RuntimeHelpers.PrepareConstrainedRegions(); try { SharedUtils.EnterMutex(eventLogMutexName, ref mutex); try { eventlogkey = GetEventLogRegKey(machineName, true); if (eventlogkey == null) { throw new InvalidOperationException(SR.Format(SR.RegKeyNoAccess, "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\EventLog", machineName)); } using (RegistryKey logKey = eventlogkey.OpenSubKey(logName)) { if (logKey == null) throw new InvalidOperationException(SR.Format(SR.MissingLog, logName, machineName)); //clear out log before trying to delete it //that way, if we can't delete the log file, no entries will persist because it has been cleared EventLog logToClear = new EventLog(logName, machineName); try { logToClear.Clear(); } finally { logToClear.Close(); } string filename = null; try { //most of the time, the "File" key does not exist, but we'll still give it a whirl filename = (string)logKey.GetValue("File"); } catch { } if (filename != null) { try { File.Delete(filename); } catch { } } } // now delete the registry entry eventlogkey.DeleteSubKeyTree(logName); } finally { eventlogkey?.Close(); } } finally { mutex?.ReleaseMutex(); } } public static void DeleteEventSource(string source) { DeleteEventSource(source, "."); } public static void DeleteEventSource(string source, string machineName) { if (!SyntaxCheck.CheckMachineName(machineName)) { throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); } Mutex mutex = null; RuntimeHelpers.PrepareConstrainedRegions(); try { SharedUtils.EnterMutex(eventLogMutexName, ref mutex); RegistryKey key = null; // First open the key read only so we can do some checks. This is important so we get the same // exceptions even if we don't have write access to the reg key. using (key = FindSourceRegistration(source, machineName, true)) { if (key == null) { if (machineName == null) throw new ArgumentException(SR.Format(SR.LocalSourceNotRegistered, source)); else throw new ArgumentException(SR.Format(SR.SourceNotRegistered, source, machineName, "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\EventLog")); } // Check parent registry key (Event Log Name) and if it's equal to source, then throw an exception. // The reason: each log registry key must always contain subkey (i.e. source) with the same name. string keyname = key.Name; int index = keyname.LastIndexOf('\\'); if (string.Compare(keyname, index + 1, source, 0, keyname.Length - index, StringComparison.Ordinal) == 0) throw new InvalidOperationException(SR.Format(SR.CannotDeleteEqualSource, source)); } try { key = FindSourceRegistration(source, machineName, false); key.DeleteSubKeyTree(source); } finally { key?.Close(); } } finally { mutex?.ReleaseMutex(); } } protected override void Dispose(bool disposing) { _underlyingEventLog?.Dispose(disposing); base.Dispose(disposing); } public void EndInit() { _underlyingEventLog.EndInit(); } public static bool Exists(string logName) { return Exists(logName, "."); } public static bool Exists(string logName, string machineName) { if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameterFormat, nameof(machineName))); if (logName == null || logName.Length == 0) return false; RegistryKey eventkey = null; RegistryKey logKey = null; try { eventkey = GetEventLogRegKey(machineName, false); if (eventkey == null) return false; logKey = eventkey.OpenSubKey(logName, false); // try to find log file key immediately. return (logKey != null); } finally { eventkey?.Close(); logKey?.Close(); } } // Try to find log file name with the same 8 first characters. // Returns 'null' if no "same first 8 chars" log is found. logName.Length must be > 7 private static string FindSame8FirstCharsLog(RegistryKey keyParent, string logName) { string logNameFirst8 = logName.Substring(0, 8); string[] logNames = keyParent.GetSubKeyNames(); for (int i = 0; i < logNames.Length; i++) { string currentLogName = logNames[i]; if (currentLogName.Length >= 8 && string.Compare(currentLogName.Substring(0, 8), logNameFirst8, StringComparison.OrdinalIgnoreCase) == 0) return currentLogName; } return null; // not found } private static RegistryKey FindSourceRegistration(string source, string machineName, bool readOnly) { return FindSourceRegistration(source, machineName, readOnly, false); } private static RegistryKey FindSourceRegistration(string source, string machineName, bool readOnly, bool wantToCreate) { if (source != null && source.Length != 0) { RegistryKey eventkey = null; try { eventkey = GetEventLogRegKey(machineName, !readOnly); if (eventkey == null) { // there's not even an event log service on the machine. // or, more likely, we don't have the access to read the registry. return null; } StringBuilder inaccessibleLogs = null; // Most machines will return only { "Application", "System", "Security" }, // but you can create your own if you want. string[] logNames = eventkey.GetSubKeyNames(); for (int i = 0; i < logNames.Length; i++) { // see if the source is registered in this log. // NOTE: A source name must be unique across ALL LOGS! RegistryKey sourceKey = null; try { RegistryKey logKey = eventkey.OpenSubKey(logNames[i], /*writable*/!readOnly); if (logKey != null) { sourceKey = logKey.OpenSubKey(source, /*writable*/!readOnly); if (sourceKey != null) { // found it return logKey; } else { logKey.Close(); } } // else logKey is null, so we don't need to Close it } catch (UnauthorizedAccessException) { if (inaccessibleLogs == null) { inaccessibleLogs = new StringBuilder(logNames[i]); } else { inaccessibleLogs.Append(", "); inaccessibleLogs.Append(logNames[i]); } } catch (SecurityException) { if (inaccessibleLogs == null) { inaccessibleLogs = new StringBuilder(logNames[i]); } else { inaccessibleLogs.Append(", "); inaccessibleLogs.Append(logNames[i]); } } finally { sourceKey?.Close(); } } if (inaccessibleLogs != null) throw new SecurityException(SR.Format(wantToCreate ? SR.SomeLogsInaccessibleToCreate : SR.SomeLogsInaccessible, inaccessibleLogs.ToString())); } finally { eventkey?.Close(); } } return null; } public static EventLog[] GetEventLogs() { return GetEventLogs("."); } public static EventLog[] GetEventLogs(string machineName) { if (!SyntaxCheck.CheckMachineName(machineName)) { throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); } string[] logNames = null; RegistryKey eventkey = null; try { // we figure out what logs are on the machine by looking in the registry. eventkey = GetEventLogRegKey(machineName, false); if (eventkey == null) // there's not even an event log service on the machine. // or, more likely, we don't have the access to read the registry. throw new InvalidOperationException(SR.Format(SR.RegKeyMissingShort, EventLogKey, machineName)); // Most machines will return only { "Application", "System", "Security" }, // but you can create your own if you want. logNames = eventkey.GetSubKeyNames(); } finally { eventkey?.Close(); } // now create EventLog objects that point to those logs EventLog[] logs = new EventLog[logNames.Length]; for (int i = 0; i < logNames.Length; i++) { EventLog log = new EventLog(logNames[i], machineName); logs[i] = log; } return logs; } internal static RegistryKey GetEventLogRegKey(string machine, bool writable) { RegistryKey lmkey = null; try { if (machine.Equals(".")) { lmkey = Registry.LocalMachine; } else { lmkey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine); } if (lmkey != null) return lmkey.OpenSubKey(EventLogKey, writable); } finally { lmkey?.Close(); } return null; } internal static string GetDllPath(string machineName) { return Path.Combine(SharedUtils.GetLatestBuildDllDirectory(machineName), DllName); } public static bool SourceExists(string source) { return SourceExists(source, "."); } public static bool SourceExists(string source, string machineName) { return SourceExists(source, machineName, false); } internal static bool SourceExists(string source, string machineName, bool wantToCreate) { if (!SyntaxCheck.CheckMachineName(machineName)) { throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); } using (RegistryKey keyFound = FindSourceRegistration(source, machineName, true, wantToCreate)) { return (keyFound != null); } } public static string LogNameFromSourceName(string source, string machineName) { return _InternalLogNameFromSourceName(source, machineName); } internal static string _InternalLogNameFromSourceName(string source, string machineName) { using (RegistryKey key = FindSourceRegistration(source, machineName, true)) { if (key == null) return string.Empty; else { string name = key.Name; int whackPos = name.LastIndexOf('\\'); // this will work even if whackPos is -1 return name.Substring(whackPos + 1); } } } public void ModifyOverflowPolicy(OverflowAction action, int retentionDays) { _underlyingEventLog.ModifyOverflowPolicy(action, retentionDays); } public void RegisterDisplayName(string resourceFile, long resourceId) { _underlyingEventLog.RegisterDisplayName(resourceFile, resourceId); } private static void SetSpecialLogRegValues(RegistryKey logKey, string logName) { // Set all the default values for this log. AutoBackupLogfiles only makes sense in // Win2000 SP4, WinXP SP1, and Win2003, but it should alright elsewhere. // Since we use this method on the existing system logs as well as our own, // we need to make sure we don't overwrite any existing values. if (logKey.GetValue("MaxSize") == null) logKey.SetValue("MaxSize", DefaultMaxSize, RegistryValueKind.DWord); if (logKey.GetValue("AutoBackupLogFiles") == null) logKey.SetValue("AutoBackupLogFiles", 0, RegistryValueKind.DWord); } private static void SetSpecialSourceRegValues(RegistryKey sourceLogKey, EventSourceCreationData sourceData) { if (string.IsNullOrEmpty(sourceData.MessageResourceFile)) sourceLogKey.SetValue("EventMessageFile", GetDllPath(sourceData.MachineName), RegistryValueKind.ExpandString); else sourceLogKey.SetValue("EventMessageFile", FixupPath(sourceData.MessageResourceFile), RegistryValueKind.ExpandString); if (!string.IsNullOrEmpty(sourceData.ParameterResourceFile)) sourceLogKey.SetValue("ParameterMessageFile", FixupPath(sourceData.ParameterResourceFile), RegistryValueKind.ExpandString); if (!string.IsNullOrEmpty(sourceData.CategoryResourceFile)) { sourceLogKey.SetValue("CategoryMessageFile", FixupPath(sourceData.CategoryResourceFile), RegistryValueKind.ExpandString); sourceLogKey.SetValue("CategoryCount", sourceData.CategoryCount, RegistryValueKind.DWord); } } private static string FixupPath(string path) { if (path[0] == '%') return path; else return Path.GetFullPath(path); } internal static string TryFormatMessage(SafeLibraryHandle hModule, uint messageNum, string[] insertionStrings) { if (insertionStrings.Length == 0) { return UnsafeTryFormatMessage(hModule, messageNum, insertionStrings); } // If you pass in an empty array UnsafeTryFormatMessage will just pull out the message. string formatString = UnsafeTryFormatMessage(hModule, messageNum, Array.Empty<string>()); if (formatString == null) { return null; } int largestNumber = 0; for (int i = 0; i < formatString.Length; i++) { if (formatString[i] == '%') { if (formatString.Length > i + 1) { StringBuilder sb = new StringBuilder(); while (i + 1 < formatString.Length && Char.IsDigit(formatString[i + 1])) { sb.Append(formatString[i + 1]); i++; } // move over the non number character that broke us out of the loop i++; if (sb.Length > 0) { int num = -1; if (Int32.TryParse(sb.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out num)) { largestNumber = Math.Max(largestNumber, num); } } } } } // Replacement strings are 1 indexed. if (largestNumber > insertionStrings.Length) { string[] newStrings = new string[largestNumber]; Array.Copy(insertionStrings, newStrings, insertionStrings.Length); for (int i = insertionStrings.Length; i < newStrings.Length; i++) { newStrings[i] = "%" + (i + 1); } insertionStrings = newStrings; } return UnsafeTryFormatMessage(hModule, messageNum, insertionStrings); } // FormatMessageW will AV if you don't pass in enough format strings. If you call TryFormatMessage we ensure insertionStrings // is long enough. You don't want to call this directly unless you're sure insertionStrings is long enough! internal static string UnsafeTryFormatMessage(SafeLibraryHandle hModule, uint messageNum, string[] insertionStrings) { string msg = null; int msgLen = 0; StringBuilder buf = new StringBuilder(1024); int flags = Interop.Kernel32.FORMAT_MESSAGE_FROM_HMODULE | Interop.Kernel32.FORMAT_MESSAGE_ARGUMENT_ARRAY; IntPtr[] addresses = new IntPtr[insertionStrings.Length]; GCHandle[] handles = new GCHandle[insertionStrings.Length]; GCHandle stringsRoot = GCHandle.Alloc(addresses, GCHandleType.Pinned); if (insertionStrings.Length == 0) { flags |= Interop.Kernel32.FORMAT_MESSAGE_IGNORE_INSERTS; } try { for (int i = 0; i < handles.Length; i++) { handles[i] = GCHandle.Alloc(insertionStrings[i], GCHandleType.Pinned); addresses[i] = handles[i].AddrOfPinnedObject(); } int lastError = Interop.Kernel32.ERROR_INSUFFICIENT_BUFFER; while (msgLen == 0 && lastError == Interop.Kernel32.ERROR_INSUFFICIENT_BUFFER) { msgLen = Interop.Kernel32.FormatMessage( flags, hModule, messageNum, 0, buf, buf.Capacity, addresses); if (msgLen == 0) { lastError = Marshal.GetLastWin32Error(); if (lastError == Interop.Kernel32.ERROR_INSUFFICIENT_BUFFER) buf.Capacity = buf.Capacity * 2; } } } catch { msgLen = 0; // return empty on failure } finally { for (int i = 0; i < handles.Length; i++) { if (handles[i].IsAllocated) handles[i].Free(); } stringsRoot.Free(); } if (msgLen > 0) { msg = buf.ToString(); // chop off a single CR/LF pair from the end if there is one. FormatMessage always appends one extra. if (msg.Length > 1 && msg[msg.Length - 1] == '\n') msg = msg.Substring(0, msg.Length - 2); } return msg; } // CharIsPrintable used to be Char.IsPrintable, but Jay removed it and // is forcing people to use the Unicode categories themselves. Copied // the code here. private static bool CharIsPrintable(char c) { UnicodeCategory uc = Char.GetUnicodeCategory(c); return (!(uc == UnicodeCategory.Control) || (uc == UnicodeCategory.Format) || (uc == UnicodeCategory.LineSeparator) || (uc == UnicodeCategory.ParagraphSeparator) || (uc == UnicodeCategory.OtherNotAssigned)); } internal static bool ValidLogName(string logName, bool ignoreEmpty) { // No need to trim here since the next check will verify that there are no spaces. // We need to ignore the empty string as an invalid log name sometimes because it can // be passed in from our default constructor. if (logName.Length == 0 && !ignoreEmpty) return false; //any space, backslash, asterisk, or question mark is bad //any non-printable characters are also bad foreach (char c in logName) if (!CharIsPrintable(c) || (c == '\\') || (c == '*') || (c == '?')) return false; return true; } public void WriteEntry(string message) { WriteEntry(message, EventLogEntryType.Information, (short)0, 0, null); } public static void WriteEntry(string source, string message) { WriteEntry(source, message, EventLogEntryType.Information, (short)0, 0, null); } public void WriteEntry(string message, EventLogEntryType type) { WriteEntry(message, type, (short)0, 0, null); } public static void WriteEntry(string source, string message, EventLogEntryType type) { WriteEntry(source, message, type, (short)0, 0, null); } public void WriteEntry(string message, EventLogEntryType type, int eventID) { WriteEntry(message, type, eventID, 0, null); } public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID) { WriteEntry(source, message, type, eventID, 0, null); } public void WriteEntry(string message, EventLogEntryType type, int eventID, short category) { WriteEntry(message, type, eventID, category, null); } public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID, short category) { WriteEntry(source, message, type, eventID, category, null); } public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID, short category, byte[] rawData) { using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source))) { log.WriteEntry(message, type, eventID, category, rawData); } } public void WriteEntry(string message, EventLogEntryType type, int eventID, short category, byte[] rawData) { _underlyingEventLog.WriteEntry(message, type, eventID, category, rawData); } public void WriteEvent(EventInstance instance, params Object[] values) { WriteEvent(instance, null, values); } public void WriteEvent(EventInstance instance, byte[] data, params Object[] values) { _underlyingEventLog.WriteEvent(instance, data, values); } public static void WriteEvent(string source, EventInstance instance, params Object[] values) { using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source))) { log.WriteEvent(instance, null, values); } } public static void WriteEvent(string source, EventInstance instance, byte[] data, params Object[] values) { using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source))) { log.WriteEvent(instance, data, values); } } // The EventLog.set_Source used to do some normalization and throw some exceptions. We mimic that behavior here. private static string CheckAndNormalizeSourceName(string source) { if (source == null) source = string.Empty; // this 254 limit is the max length of a registry key. if (source.Length + EventLogKey.Length > 254) throw new ArgumentException(SR.Format(SR.ParameterTooLong, nameof(source), 254 - EventLogKey.Length)); return source; } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Management; using System.Globalization; using System.Data; using System.Threading; using System.Resources; namespace HWD { public delegate void addRowItemDelegate(DataRow r); public class Reporter : System.Windows.Forms.Form { private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.Button button1; private System.Windows.Forms.DataGrid dataGrid1; private System.Windows.Forms.ProgressBar progressBar1; private System.Windows.Forms.Button button2; private HWD.userData userData1; private System.Data.DataTable dt; private System.Data.DataView dataView1; public bool anotherLogin; public string username; public string password; private ManagementObjectSearcher query; private ManagementObjectCollection queryCollection; private System.Management.ObjectQuery oq; private ConnectionOptions co = new ConnectionOptions(); private string strQuery; private string caption; private string toprint; private ReportPrinting.ReportDocument reportDocument1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtValue; private System.Windows.Forms.Label label3; private ResourceManager m_ResourceManager; public HWD.userData dataSet { set { this.userData1 = value; } get { return this.userData1; } } public ResourceManager rsxmgr { set { this.m_ResourceManager = value; } } private System.ComponentModel.Container components = null; public Reporter() { InitializeComponent(); } protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Reporter)); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.button1 = new System.Windows.Forms.Button(); this.dataGrid1 = new System.Windows.Forms.DataGrid(); this.dataView1 = new System.Data.DataView(); this.progressBar1 = new System.Windows.Forms.ProgressBar(); this.button2 = new System.Windows.Forms.Button(); this.userData1 = new HWD.userData(); this.reportDocument1 = new ReportPrinting.ReportDocument(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.txtValue = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dataView1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.userData1)).BeginInit(); this.SuspendLayout(); // // comboBox1 // this.comboBox1.BackColor = System.Drawing.Color.OldLace; this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox1.Items.AddRange(new object[] { "Printers", "MAC Address", "Application*", "HotFix*"}); this.comboBox1.Location = new System.Drawing.Point(8, 24); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(216, 21); this.comboBox1.TabIndex = 0; // // button1 // this.button1.BackColor = System.Drawing.Color.SaddleBrown; this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button1.ForeColor = System.Drawing.Color.OldLace; this.button1.Location = new System.Drawing.Point(424, 8); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(120, 24); this.button1.TabIndex = 1; this.button1.Text = "Scan"; this.button1.Click += new System.EventHandler(this.button1_Click); // // dataGrid1 // this.dataGrid1.AlternatingBackColor = System.Drawing.Color.OldLace; this.dataGrid1.BackColor = System.Drawing.Color.OldLace; this.dataGrid1.BackgroundColor = System.Drawing.Color.Tan; this.dataGrid1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.dataGrid1.CaptionBackColor = System.Drawing.Color.SaddleBrown; this.dataGrid1.CaptionForeColor = System.Drawing.Color.OldLace; this.dataGrid1.CaptionText = "Reporter"; this.dataGrid1.DataMember = ""; this.dataGrid1.DataSource = this.dataView1; this.dataGrid1.Dock = System.Windows.Forms.DockStyle.Bottom; this.dataGrid1.FlatMode = true; this.dataGrid1.Font = new System.Drawing.Font("Tahoma", 8F); this.dataGrid1.ForeColor = System.Drawing.Color.DarkSlateGray; this.dataGrid1.GridLineColor = System.Drawing.Color.Tan; this.dataGrid1.HeaderBackColor = System.Drawing.Color.Wheat; this.dataGrid1.HeaderFont = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.dataGrid1.HeaderForeColor = System.Drawing.Color.SaddleBrown; this.dataGrid1.LinkColor = System.Drawing.Color.DarkSlateBlue; this.dataGrid1.Location = new System.Drawing.Point(0, 101); this.dataGrid1.Name = "dataGrid1"; this.dataGrid1.ParentRowsBackColor = System.Drawing.Color.OldLace; this.dataGrid1.ParentRowsForeColor = System.Drawing.Color.DarkSlateGray; this.dataGrid1.ReadOnly = true; this.dataGrid1.SelectionBackColor = System.Drawing.Color.SlateGray; this.dataGrid1.SelectionForeColor = System.Drawing.Color.White; this.dataGrid1.Size = new System.Drawing.Size(560, 376); this.dataGrid1.TabIndex = 2; // // progressBar1 // this.progressBar1.Location = new System.Drawing.Point(8, 72); this.progressBar1.Name = "progressBar1"; this.progressBar1.Size = new System.Drawing.Size(544, 24); this.progressBar1.Step = 1; this.progressBar1.TabIndex = 3; // // button2 // this.button2.BackColor = System.Drawing.Color.SaddleBrown; this.button2.Enabled = false; this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button2.ForeColor = System.Drawing.Color.OldLace; this.button2.Location = new System.Drawing.Point(424, 40); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(120, 24); this.button2.TabIndex = 4; this.button2.Text = "Preview"; this.button2.Click += new System.EventHandler(this.button2_Click); // // userData1 // this.userData1.DataSetName = "userData"; this.userData1.Locale = new System.Globalization.CultureInfo("es-MX"); // // reportDocument1 // this.reportDocument1.Body = null; this.reportDocument1.DocumentUnit = System.Drawing.GraphicsUnit.Inch; this.reportDocument1.PageFooter = null; this.reportDocument1.PageFooterMaxHeight = 1F; this.reportDocument1.PageHeader = null; this.reportDocument1.PageHeaderMaxHeight = 1F; this.reportDocument1.ReportMaker = null; this.reportDocument1.ResetAfterPrint = true; // // label1 // this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(128, 16); this.label1.TabIndex = 5; this.label1.Text = "Report"; // // label2 // this.label2.Location = new System.Drawing.Point(232, 8); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(80, 16); this.label2.TabIndex = 6; this.label2.Text = "Value"; // // txtValue // this.txtValue.BackColor = System.Drawing.Color.OldLace; this.txtValue.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtValue.Location = new System.Drawing.Point(232, 24); this.txtValue.Name = "txtValue"; this.txtValue.Size = new System.Drawing.Size(184, 20); this.txtValue.TabIndex = 7; this.txtValue.Text = ""; // // label3 // this.label3.Location = new System.Drawing.Point(8, 48); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(280, 16); this.label3.TabIndex = 8; this.label3.Text = "* Need a value"; // // Reporter // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackColor = System.Drawing.Color.Tan; this.ClientSize = new System.Drawing.Size(560, 477); this.Controls.Add(this.label3); this.Controls.Add(this.txtValue); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.button2); this.Controls.Add(this.progressBar1); this.Controls.Add(this.dataGrid1); this.Controls.Add(this.button1); this.Controls.Add(this.comboBox1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "Reporter"; this.Text = "HWD - Reporter"; this.Load += new System.EventHandler(this.Reporter_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dataView1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.userData1)).EndInit(); this.ResumeLayout(false); } #endregion private void Reporter_Load(object sender, System.EventArgs e) { this.dt = this.userData1.Tables["MWD"]; this.dataView1.Table = this.dt; this.UpdateUI(); } private void UpdateUI() { this.button1.Text = m_ResourceManager.GetString("rbutton1"); this.button2.Text = m_ResourceManager.GetString("rbutton2"); } private void button1_Click(object sender, System.EventArgs e) { this.dt.Rows.Clear(); string app = this.txtValue.Text; switch(this.comboBox1.SelectedItem.ToString()) { case "Printers": this.progressBar1.Maximum = this.userData1.Tables["HWD"].Rows.Count; this.strQuery = "SELECT * FROM Win32_Printer"; this.caption = "Caption"; foreach(DataRow drs in this.userData1.Tables["HWD"].Rows) { SystemScan par = new SystemScan(drs["Username"].ToString(), drs["ComputerName"].ToString()); ThreadPool.QueueUserWorkItem(new WaitCallback(ScanItems), par); } this.button2.Enabled = true; this.toprint = "Printers"; break; case "MAC Address": this.progressBar1.Maximum = this.userData1.Tables["HWD"].Rows.Count; this.strQuery = "SELECT * FROM Win32_NetworkAdapter"; this.caption = "MACAddress"; foreach(DataRow drs in this.userData1.Tables["HWD"].Rows) { SystemScan par = new SystemScan(drs["Username"].ToString(), drs["ComputerName"].ToString()); ThreadPool.QueueUserWorkItem(new WaitCallback(ScanItems), par); } this.button2.Enabled = true; this.toprint = "MAC Address"; break; case "Application*": if (app.Length > 0) { this.progressBar1.Maximum = this.userData1.Tables["HWD"].Rows.Count; this.strQuery = "SELECT * FROM Win32_Product WHERE Name like '%" + app + "%'"; this.caption = "Caption"; foreach(DataRow drs in this.userData1.Tables["HWD"].Rows) { SystemScan par = new SystemScan(drs["Username"].ToString(), drs["ComputerName"].ToString()); ThreadPool.QueueUserWorkItem(new WaitCallback(ScanItems), par); } this.button2.Enabled = true; this.toprint = "Application " + app; } else { MessageBox.Show("This reporter needs a value"); } break; case "HotFix*": if (app.Length > 0) { this.progressBar1.Maximum = this.userData1.Tables["HWD"].Rows.Count; this.strQuery = "SELECT * FROM Win32_QuickFixEngineering WHERE Description like '%" + app + "%' OR HotFixID like '%" + app + "%'"; this.caption = "Caption"; foreach(DataRow drs in this.userData1.Tables["HWD"].Rows) { SystemScan par = new SystemScan(drs["Username"].ToString(), drs["ComputerName"].ToString()); ThreadPool.QueueUserWorkItem(new WaitCallback(ScanItems), par); } this.button2.Enabled = true; this.toprint = "HotFix " + app; } else { MessageBox.Show("This reporter needs a value"); } break; default: MessageBox.Show("What are you trying to do?"); break; } this.button1.Enabled = false; } private void addRow(DataRow r) { this.dt.Rows.Add(r); } private void ScanItems(Object pars) { SystemScan par = (SystemScan) pars; this.progressBar1.Value++; try { if (this.anotherLogin && this.username.Length > 0) { co.Username = this.username; co.Password = this.password; } System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\" + par.ComputerName + "\\root\\cimv2", co); oq = new System.Management.ObjectQuery(strQuery); query = new ManagementObjectSearcher(ms,oq); queryCollection = query.Get(); foreach(ManagementObject mo in queryCollection) { DataRow dr = this.dt.NewRow(); dr["ComputerName"] = par.ComputerName; dr["UserName"] = par.Username; dr["ItemCaption"] = mo[caption].ToString(); Invoke(new addRowItemDelegate(addRow),new object[]{dr}); } } catch { return; } } private void button2_Click(object sender, System.EventArgs e) { if (this.dataView1.Table.Rows.Count > 1) { this.Cursor = Cursors.WaitCursor; try { ReportMWD tmpRep = new ReportMWD(); tmpRep.dataview = this.dataView1; tmpRep.Title = "Report of - " + this.toprint; preview pre = new preview(); pre.irp = tmpRep; pre.ShowDialog(); } catch { MessageBox.Show(this, "Unable Report", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } this.Cursor = Cursors.Default; } } } public class SystemScan { public string Username; public string ComputerName; public SystemScan(string user, string machine) { Username = user; ComputerName = machine; } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using System.IO; using NodeDefinition; using Pathfinding; using Particles2DPipelineSample; using GameStateManagement; namespace HackPrototype { class HackGameBoard_CollapseController { StringBuilder timerString = new StringBuilder(); HackGameTimer collapseTimer; Point boardcenter; bool lerpingIn = false; bool lerpingOut = false; bool firingFlash = false; bool playActivationSound = false; const float lerpInOutTime = 0.5f; bool collapsingFinal = false; HackGameTimer collapseFinalTimer = new HackGameTimer(1.0f); HackGameForwardLerpDrawHelper lerpInOut = new HackGameForwardLerpDrawHelper(0,0,0,0,Color.White,Color.White,0,Vector2.Zero,Vector2.Zero,0); HackGameForwardLerpDrawHelper lerpFlash = new HackGameForwardLerpDrawHelper(0, 0, 0, 0, Color.White, Color.White, 0, Vector2.Zero, Vector2.Zero, 0); HackGameTimer lerpFlashTimer = new HackGameTimer(0); List<HackGameBoard_CollapseTarget> targets = new List<HackGameBoard_CollapseTarget>(); int max_target_levels; int max_targets_value; int current_targets_value; float timePerTargetLevel = 0; float currentTargetTimer = 0; List<HackGameBoard_CollapseTarget> targetsToFire = new List<HackGameBoard_CollapseTarget>(); float setTime; bool active = false; bool frozen = false; bool isCollapsed = false; bool stopLoopSound = false; public HackGameBoard_CollapseController(float time, HackGameBoard board, Point center) { setTime = time; PopulateTargets(board, center); } private void PopulateTargets(HackGameBoard board, Point center) { PathFinder pf = new PathFinder(); pf.Initialize(board); boardcenter = center; for (int i = 0; i < board.GetGameBoardSize(); i++) { for(int k = 0; k < board.GetGameBoardSize(); k++) { if (board.board[i, k].type == HackGameBoardElementBaseType.HackGameBoardElementBaseType_Node) { //pathfind to the center. pf.Reset(new Point(k, i), center); bool success = pf.SearchPath(); if (success == true) { HackGameBoard_CollapseTarget target = new HackGameBoard_CollapseTarget(); target.location = new Point(k, i); target.level = pf.FinalPath().Count - 1; target.delay = (float)board.r.NextDouble(); targets.Add(target); } } } } int maxtargets = 0; max_target_levels = 0; targets.Sort(CompareTargetsByLevel); foreach (HackGameBoard_CollapseTarget target in targets) { if (target.level > maxtargets) { maxtargets = target.level; max_target_levels++; } } max_targets_value = maxtargets; } private static int CompareTargetsByLevel(HackGameBoard_CollapseTarget x, HackGameBoard_CollapseTarget y) { if (x.level > y.level) { return 1; } if (y.level > x.level) { return -1; } else { return 0; } } private void UpdateTimerString() { timerString.Remove(0, timerString.Length); if (collapseTimer.GetLifeTimeLeft() <= 0) { timerString.Append("00.0"); } else { decimal timeleft = (decimal)collapseTimer.GetLifeTimeLeft(); decimal rounddown = (decimal.Floor(timeleft)); if (collapseTimer.GetLifeTimeLeft() < 10.0f) { timerString.Append('0'); } timerString.Append((int)(rounddown)); timerString.Append('.'); timerString.Append((int)(decimal.Floor((timeleft - rounddown) * 10))); } } public void Freeze() { frozen = true; } public void Unfreeze() { frozen = false; } public bool HasCollapsed() { return isCollapsed; } public bool IsActive() { return active; } public void Activate(HackGameBoard board) { if (!active) { LerpIn(); playActivationSound = true; board.ticker.SetOverride("..NETWORK COLLAPSE..EXIT IMMEDIATELY..NETWORK COLLAPSE..EXIT IMMEDIATELY.."); } active = true; ResetTargets(); decimal timeleft = (decimal)collapseTimer.GetLifeTimeLeft(); decimal rounddown = (decimal.Floor(timeleft)); decimal splitsecond = decimal.Floor((timeleft - rounddown) * 10); if ((float)splitsecond == 0) { lerpFlashTimer.Reset(1.0f); } else { lerpFlashTimer.Reset((float)splitsecond / 10.0f); } if (collapseTimer == null) { collapseTimer = new HackGameTimer(setTime); UpdateTimerString(); } //apply bonus float nodeValueMultiplier = 2.0f; if (board.IsBonusRound()) { nodeValueMultiplier = 4.0f; } board.ApplyMultiplier(nodeValueMultiplier); //this needs to be an event with a delay int multInt = (int)nodeValueMultiplier; string multString = "Nodes " + multInt + "x Value!"; board.AddNewTextEvent(multString, 2.0f); } public void Deactivate(HackGameBoard board) { if (active) { LerpOut(); } board.ticker.ClearOverride(); active = false; stopLoopSound = true; } private void LerpIn() { if (!lerpingIn) { lerpingIn = true; if (lerpingOut) { lerpInOut.Reset(lerpInOutTime - lerpInOut.GetLifeTimeLeft(), lerpInOut.CurrentScale(), 1.0f, lerpInOutTime - lerpInOut.GetLifeTimeLeft(), Color.White, Color.White, lerpInOutTime, Vector2.Zero, Vector2.Zero, lerpInOutTime); lerpingOut = false; } else { lerpInOut.Reset(lerpInOutTime, 0, 1.0f, lerpInOutTime, Color.White, Color.White, lerpInOutTime, Vector2.Zero, Vector2.Zero, lerpInOutTime); } } } private void LerpOut() { if (!lerpingOut) { lerpingOut = true; if (lerpingIn) { lerpInOut.Reset(lerpInOutTime - lerpInOut.GetLifeTimeLeft(), lerpInOut.CurrentScale(), 0.0f, lerpInOutTime - lerpInOut.GetLifeTimeLeft(), Color.White, Color.White, lerpInOutTime, Vector2.Zero, Vector2.Zero, lerpInOutTime); lerpingOut = false; } else { lerpInOut.Reset(lerpInOutTime, 1.0f, 0, lerpInOutTime, Color.White, Color.White, lerpInOutTime, Vector2.Zero, Vector2.Zero, lerpInOutTime); } } } private void FireFlash(float nextFlashTime) { lerpFlash.Reset(0.5f, 1.0f, 1.0f, 0.5f, new Color(0.7f, 0.3f, 0.3f, 0.3f), new Color(0.3f, 0.3f, 0.3f, 0.3f), 0.5f, Vector2.Zero, Vector2.Zero, 0.5f); lerpFlashTimer.Reset(nextFlashTime); firingFlash = true; } public void SetTimer(float newtimer) { setTime = newtimer; ResetTargets(); collapseTimer = new HackGameTimer(setTime); UpdateTimerString(); } private void ResetTargets() { current_targets_value = max_targets_value; timePerTargetLevel = (setTime - 10.0f) / max_target_levels; //link up the final collapse time to ten seconds after the last layer has been placed. currentTargetTimer = 0; //fire right away } public void DrawSelf(HackNodeGameBoardMedia drawing, SpriteBatch spriteBatch, GraphicsDevice GraphicsDevice, HackGameAgent_Player player) { if (active || lerpingOut) { //standard drawing Vector2 fontSize = drawing.Collapse_GiantNumbers_Font.MeasureString(timerString); Vector2 finalPos = new Vector2(GraphicsDevice.Viewport.Width / 2 - fontSize.X / 2, GraphicsDevice.Viewport.Height / 2); Vector2 finalScale = Vector2.One; if (lerpingIn || lerpingOut) { finalScale.Y = lerpInOut.CurrentScale(); } if (firingFlash) { firingFlash = false; drawing.TimerTickSound.Play(); } if (playActivationSound) { playActivationSound = false; drawing.StartWarningLoopSound(); } Color finalColor = lerpFlash.IsAlive() ? lerpFlash.CurrentColor() : new Color(0.3f, 0.3f, 0.3f, 0.3f); if(collapsingFinal == true) { Vector4 finalColorExtra = finalColor.ToVector4(); finalColorExtra.X = MathHelper.Clamp(finalColorExtra.X + (1.0f - collapseFinalTimer.GetLifeTimeLeft()), 0, 1.0f); finalColorExtra.W = MathHelper.Clamp(finalColorExtra.W + (1.0f - collapseFinalTimer.GetLifeTimeLeft()), 0, 1.0f); finalColor = new Color(finalColorExtra); } spriteBatch.DrawString(drawing.Collapse_GiantNumbers_Font, timerString, finalPos, finalColor, 0, new Vector2(0, fontSize.Y / 2), finalScale, SpriteEffects.None, 0); } if(stopLoopSound == true) { drawing.StopWarningLoopSound(); stopLoopSound = false; } } /* public void UpdateSelf(HackGameBoard board, GameTime time) { if (active && !frozen) { collapseTimer.Update(time); UpdateTimerString(); lerpFlash.Update(time); lerpFlashTimer.Update(time); if (!lerpFlashTimer.IsAlive()) { FireFlash(1.0f); } if (lerpingIn || lerpingOut) { lerpInOut.Update(time); if (!lerpInOut.IsAlive()) { lerpingIn = false; lerpingOut = false; } } if (!collapseTimer.IsAlive()) { CollapseLevel(); } else { currentTargetTimer -= (float)time.ElapsedGameTime.TotalSeconds; if (currentTargetTimer <= 0) { //time to fire off another set of collapsers FireCollapsers(); currentTargetTimer = timePerTargetLevel; current_targets_value--; } //fire ready targets List<HackGameBoard_CollapseTarget> dead = new List<HackGameBoard_CollapseTarget>(); for (int i = 0; i < targetsToFire.Count; i++ ) { targetsToFire[i].delay -= (float)time.ElapsedGameTime.TotalSeconds; if (targetsToFire[i].delay <= 0) { HackGameAgent_Collapser collapser = new HackGameAgent_Collapser(board, MathHelper.Lerp(05.0f, 10.0f,(float)board.r.NextDouble()), targetsToFire[i].location); collapser.SpawnIn(); board.AddAgent(collapser); dead.Add(targetsToFire[i]); } } for (int i = 0; i < dead.Count; i++) { targetsToFire.Remove(dead[i]); } } } } */ public void UpdateSelf(HackGameBoard board, GameTime time) { if (collapsingFinal == true) { collapseFinalTimer.Update(time); if (!collapseFinalTimer.IsAlive()) { FinalCollapse(); } } lerpInOut.Update(time); if (lerpingIn || lerpingOut) { if (!lerpInOut.IsAlive()) { lerpingIn = false; lerpingOut = false; } } if (active && !frozen && !lerpingIn) { collapseTimer.Update(time); UpdateTimerString(); lerpFlash.Update(time); lerpFlashTimer.Update(time); if (!lerpFlashTimer.IsAlive()) { FireFlash(1.0f); } UpdateCollapsers(board, time); } } private void UpdateCollapsers(HackGameBoard board, GameTime time) { if (!collapseTimer.IsAlive()) { CollapseLevel(board); } else { currentTargetTimer -= (float)time.ElapsedGameTime.TotalSeconds; if (currentTargetTimer <= 0) { //time to fire off another set of collapsers FireCollapsers(); currentTargetTimer = timePerTargetLevel; current_targets_value--; } //fire ready targets List<HackGameBoard_CollapseTarget> dead = new List<HackGameBoard_CollapseTarget>(); for (int i = 0; i < targetsToFire.Count; i++) { targetsToFire[i].delay -= (float)time.ElapsedGameTime.TotalSeconds; if (targetsToFire[i].delay <= 0) { HackGameAgent_Collapser collapser = new HackGameAgent_Collapser(board, MathHelper.Lerp(05.0f, 10.0f, (float)board.r.NextDouble()), targetsToFire[i].location); collapser.SpawnIn(); board.AddAgent(collapser); dead.Add(targetsToFire[i]); } } for (int i = 0; i < dead.Count; i++) { targetsToFire.Remove(dead[i]); } } } private void FireCollapsers() { //we're at level x. get to level y which is either the next highest level that has at least one representative in the list or is => max int i; bool found = false; for (i = current_targets_value; i > 0; i--) { foreach (HackGameBoard_CollapseTarget target in targets) { if (target.level == i) { found = true; //fire this! FireCollapserItem(target); } } if (found) { current_targets_value = i; return; } } //we dropped off the end of the list. //bummer. } private void FireCollapserItem(HackGameBoard_CollapseTarget target) { targetsToFire.Add(target); } private void CollapseLevel(HackGameBoard board) { HackGameAgent_Collapser collapser = new HackGameAgent_Collapser(board, 1.0f, boardcenter); collapser.SpawnIn(); board.AddAgent(collapser); collapsingFinal = true; Freeze(); } private void FinalCollapse() { isCollapsed = true; stopLoopSound = true; } } public class HackGameBoard_CollapseTarget { public Point location; public int level; public float delay; public float timer; } }
// // XmlValueConverter.cs // // Author: // Atsushi Enomoto <atsushi@ximian.com> // // (C)2004 Novell Inc, // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using System; namespace Mono.System.Xml.Schema { internal abstract class XmlValueConverter { [MonoTODO] protected XmlValueConverter () { } public abstract object ChangeType (bool value, Type type); public abstract object ChangeType (DateTime value, Type type); public abstract object ChangeType (decimal value, Type type); public abstract object ChangeType (double value, Type type); public abstract object ChangeType (int value, Type type); public abstract object ChangeType (long value, Type type); public abstract object ChangeType (object value, Type type); public abstract object ChangeType (float value, Type type); public abstract object ChangeType (string value, Type type); public abstract object ChangeType (object value, Type type, IXmlNamespaceResolver nsResolver); public abstract object ChangeType (string value, Type type, IXmlNamespaceResolver nsResolver); public abstract bool ToBoolean (bool value); public abstract bool ToBoolean (DateTime value); public abstract bool ToBoolean (decimal value); public abstract bool ToBoolean (double value); public abstract bool ToBoolean (int value); public abstract bool ToBoolean (long value); public abstract bool ToBoolean (object value); public abstract bool ToBoolean (float value); public abstract bool ToBoolean (string value); public abstract DateTime ToDateTime (bool value); public abstract DateTime ToDateTime (DateTime value); public abstract DateTime ToDateTime (decimal value); public abstract DateTime ToDateTime (double value); public abstract DateTime ToDateTime (int value); public abstract DateTime ToDateTime (long value); public abstract DateTime ToDateTime (object value); public abstract DateTime ToDateTime (float value); public abstract DateTime ToDateTime (string value); public abstract decimal ToDecimal (bool value); public abstract decimal ToDecimal (DateTime value); public abstract decimal ToDecimal (decimal value); public abstract decimal ToDecimal (double value); public abstract decimal ToDecimal (int value); public abstract decimal ToDecimal (long value); public abstract decimal ToDecimal (object value); public abstract decimal ToDecimal (float value); public abstract decimal ToDecimal (string value); public abstract double ToDouble (bool value); public abstract double ToDouble (DateTime value); public abstract double ToDouble (decimal value); public abstract double ToDouble (double value); public abstract double ToDouble (int value); public abstract double ToDouble (long value); public abstract double ToDouble (object value); public abstract double ToDouble (float value); public abstract double ToDouble (string value); public abstract int ToInt32 (bool value); public abstract int ToInt32 (DateTime value); public abstract int ToInt32 (decimal value); public abstract int ToInt32 (double value); public abstract int ToInt32 (int value); public abstract int ToInt32 (long value); public abstract int ToInt32 (object value); public abstract int ToInt32 (float value); public abstract int ToInt32 (string value); public abstract long ToInt64 (bool value); public abstract long ToInt64 (DateTime value); public abstract long ToInt64 (decimal value); public abstract long ToInt64 (double value); public abstract long ToInt64 (int value); public abstract long ToInt64 (long value); public abstract long ToInt64 (object value); public abstract long ToInt64 (float value); public abstract long ToInt64 (string value); public abstract float ToSingle (bool value); public abstract float ToSingle (DateTime value); public abstract float ToSingle (decimal value); public abstract float ToSingle (double value); public abstract float ToSingle (int value); public abstract float ToSingle (long value); public abstract float ToSingle (object value); public abstract float ToSingle (float value); public abstract float ToSingle (string value); public abstract string ToString (bool value); public abstract string ToString (DateTime value); public abstract string ToString (decimal value); public abstract string ToString (double value); public abstract string ToString (int value); public abstract string ToString (long value); public abstract string ToString (object value); public abstract string ToString (object value, IXmlNamespaceResolver nsResolver); public abstract string ToString (float value); public abstract string ToString (string value); public abstract string ToString (string value, IXmlNamespaceResolver nsResolver); } internal class XsdNonPermissiveConverter : XmlValueConverter { readonly XmlTypeCode typeCode; public XsdNonPermissiveConverter (XmlTypeCode typeCode) { this.typeCode = typeCode; } public XmlTypeCode Code { get { return typeCode; } } public override object ChangeType (bool value, Type type) { return ChangeType ((object) value, type); } public override object ChangeType (DateTime value, Type type) { return ChangeType ((object) value, type); } public override object ChangeType (decimal value, Type type) { return ChangeType ((object) value, type); } public override object ChangeType (double value, Type type) { return ChangeType ((object) value, type); } public override object ChangeType (int value, Type type) { return ChangeType ((object) value, type); } public override object ChangeType (long value, Type type) { return ChangeType ((object) value, type); } public override object ChangeType (float value, Type type) { return ChangeType ((object) value, type); } public override object ChangeType (string value, Type type) { return ChangeType ((object) value, type); } public override object ChangeType (object value, Type type) { return ChangeType (value, type, null); } [MonoTODO] public override object ChangeType (object value, Type type, IXmlNamespaceResolver nsResolver) { if (value == null) throw new ArgumentNullException ("value"); if (type == null) throw new ArgumentNullException ("type"); switch (Type.GetTypeCode (value.GetType ())) { case TypeCode.Boolean: bool bvalue = (bool) value; switch (Type.GetTypeCode (type)) { case TypeCode.Boolean: return ToBoolean (bvalue); case TypeCode.DateTime: return ToDateTime (bvalue); case TypeCode.Decimal: return ToDecimal (bvalue); case TypeCode.Double: return ToDouble (bvalue); case TypeCode.Int32: return ToInt32 (bvalue); case TypeCode.Int64: return ToInt64 (bvalue); case TypeCode.Single: return ToSingle (bvalue); case TypeCode.String: return ToString (bvalue); } break; // case TypeCode.Byte: // case TypeCode.Char: case TypeCode.DateTime: DateTime dtvalue = (DateTime) value; switch (Type.GetTypeCode (type)) { case TypeCode.Boolean: return ToBoolean (dtvalue); case TypeCode.DateTime: return ToDateTime (dtvalue); case TypeCode.Decimal: return ToDecimal (dtvalue); case TypeCode.Double: return ToDouble (dtvalue); case TypeCode.Int32: return ToInt32 (dtvalue); case TypeCode.Int64: return ToInt64 (dtvalue); case TypeCode.Single: return ToSingle (dtvalue); case TypeCode.String: return ToString (dtvalue); } break; // case TypeCode.DBNull: case TypeCode.Decimal: decimal decvalue = (decimal) value; switch (Type.GetTypeCode (type)) { case TypeCode.Boolean: return ToBoolean (decvalue); case TypeCode.DateTime: return ToDateTime (decvalue); case TypeCode.Decimal: return ToDecimal (decvalue); case TypeCode.Double: return ToDouble (decvalue); case TypeCode.Int32: return ToInt32 (decvalue); case TypeCode.Int64: return ToInt64 (decvalue); case TypeCode.Single: return ToSingle (decvalue); case TypeCode.String: return ToString (decvalue); } break; case TypeCode.Double: double dblvalue = (double) value; switch (Type.GetTypeCode (type)) { case TypeCode.Boolean: return ToBoolean (dblvalue); case TypeCode.DateTime: return ToDateTime (dblvalue); case TypeCode.Decimal: return ToDecimal (dblvalue); case TypeCode.Double: return ToDouble (dblvalue); case TypeCode.Int32: return ToInt32 (dblvalue); case TypeCode.Int64: return ToInt64 (dblvalue); case TypeCode.Single: return ToSingle (dblvalue); case TypeCode.String: return ToString (dblvalue); } break; // case TypeCode.Empty: // case TypeCode.Int16: case TypeCode.Int32: int ivalue = (int) value; switch (Type.GetTypeCode (type)) { case TypeCode.Boolean: return ToBoolean (ivalue); case TypeCode.DateTime: return ToDateTime (ivalue); case TypeCode.Decimal: return ToDecimal (ivalue); case TypeCode.Double: return ToDouble (ivalue); case TypeCode.Int32: return ToInt32 (ivalue); case TypeCode.Int64: return ToInt64 (ivalue); case TypeCode.Single: return ToSingle (ivalue); case TypeCode.String: return ToString (ivalue); } break; case TypeCode.Int64: long lvalue = (long) value; switch (Type.GetTypeCode (type)) { case TypeCode.Boolean: return ToBoolean (lvalue); case TypeCode.DateTime: return ToDateTime (lvalue); case TypeCode.Decimal: return ToDecimal (lvalue); case TypeCode.Double: return ToDouble (lvalue); case TypeCode.Int32: return ToInt32 (lvalue); case TypeCode.Int64: return ToInt64 (lvalue); case TypeCode.Single: return ToSingle (lvalue); case TypeCode.String: return ToString (lvalue); } break; // case TypeCode.Object: // case TypeCode.SByte: case TypeCode.Single: float fvalue = (float) value; switch (Type.GetTypeCode (type)) { case TypeCode.Boolean: return ToBoolean (fvalue); case TypeCode.DateTime: return ToDateTime (fvalue); case TypeCode.Decimal: return ToDecimal (fvalue); case TypeCode.Double: return ToDouble (fvalue); case TypeCode.Int32: return ToInt32 (fvalue); case TypeCode.Int64: return ToInt64 (fvalue); case TypeCode.Single: return ToSingle (fvalue); case TypeCode.String: return ToString (fvalue); } break; case TypeCode.String: string svalue = (string) value; switch (Type.GetTypeCode (type)) { case TypeCode.Boolean: return ToBoolean (svalue); case TypeCode.DateTime: return ToDateTime (svalue); case TypeCode.Decimal: return ToDecimal (svalue); case TypeCode.Double: return ToDouble (svalue); case TypeCode.Int32: return ToInt32 (svalue); case TypeCode.Int64: return ToInt64 (svalue); case TypeCode.Single: return ToSingle (svalue); case TypeCode.String: return ToString (svalue); } break; // case TypeCode.UInt16: // case TypeCode.UInt32: // case TypeCode.UInt64: default: if (type == typeof (TimeSpan)) // xs:duration, xdt:yearMonthDuration, // xdt:dayTimeDuration. FIXME: yMD to // dTD and dTD to yMD are not allowed. return ToTimeSpan (value); if (value.GetType () == typeof (byte [])) { // xs:base64 by default if (type == typeof (string)) return XQueryConvert.Base64BinaryToString ((byte []) value); else if (type == typeof (byte [])) return value; } if (value.GetType () == type) { if (type == typeof (XmlQualifiedName)) { // xs:QName and xs:NOTATION throw new NotImplementedException (); } } break; } throw Error (value.GetType (), type); } public override object ChangeType (string value, Type type, IXmlNamespaceResolver nsResolver) { return ChangeType ((object) value, type, nsResolver); } public TimeSpan ToTimeSpan (bool value) { throw Error (typeof (bool), typeof (TimeSpan)); } public TimeSpan ToTimeSpan (DateTime value) { throw Error (typeof (bool), typeof (TimeSpan)); } public TimeSpan ToTimeSpan (decimal value) { throw Error (typeof (bool), typeof (TimeSpan)); } public TimeSpan ToTimeSpan (double value) { throw Error (typeof (bool), typeof (TimeSpan)); } public TimeSpan ToTimeSpan (int value) { throw Error (typeof (bool), typeof (TimeSpan)); } public TimeSpan ToTimeSpan (long value) { throw Error (typeof (bool), typeof (TimeSpan)); } public virtual TimeSpan ToTimeSpan (object value) { // Allow on overriden converter for xs:duration, // xdt:dayTimeDuration and xdt:yearMonthDuration. throw Error (typeof (bool), typeof (TimeSpan)); } public TimeSpan ToTimeSpan (float value) { throw Error (typeof (bool), typeof (TimeSpan)); } public TimeSpan ToTimeSpan (string value) { throw Error (typeof (bool), typeof (TimeSpan)); } protected InvalidCastException Error (Type valueType, Type destType) { return new InvalidCastException (String.Format ("The conversion from {0} value to {1} type via {2} type is not allowed.", valueType, destType, typeCode)); } public override bool ToBoolean (bool value) { throw Error (typeof (bool), typeof (bool)); } public override bool ToBoolean (DateTime value) { throw Error (typeof (DateTime), typeof (bool)); } public override bool ToBoolean (decimal value) { throw Error (typeof (decimal), typeof (bool)); } public override bool ToBoolean (double value) { throw Error (typeof (double), typeof (bool)); } public override bool ToBoolean (int value) { throw Error (typeof (int), typeof (bool)); } public override bool ToBoolean (long value) { throw Error (typeof (long), typeof (bool)); } public override bool ToBoolean (object value) { if (value == null) throw new ArgumentNullException ("value"); throw Error (value.GetType (), typeof (bool)); } public override bool ToBoolean (float value) { throw Error (typeof (float), typeof (bool)); } public override bool ToBoolean (string value) { throw Error (typeof (string), typeof (bool)); } public override DateTime ToDateTime (bool value) { throw Error (typeof (bool), typeof (DateTime)); } public override DateTime ToDateTime (DateTime value) { throw Error (typeof (DateTime), typeof (DateTime)); } public override DateTime ToDateTime (decimal value) { throw Error (typeof (decimal), typeof (DateTime)); } public override DateTime ToDateTime (double value) { throw Error (typeof (double), typeof (DateTime)); } public override DateTime ToDateTime (int value) { throw Error (typeof (int), typeof (DateTime)); } public override DateTime ToDateTime (long value) { throw Error (typeof (long), typeof (DateTime)); } public override DateTime ToDateTime (object value) { if (value == null) throw new ArgumentNullException ("value"); throw Error (value.GetType (), typeof (DateTime)); } public override DateTime ToDateTime (float value) { throw Error (typeof (float), typeof (DateTime)); } public override DateTime ToDateTime (string value) { throw Error (typeof (string), typeof (DateTime)); } public override decimal ToDecimal (bool value) { throw Error (typeof (bool), typeof (decimal)); } public override decimal ToDecimal (DateTime value) { throw Error (typeof (DateTime), typeof (decimal)); } public override decimal ToDecimal (decimal value) { throw Error (typeof (decimal), typeof (decimal)); } public override decimal ToDecimal (double value) { throw Error (typeof (double), typeof (decimal)); } public override decimal ToDecimal (int value) { throw Error (typeof (int), typeof (decimal)); } public override decimal ToDecimal (long value) { throw Error (typeof (long), typeof (decimal)); } public override decimal ToDecimal (object value) { if (value == null) throw new ArgumentNullException ("value"); throw Error (value.GetType (), typeof (decimal)); } public override decimal ToDecimal (float value) { throw Error (typeof (float), typeof (decimal)); } public override decimal ToDecimal (string value) { throw Error (typeof (string), typeof (decimal)); } public override double ToDouble (bool value) { throw Error (typeof (bool), typeof (double)); } public override double ToDouble (DateTime value) { throw Error (typeof (DateTime), typeof (double)); } public override double ToDouble (decimal value) { throw Error (typeof (decimal), typeof (double)); } public override double ToDouble (double value) { throw Error (typeof (double), typeof (double)); } public override double ToDouble (int value) { throw Error (typeof (int), typeof (double)); } public override double ToDouble (long value) { throw Error (typeof (long), typeof (double)); } public override double ToDouble (object value) { if (value == null) throw new ArgumentNullException ("value"); throw Error (value.GetType (), typeof (double)); } public override double ToDouble (float value) { throw Error (typeof (float), typeof (double)); } public override double ToDouble (string value) { throw Error (typeof (string), typeof (double)); } public override float ToSingle (bool value) { throw Error (typeof (bool), typeof (float)); } public override float ToSingle (DateTime value) { throw Error (typeof (DateTime), typeof (float)); } public override float ToSingle (decimal value) { throw Error (typeof (decimal), typeof (float)); } public override float ToSingle (double value) { throw Error (typeof (double), typeof (float)); } public override float ToSingle (int value) { throw Error (typeof (int), typeof (float)); } public override float ToSingle (long value) { throw Error (typeof (long), typeof (float)); } public override float ToSingle (object value) { if (value == null) throw new ArgumentNullException ("value"); throw Error (value.GetType (), typeof (float)); } public override float ToSingle (float value) { throw Error (typeof (float), typeof (float)); } public override float ToSingle (string value) { throw Error (typeof (string), typeof (float)); } public override int ToInt32 (bool value) { throw Error (typeof (bool), typeof (int)); } public override int ToInt32 (DateTime value) { throw Error (typeof (DateTime), typeof (int)); } public override int ToInt32 (decimal value) { throw Error (typeof (decimal), typeof (int)); } public override int ToInt32 (double value) { throw Error (typeof (double), typeof (int)); } public override int ToInt32 (int value) { throw Error (typeof (int), typeof (int)); } public override int ToInt32 (long value) { throw Error (typeof (long), typeof (int)); } public override int ToInt32 (object value) { if (value == null) throw new ArgumentNullException ("value"); throw Error (value.GetType (), typeof (int)); } public override int ToInt32 (float value) { throw Error (typeof (float), typeof (int)); } public override int ToInt32 (string value) { throw Error (typeof (string), typeof (int)); } public override long ToInt64 (bool value) { throw Error (typeof (bool), typeof (long)); } public override long ToInt64 (DateTime value) { throw Error (typeof (DateTime), typeof (long)); } public override long ToInt64 (decimal value) { throw Error (typeof (decimal), typeof (long)); } public override long ToInt64 (double value) { throw Error (typeof (double), typeof (long)); } public override long ToInt64 (int value) { throw Error (typeof (int), typeof (long)); } public override long ToInt64 (long value) { throw Error (typeof (long), typeof (long)); } public override long ToInt64 (object value) { if (value == null) throw new ArgumentNullException ("value"); throw Error (value.GetType (), typeof (long)); } public override long ToInt64 (float value) { throw Error (typeof (float), typeof (long)); } public override long ToInt64 (string value) { throw Error (typeof (string), typeof (long)); } public override string ToString (bool value) { throw Error (typeof (bool), typeof (string)); } public override string ToString (DateTime value) { throw Error (typeof (DateTime), typeof (string)); } public override string ToString (decimal value) { throw Error (typeof (decimal), typeof (string)); } public override string ToString (double value) { throw Error (typeof (double), typeof (string)); } public override string ToString (int value) { throw Error (typeof (int), typeof (string)); } public override string ToString (long value) { throw Error (typeof (long), typeof (string)); } public override string ToString (object value) { return ToString (value, null); } public override string ToString (object value, IXmlNamespaceResolver nsResolver) { if (value == null) throw new ArgumentNullException ("value"); throw Error (value.GetType (), typeof (string)); } public override string ToString (float value) { throw Error (typeof (float), typeof (string)); } public override string ToString (string value) { return ToString (value, null); } public override string ToString (string value, IXmlNamespaceResolver nsResolver) { throw Error (typeof (string), typeof (string)); } } internal class XsdLaxConverter : XsdNonPermissiveConverter { public XsdLaxConverter (XmlTypeCode code) : base (code) { } public override string ToString (bool value) { return XmlConvert.ToString (value); } public override string ToString (decimal value) { return XmlConvert.ToString (value); } public override string ToString (double value) { return XmlConvert.ToString (value); } public override string ToString (int value) { return XmlConvert.ToString (value); } public override string ToString (long value) { return XmlConvert.ToString (value); } public override string ToString (object value) { return ChangeType (value, typeof (string)) as string; } public override string ToString (float value) { return XmlConvert.ToString (value); } public override bool ToBoolean (bool value) { return value; } public override decimal ToDecimal (decimal value) { return value; } public override decimal ToDecimal (double value) { return (decimal) value; } public override decimal ToDecimal (int value) { return (decimal) value; } public override decimal ToDecimal (long value) { return (decimal) value; } [MonoTODO] public override decimal ToDecimal (object value) { return (decimal) ChangeType (value, typeof (decimal)); } public override decimal ToDecimal (float value) { return (decimal) value; } public override double ToDouble (decimal value) { return (double) value; } public override double ToDouble (double value) { return (double) value; } public override double ToDouble (int value) { return (double) value; } public override double ToDouble (long value) { return (double) value; } [MonoTODO] public override double ToDouble (object value) { return (double) ChangeType (value, typeof (double)); } public override double ToDouble (float value) { return (double) value; } public override float ToSingle (decimal value) { return (float) value; } public override float ToSingle (double value) { return (float) value; } public override float ToSingle (int value) { return (float) value; } public override float ToSingle (long value) { return (float) value; } [MonoTODO] public override float ToSingle (object value) { return (float) ChangeType (value, typeof (float)); } public override float ToSingle (float value) { return (float) value; } public override int ToInt32 (int value) { return value; } public override int ToInt32 (long value) { return XQueryConvert.IntegerToInt (value); } [MonoTODO] public override int ToInt32 (object value) { return (int) ChangeType (value, typeof (int)); } public override long ToInt64 (int value) { return value; } public override long ToInt64 (long value) { return value; } [MonoTODO] public override long ToInt64 (object value) { return (long) ChangeType (value, typeof (long)); } } internal class XsdAnyTypeConverter : XsdNumericConverter { public XsdAnyTypeConverter (XmlTypeCode code) : base (code) { } #region boolean public override bool ToBoolean (decimal value) { return value != 0; } public override bool ToBoolean (double value) { return value != 0; } public override bool ToBoolean (int value) { return value != 0; } public override bool ToBoolean (long value) { return value != 0; } [MonoTODO] public override bool ToBoolean (object value) { return (bool) ChangeType (value, typeof (bool)); } public override bool ToBoolean (float value) { return value != 0; } public override decimal ToDecimal (bool value) { return value ? 1 : 0; } public override double ToDouble (bool value) { return value ? 1 : 0; } public override float ToSingle (bool value) { return value ? 1 : 0; } public override int ToInt32 (bool value) { return value ? 1 : 0; } public override long ToInt64 (bool value) { return value ? 1 : 0; } #endregion #region string public override DateTime ToDateTime (DateTime value) { return value; } public override string ToString (DateTime value) { return XmlConvert.ToString (value); } public override string ToString (string value) { return value; } #endregion } internal class XsdStringConverter : XsdLaxConverter { public XsdStringConverter (XmlTypeCode code) : base (code) { } public override DateTime ToDateTime (DateTime value) { return value; } public override string ToString (DateTime value) { return XmlConvert.ToString (value); } public override string ToString (string value) { return value; } } internal class XsdNumericConverter : XsdLaxConverter { public XsdNumericConverter (XmlTypeCode code) : base (code) { } #region boolean public override bool ToBoolean (decimal value) { return value != 0; } public override bool ToBoolean (double value) { return value != 0; } public override bool ToBoolean (int value) { return value != 0; } public override bool ToBoolean (long value) { return value != 0; } [MonoTODO] public override bool ToBoolean (object value) { return (bool) ChangeType (value, typeof (bool)); } public override bool ToBoolean (float value) { return value != 0; } public override decimal ToDecimal (bool value) { return value ? 1 : 0; } public override double ToDouble (bool value) { return value ? 1 : 0; } public override float ToSingle (bool value) { return value ? 1 : 0; } public override int ToInt32 (bool value) { return value ? 1 : 0; } public override long ToInt64 (bool value) { return value ? 1 : 0; } #endregion #region numeric with point to without point public override int ToInt32 (decimal value) { return XQueryConvert.DecimalToInt (value); } public override int ToInt32 (double value) { return XQueryConvert.DoubleToInt (value); } public override int ToInt32 (float value) { return XQueryConvert.FloatToInt (value); } public override long ToInt64 (decimal value) { return XQueryConvert.DecimalToInteger (value); } public override long ToInt64 (double value) { return XQueryConvert.DoubleToInteger (value); } public override long ToInt64 (float value) { return XQueryConvert.FloatToInteger (value); } #endregion } internal class XsdDateTimeConverter : XsdNonPermissiveConverter { public XsdDateTimeConverter (XmlTypeCode code) : base (code) { } public override string ToString (DateTime value) { return XmlConvert.ToString (value); } public override DateTime ToDateTime (DateTime value) { return value; } } internal class XsdBooleanConverter : XsdNumericConverter { public XsdBooleanConverter (XmlTypeCode code) : base (code) { } } internal class XsdMiscBaseConverter : XsdNonPermissiveConverter { public XsdMiscBaseConverter (XmlTypeCode code) : base (code) { } public override string ToString (string value) { return value; } public override object ChangeType (object value, Type type, IXmlNamespaceResolver nsResolver) { if (Code == XmlTypeCode.HexBinary) { if (value == null) throw new ArgumentNullException ("value"); if (type == null) throw new ArgumentNullException ("type"); if (value.GetType () == typeof (byte [])) { if (type == typeof (string)) return XQueryConvert.HexBinaryToString ((byte []) value); else if (type == typeof (byte [])) return value; } } return base.ChangeType (value, type, nsResolver); } } } #endif
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Xml; using System.Xml.Schema; using System.IO; using System.Reflection; using System.Diagnostics; using System.Runtime.Serialization; using System.Security.Permissions; using System.Globalization; //using System.Workflow.Activities; using System.Workflow.ComponentModel; using System.Workflow.Runtime; using System.Workflow.Runtime.Hosting; using Hosting = System.Workflow.Runtime.Hosting; namespace System.Workflow.Runtime.Tracking { internal sealed class PropertyHelper { private PropertyHelper() { } #region Internal Static Methods internal static void GetProperty(string name, Activity activity, TrackingAnnotationCollection annotations, out TrackingDataItem item) { item = null; object tmp = PropertyHelper.GetProperty(name, activity); item = new TrackingDataItem(); item.FieldName = name; item.Data = tmp; foreach (string s in annotations) item.Annotations.Add(s); } internal static object GetProperty(string name, object obj) { if (null == name) throw new ArgumentNullException("name"); if (null == obj) throw new ArgumentNullException("obj"); // // Split the names string[] names = name.Split(new char[] { '.' }); object currObj = obj; for (int i = 0; i < names.Length; i++) { if ((null == names[i]) || (0 == names[i].Length)) throw new InvalidOperationException(ExecutionStringManager.TrackingProfileInvalidMember); object tmp = null; PropertyHelper.GetPropertyOrField(names[i], currObj, out tmp); // // Attempt to resolve runtime values (ParameterBinding, ParameterDeclaration and Bind) if (currObj is Activity) currObj = GetRuntimeValue(tmp, (Activity)currObj); else currObj = tmp; } return currObj; } internal static void GetPropertyOrField(string name, object o, out object obj) { obj = null; if (null == name) throw new ArgumentNullException("name"); if (null == o) throw new ArgumentNullException("o"); Type t = o.GetType(); string tmp = null, realName = null; bool isCollection = false; int index = -1; if (TryParseIndex(name, out tmp, out index)) isCollection = true; else tmp = name; object val = null; if ((null != tmp) && (tmp.Length > 0)) { if (!NameIsDefined(tmp, o, out realName)) throw new MissingMemberException(o.GetType().Name, tmp); // // Attempt to match default, no parameter (if overloaded) // Indexer accesses will fail - we do not handle indexers // Do case sensitive here because we have the real name of the matching member val = t.InvokeMember(realName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.GetField | BindingFlags.Instance | BindingFlags.Static, null, o, null, System.Globalization.CultureInfo.InvariantCulture); } else val = o; // root object is a collection - all that is passed for name is "[1]" if (isCollection) { IEnumerable collection = val as IEnumerable; if (null != collection) GetEnumerationMember(collection, index, out obj); } else obj = val; } internal static void GetEnumerationMember(IEnumerable collection, int index, out object obj) { obj = null; if (null == collection) throw new ArgumentNullException("collection"); IEnumerator e = collection.GetEnumerator(); int i = 0; while (e.MoveNext()) { if (i++ == index) { obj = e.Current; return; } } throw new IndexOutOfRangeException(); } internal static object GetRuntimeValue(object o, Activity activity) { if (null == o) return o; object tmp = o; if (o is ActivityBind) { if (null == activity) throw new ArgumentNullException("activity"); tmp = ((ActivityBind)o).GetRuntimeValue(activity); } else if (o is WorkflowParameterBinding) { tmp = ((WorkflowParameterBinding)o).Value; } return tmp; } internal static void GetAllMembers(Activity activity, IList<TrackingDataItem> items, TrackingAnnotationCollection annotations) { Type t = activity.GetType(); // // Get all fields FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.GetField); foreach (FieldInfo f in fields) { if (!PropertyHelper.IsInternalVariable(f.Name)) { TrackingDataItem data = new TrackingDataItem(); data.FieldName = f.Name; data.Data = GetRuntimeValue(f.GetValue(activity), activity); foreach (string s in annotations) data.Annotations.Add(s); items.Add(data); } } // // Get all properties (except indexers) PropertyInfo[] properties = t.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.GetProperty); foreach (PropertyInfo p in properties) { if (!IsInternalVariable(p.Name)) { // // Skip indexers, since private data members // are exposed the data is still available. if (p.GetIndexParameters().Length > 0) continue; TrackingDataItem data = new TrackingDataItem(); data.FieldName = p.Name; data.Data = GetRuntimeValue(p.GetValue(activity, null), activity); foreach (string s in annotations) data.Annotations.Add(s); items.Add(data); } } } #endregion #region Private Methods private static bool IsInternalVariable(string name) { string[] vars = { "__winoe_ActivityLocks_", "__winoe_StaticActivityLocks_", "__winoe_MethodLocks_" }; foreach (string s in vars) { if (0 == string.Compare(s, name, StringComparison.Ordinal)) return true; } return false; } private static bool NameIsDefined(string name, object o, out string realName) { realName = null; Type t = o.GetType(); // // Get the member with the requested name // Do case specific first MemberInfo[] members = t.GetMember(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.GetField | BindingFlags.Instance | BindingFlags.Static); // // Not found if ((null == members) || (0 == members.Length)) { // // Do case insensitive members = t.GetMember(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.GetField | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase); // // Not found if ((null == members) || (0 == members.Length)) { return false; } } if ((null == members) || (0 == members.Length) || (null == members[0].Name) || (0 == members[0].Name.Length)) return false; realName = members[0].Name; return true; } private static bool TryParseIndex(string fullName, out string name, out int index) { name = null; index = -1; int endPos = -1, startPos = -1; for (int i = fullName.Length - 1; i > 0; i--) { if ((']' == fullName[i]) && (-1 == endPos)) { endPos = i; } else if (('[' == fullName[i]) && (-1 == startPos)) { startPos = i; break; } } if ((-1 == endPos) || (-1 == startPos)) return false; string idx = fullName.Substring(startPos + 1, endPos - 1 - startPos); name = fullName.Substring(0, startPos); return int.TryParse(idx, out index); } #endregion } }
namespace System.Runtime.CompilerServices { internal class __BlockReflectionAttribute : Attribute { } } namespace Microsoft.Xml.Serialization.GeneratedAssembly { [System.Runtime.CompilerServices.__BlockReflection] public class XmlSerializationWriter1 : System.Xml.Serialization.XmlSerializationWriter { public void Write3_ArrayOfPersistModel(object o, string parentRuntimeNs = null, string parentCompileTimeNs = null) { string defaultNamespace = parentRuntimeNs ?? @""; WriteStartDocument(); if (o == null) { WriteNullTagLiteral(@"ArrayOfPersistModel", defaultNamespace); return; } TopLevelElement(); string namespace1 = ( parentCompileTimeNs == @"" && parentRuntimeNs != null ) ? parentRuntimeNs : @""; { global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel> a = (global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel>)((global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel>)o); if ((object)(a) == null) { WriteNullTagLiteral(@"ArrayOfPersistModel", defaultNamespace); } else { WriteStartElement(@"ArrayOfPersistModel", namespace1, null, false); for (int ia = 0; ia < ((System.Collections.ICollection)a).Count; ia++) { string namespace2 = ( parentCompileTimeNs == @"" && parentRuntimeNs != null ) ? parentRuntimeNs : @""; Write2_PersistModel(@"PersistModel", namespace2, ((global::NavigationMenuSample.Models.PersistModel)a[ia]), true, false, namespace2, @""); } WriteEndElement(); } } } public void Write4_anyType(object o, string parentRuntimeNs = null, string parentCompileTimeNs = null) { string defaultNamespace = parentRuntimeNs ?? @""; WriteStartDocument(); if (o == null) { WriteNullTagLiteral(@"anyType", defaultNamespace); return; } TopLevelElement(); string namespace3 = ( parentCompileTimeNs == @"" && parentRuntimeNs != null ) ? parentRuntimeNs : @""; Write1_Object(@"anyType", namespace3, ((global::System.Object)o), true, false, namespace3, @""); } public void Write5_anyType(object o, string parentRuntimeNs = null, string parentCompileTimeNs = null) { string defaultNamespace = parentRuntimeNs ?? @""; WriteStartDocument(); if (o == null) { WriteNullTagLiteral(@"anyType", defaultNamespace); return; } TopLevelElement(); string namespace4 = ( parentCompileTimeNs == @"" && parentRuntimeNs != null ) ? parentRuntimeNs : @""; Write1_Object(@"anyType", namespace4, ((global::System.Object)o), true, false, namespace4, @""); } void Write1_Object(string n, string ns, global::System.Object o, bool isNullable, bool needType, string parentRuntimeNs = null, string parentCompileTimeNs = null) { string defaultNamespace = parentRuntimeNs; if ((object)o == null) { if (isNullable) WriteNullTagLiteral(n, ns); return; } if (!needType) { System.Type t = o.GetType(); if (t == typeof(global::System.Object)) { } else if (t == typeof(global::NavigationMenuSample.Models.PersistModel)) { Write2_PersistModel(n, ns,(global::NavigationMenuSample.Models.PersistModel)o, isNullable, true); return; } else if (t == typeof(global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel>)) { Writer.WriteStartElement(n, ns); WriteXsiType(@"ArrayOfPersistModel", @""); { global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel> a = (global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel>)o; if (a != null) { for (int ia = 0; ia < ((System.Collections.ICollection)a).Count; ia++) { string namespace5 = ( parentCompileTimeNs == @"" && parentRuntimeNs != null ) ? parentRuntimeNs : @""; Write2_PersistModel(@"PersistModel", namespace5, ((global::NavigationMenuSample.Models.PersistModel)a[ia]), true, false, namespace5, @""); } } } Writer.WriteEndElement(); return; } else { WriteTypedPrimitive(n, ns, o, true); return; } } WriteStartElement(n, ns, o, false, null); WriteEndElement(o); } void Write2_PersistModel(string n, string ns, global::NavigationMenuSample.Models.PersistModel o, bool isNullable, bool needType, string parentRuntimeNs = null, string parentCompileTimeNs = null) { string defaultNamespace = parentRuntimeNs; if ((object)o == null) { if (isNullable) WriteNullTagLiteral(n, ns); return; } if (!needType) { System.Type t = o.GetType(); if (t == typeof(global::NavigationMenuSample.Models.PersistModel)) { } else { throw CreateUnknownTypeException(o); } } WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"PersistModel", defaultNamespace); string namespace6 = ( parentCompileTimeNs == @"" && parentRuntimeNs != null ) ? parentRuntimeNs : @""; WriteElementString(@"UserID", namespace6, ((global::System.String)o.@UserID)); string namespace7 = ( parentCompileTimeNs == @"" && parentRuntimeNs != null ) ? parentRuntimeNs : @""; WriteElementString(@"ScreenName", namespace7, ((global::System.String)o.@ScreenName)); string namespace8 = ( parentCompileTimeNs == @"" && parentRuntimeNs != null ) ? parentRuntimeNs : @""; WriteElementString(@"AccessToken", namespace8, ((global::System.String)o.@AccessToken)); string namespace9 = ( parentCompileTimeNs == @"" && parentRuntimeNs != null ) ? parentRuntimeNs : @""; WriteElementString(@"AccessSecretToken", namespace9, ((global::System.String)o.@AccessSecretToken)); WriteEndElement(o); } protected override void InitCallbacks() { } } [System.Runtime.CompilerServices.__BlockReflection] public class XmlSerializationReader1 : System.Xml.Serialization.XmlSerializationReader { public object Read3_ArrayOfPersistModel(string defaultNamespace = null) { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object) Reader.LocalName == (object)id1_ArrayOfPersistModel && string.Equals(Reader.NamespaceURI, defaultNamespace ?? id2_Item))) { if (!ReadNull()) { if ((object)(o) == null) o = new global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel>(); global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel> a_0_0 = (global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel>)o; if ((Reader.IsEmptyElement)) { Reader.Skip(); } else { Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations0 = 0; int readerCount0 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object) Reader.LocalName == (object)id3_PersistModel && string.Equals(Reader.NamespaceURI, defaultNamespace ?? id2_Item))) { if ((object)(a_0_0) == null) Reader.Skip(); else a_0_0.Add(Read2_PersistModel(true, true, defaultNamespace)); } else { UnknownNode(null, @":PersistModel"); } } else { UnknownNode(null, @":PersistModel"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations0, ref readerCount0); } ReadEndElement(); } } else { if ((object)(o) == null) o = new global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel>(); global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel> a_0_0 = (global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel>)o; } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null, defaultNamespace ?? @":ArrayOfPersistModel"); } return (object)o; } public object Read4_anyType(string defaultNamespace = null) { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object) Reader.LocalName == (object)id4_anyType && string.Equals(Reader.NamespaceURI, defaultNamespace ?? id2_Item))) { o = Read1_Object(true, true, defaultNamespace); } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null, defaultNamespace ?? @":anyType"); } return (object)o; } public object Read5_anyType(string defaultNamespace = null) { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object) Reader.LocalName == (object)id4_anyType && string.Equals(Reader.NamespaceURI, defaultNamespace ?? id2_Item))) { o = Read1_Object(true, true, defaultNamespace); } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null, defaultNamespace ?? @":anyType"); } return (object)o; } global::System.Object Read1_Object(bool isNullable, bool checkType, string defaultNamespace = null) { System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; bool isNull = false; if (isNullable) isNull = ReadNull(); if (checkType) { if (isNull) { if (xsiType != null) return (global::System.Object)ReadTypedNull(xsiType); else return null; } if (xsiType == null) { return ReadTypedPrimitive(new System.Xml.XmlQualifiedName("anyType", "http://www.w3.org/2001/XMLSchema")); } else if (((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id3_PersistModel && string.Equals( ((System.Xml.XmlQualifiedName)xsiType).Namespace, defaultNamespace ?? id2_Item))) return Read2_PersistModel(isNullable, false, defaultNamespace); else if (((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id1_ArrayOfPersistModel && string.Equals( ((System.Xml.XmlQualifiedName)xsiType).Namespace, defaultNamespace ?? id2_Item))) { global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel> a = null; if (!ReadNull()) { if ((object)(a) == null) a = new global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel>(); global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel> z_0_0 = (global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel>)a; if ((Reader.IsEmptyElement)) { Reader.Skip(); } else { Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations1 = 0; int readerCount1 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object) Reader.LocalName == (object)id3_PersistModel && string.Equals(Reader.NamespaceURI, defaultNamespace ?? id2_Item))) { if ((object)(z_0_0) == null) Reader.Skip(); else z_0_0.Add(Read2_PersistModel(true, true, defaultNamespace)); } else { UnknownNode(null, @":PersistModel"); } } else { UnknownNode(null, @":PersistModel"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations1, ref readerCount1); } ReadEndElement(); } } return a; } else return ReadTypedPrimitive((System.Xml.XmlQualifiedName)xsiType); } if (isNull) return null; global::System.Object o; o = new global::System.Object(); bool[] paramsRead = new bool[0]; while (Reader.MoveToNextAttribute()) { if (!IsXmlnsAttribute(Reader.Name)) { UnknownNode((object)o); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations2 = 0; int readerCount2 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { UnknownNode((object)o, @""); } else { UnknownNode((object)o, @""); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations2, ref readerCount2); } ReadEndElement(); return o; } global::NavigationMenuSample.Models.PersistModel Read2_PersistModel(bool isNullable, bool checkType, string defaultNamespace = null) { System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; bool isNull = false; if (isNullable) isNull = ReadNull(); if (checkType) { if (xsiType == null || ((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id3_PersistModel && string.Equals( ((System.Xml.XmlQualifiedName)xsiType).Namespace, defaultNamespace ?? id2_Item))) { } else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } if (isNull) return null; global::NavigationMenuSample.Models.PersistModel o; o = new global::NavigationMenuSample.Models.PersistModel(); bool[] paramsRead = new bool[4]; while (Reader.MoveToNextAttribute()) { if (!IsXmlnsAttribute(Reader.Name)) { UnknownNode((object)o); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations3 = 0; int readerCount3 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (!paramsRead[0] && ((object) Reader.LocalName == (object)id5_UserID && string.Equals(Reader.NamespaceURI, defaultNamespace ?? id2_Item))) { { o.@UserID = Reader.ReadElementContentAsString(); } paramsRead[0] = true; } else if (!paramsRead[1] && ((object) Reader.LocalName == (object)id6_ScreenName && string.Equals(Reader.NamespaceURI, defaultNamespace ?? id2_Item))) { { o.@ScreenName = Reader.ReadElementContentAsString(); } paramsRead[1] = true; } else if (!paramsRead[2] && ((object) Reader.LocalName == (object)id7_AccessToken && string.Equals(Reader.NamespaceURI, defaultNamespace ?? id2_Item))) { { o.@AccessToken = Reader.ReadElementContentAsString(); } paramsRead[2] = true; } else if (!paramsRead[3] && ((object) Reader.LocalName == (object)id8_AccessSecretToken && string.Equals(Reader.NamespaceURI, defaultNamespace ?? id2_Item))) { { o.@AccessSecretToken = Reader.ReadElementContentAsString(); } paramsRead[3] = true; } else { UnknownNode((object)o, @":UserID, :ScreenName, :AccessToken, :AccessSecretToken"); } } else { UnknownNode((object)o, @":UserID, :ScreenName, :AccessToken, :AccessSecretToken"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations3, ref readerCount3); } ReadEndElement(); return o; } protected override void InitCallbacks() { } string id2_Item; string id3_PersistModel; string id5_UserID; string id7_AccessToken; string id6_ScreenName; string id1_ArrayOfPersistModel; string id8_AccessSecretToken; string id4_anyType; protected override void InitIDs() { id2_Item = Reader.NameTable.Add(@""); id3_PersistModel = Reader.NameTable.Add(@"PersistModel"); id5_UserID = Reader.NameTable.Add(@"UserID"); id7_AccessToken = Reader.NameTable.Add(@"AccessToken"); id6_ScreenName = Reader.NameTable.Add(@"ScreenName"); id1_ArrayOfPersistModel = Reader.NameTable.Add(@"ArrayOfPersistModel"); id8_AccessSecretToken = Reader.NameTable.Add(@"AccessSecretToken"); id4_anyType = Reader.NameTable.Add(@"anyType"); } } [System.Runtime.CompilerServices.__BlockReflection] public abstract class XmlSerializer1 : System.Xml.Serialization.XmlSerializer { protected override System.Xml.Serialization.XmlSerializationReader CreateReader() { return new XmlSerializationReader1(); } protected override System.Xml.Serialization.XmlSerializationWriter CreateWriter() { return new XmlSerializationWriter1(); } } [System.Runtime.CompilerServices.__BlockReflection] public sealed class ListOfPersistModelSerializer : XmlSerializer1 { public override System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { return xmlReader.IsStartElement(@"ArrayOfPersistModel", this.DefaultNamespace ?? @""); } protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) { ((XmlSerializationWriter1)writer).Write3_ArrayOfPersistModel(objectToSerialize, this.DefaultNamespace, @""); } protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) { return ((XmlSerializationReader1)reader).Read3_ArrayOfPersistModel(this.DefaultNamespace); } } [System.Runtime.CompilerServices.__BlockReflection] public sealed class ObjectSerializer : XmlSerializer1 { public override System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { return xmlReader.IsStartElement(@"anyType", this.DefaultNamespace ?? @""); } protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) { ((XmlSerializationWriter1)writer).Write4_anyType(objectToSerialize, this.DefaultNamespace, @""); } protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) { return ((XmlSerializationReader1)reader).Read4_anyType(this.DefaultNamespace); } } [System.Runtime.CompilerServices.__BlockReflection] public class XmlSerializerContract : global::System.Xml.Serialization.XmlSerializerImplementation { public override global::System.Xml.Serialization.XmlSerializationReader Reader { get { return new XmlSerializationReader1(); } } public override global::System.Xml.Serialization.XmlSerializationWriter Writer { get { return new XmlSerializationWriter1(); } } System.Collections.IDictionary readMethods = null; public override System.Collections.IDictionary ReadMethods { get { if (readMethods == null) { System.Collections.IDictionary _tmp = new System.Collections.Generic.Dictionary<string, string>(); _tmp[@"System.Collections.Generic.List`1[[NavigationMenuSample.Models.PersistModel, KunappWinApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]::"] = @"Read3_ArrayOfPersistModel"; _tmp[@"System.Object::"] = @"Read4_anyType"; _tmp[@"System.Object::"] = @"Read5_anyType"; if (readMethods == null) readMethods = _tmp; } return readMethods; } } System.Collections.IDictionary writeMethods = null; public override System.Collections.IDictionary WriteMethods { get { if (writeMethods == null) { System.Collections.IDictionary _tmp = new System.Collections.Generic.Dictionary<string, string>(); _tmp[@"System.Collections.Generic.List`1[[NavigationMenuSample.Models.PersistModel, KunappWinApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]::"] = @"Write3_ArrayOfPersistModel"; _tmp[@"System.Object::"] = @"Write4_anyType"; _tmp[@"System.Object::"] = @"Write5_anyType"; if (writeMethods == null) writeMethods = _tmp; } return writeMethods; } } System.Collections.IDictionary typedSerializers = null; public override System.Collections.IDictionary TypedSerializers { get { if (typedSerializers == null) { System.Collections.IDictionary _tmp = new System.Collections.Generic.Dictionary<string, System.Xml.Serialization.XmlSerializer>(); _tmp.Add(@"System.Collections.Generic.List`1[[NavigationMenuSample.Models.PersistModel, KunappWinApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]::", new ListOfPersistModelSerializer()); _tmp.Add(@"System.Object::", new ObjectSerializer()); if (typedSerializers == null) typedSerializers = _tmp; } return typedSerializers; } } public override System.Boolean CanSerialize(System.Type type) { if (type == typeof(global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel>)) return true; if (type == typeof(global::System.Object)) return true; if (type == typeof(global::System.Reflection.TypeInfo)) return true; return false; } public override System.Xml.Serialization.XmlSerializer GetSerializer(System.Type type) { if (type == typeof(global::System.Collections.Generic.List<global::NavigationMenuSample.Models.PersistModel>)) return new ListOfPersistModelSerializer(); if (type == typeof(global::System.Object)) return new ObjectSerializer(); if (type == typeof(global::System.Object)) return new ObjectSerializer(); return null; } public static global::System.Xml.Serialization.XmlSerializerImplementation GetXmlSerializerContract() { return new XmlSerializerContract(); } } [System.Runtime.CompilerServices.__BlockReflection] public static class ActivatorHelper { public static object CreateInstance(System.Type type) { System.Reflection.TypeInfo ti = System.Reflection.IntrospectionExtensions.GetTypeInfo(type); foreach (System.Reflection.ConstructorInfo ci in ti.DeclaredConstructors) { if (!ci.IsStatic && ci.GetParameters().Length == 0) { return ci.Invoke(null); } } return System.Activator.CreateInstance(type); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace AoC2017 { enum Command { Unknown, Increment, Decrement } enum Comparison { Unknown, LessThan, LessThanOrEqualTo, EqualTo, NotEqualTo, GreaterThan, GreaterThanOrEqualTo } class Condition { public string Left; public Comparison Comparison; public long Right; private Condition() {} public Condition(string left, Comparison comparison, long right) { Left = left; Comparison = comparison; Right = right; } } class Statement { public string Register { private set; get; } public Command Command { private set; get; } public long Amount { private set; get; } public Condition Condition { private set; get; } public Comparison Comparison { private set; get; } private Statement() {} public Statement(string register, Command command, long amount, Condition condition, Comparison comparison) { Register = register; Command = command; Amount = amount; Condition = condition; Comparison = comparison; } } class Day08 { private static Dictionary<string, long> Registers { get; set; } private static List<Statement> Statements { get; set; } static void Main(string[] args) { var inputFile = @"../inputs/day08.txt"; var part1 = long.MinValue; var part2 = long.MinValue; Registers = new Dictionary<string, long>(); Statements = new List<Statement>(); var lines = File.ReadAllLines(inputFile); foreach (var line in lines) { Statements.Add(ParseStatement(line)); } foreach (var statement in Statements) { long regValue = GetRegister(statement.Condition.Left); long cmpValue = statement.Condition.Right; bool conditional = false; switch (statement.Condition.Comparison) { case Comparison.LessThan: conditional = regValue < cmpValue; break; case Comparison.LessThanOrEqualTo: conditional = regValue <= cmpValue; break; case Comparison.GreaterThan: conditional = regValue > cmpValue; break; case Comparison.GreaterThanOrEqualTo: conditional = regValue >= cmpValue; break; case Comparison.EqualTo: conditional = regValue == cmpValue; break; case Comparison.NotEqualTo: conditional = regValue != cmpValue; break; case Comparison.Unknown: default: Console.Error.WriteLine("error: unknown comparison operator"); conditional = false; break; } long currentValue = GetRegister(statement.Register); long incValue = 0; if (conditional) { switch (statement.Command) { case Command.Increment: incValue = statement.Amount; break; case Command.Decrement: incValue = -1 * statement.Amount; break; case Command.Unknown: default: Console.Error.WriteLine("error: unknown command"); break; } } long newValue = currentValue + incValue; SetRegister(statement.Register, newValue); if (newValue > part2) { part2 = newValue; } } Console.ForegroundColor = ConsoleColor.DarkGray; foreach (var key in Registers.Keys) { var value = GetRegister(key); if (value > part1) { part1 = value; Console.WriteLine($"New largest value = {part1} ({key})"); } } Console.BackgroundColor = ConsoleColor.DarkBlue; Console.ForegroundColor = ConsoleColor.White; foreach (var key in Registers.Keys) { Console.WriteLine($"{key} = {GetRegister(key)}"); } Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"Part 1: {part1}\nPart 2: {part2}"); } static Statement ParseStatement(string line) { var parts = line.Split(' '); var register = parts[0]; var amount = Int64.Parse(parts[2]); var left = parts[4]; var right = Int64.Parse(parts[6]); Command command; switch (parts[1]) { case "inc": command = Command.Increment; break; case "dec": command = Command.Decrement; break; default: Console.Error.WriteLine("error: unsupported command \"{}\"", parts[1]); command = Command.Unknown; break; } Comparison comparison; switch (parts[5]) { case "<": comparison = Comparison.LessThan; break; case "<=": comparison = Comparison.LessThanOrEqualTo; break; case ">": comparison = Comparison.GreaterThan; break; case ">=": comparison = Comparison.GreaterThanOrEqualTo; break; case "==": comparison = Comparison.EqualTo; break; case "!=": comparison = Comparison.NotEqualTo; break; default: Console.Error.WriteLine("error: unsupported command \"{}\"", parts[1]); comparison = Comparison.Unknown; break; } Condition condition = new Condition(left, comparison, right); Statement statement = new Statement(register, command, amount, condition, comparison); return statement; } static long GetRegister(string register) { if (!Registers.ContainsKey(register)) { Registers[register] = 0; } return Registers[register]; } static void SetRegister(string register, long value) { Registers[register] = value; } } }
/** * MetroFramework - Modern UI for WinForms * * The MIT License (MIT) * Copyright (c) 2011 Sven Walter, http://github.com/viperneo * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.ComponentModel; using System.Collections.Generic; using System.Reflection; using System.Security; using System.Windows.Forms; using MetroFramework.Components; using MetroFramework.Drawing; using MetroFramework.Interfaces; using MetroFramework.Native; namespace MetroFramework.Forms { #region Enums public enum MetroFormTextAlign { Left, Center, Right } public enum MetroFormShadowType { None, Flat, DropShadow, SystemShadow, AeroShadow } public enum MetroFormBorderStyle { None, FixedSingle } public enum BackLocation { TopLeft, TopRight, BottomLeft, BottomRight } #endregion public class MetroForm : Form, IMetroForm, IDisposable { #region Interface private MetroColorStyle metroStyle = MetroColorStyle.Blue; [Category(MetroDefaults.PropertyCategory.Appearance)] public MetroColorStyle Style { get { if (StyleManager != null) return StyleManager.Style; return metroStyle; } set { metroStyle = value; } } private MetroThemeStyle metroTheme = MetroThemeStyle.Light; [Category(MetroDefaults.PropertyCategory.Appearance)] public MetroThemeStyle Theme { get { if (StyleManager != null) return StyleManager.Theme; return metroTheme; } set { metroTheme = value; } } private MetroStyleManager metroStyleManager = null; [Browsable(false)] public MetroStyleManager StyleManager { get { return metroStyleManager; } set { metroStyleManager = value; } } #endregion #region Fields private MetroFormTextAlign textAlign = MetroFormTextAlign.Left; [Browsable(true)] [Category(MetroDefaults.PropertyCategory.Appearance)] public MetroFormTextAlign TextAlign { get { return textAlign; } set { textAlign = value; } } [Browsable(false)] public override Color BackColor { get { return MetroPaint.BackColor.Form(Theme); } } private MetroFormBorderStyle formBorderStyle = MetroFormBorderStyle.None; [DefaultValue(MetroFormBorderStyle.None)] [Browsable(true)] [Category(MetroDefaults.PropertyCategory.Appearance)] public MetroFormBorderStyle BorderStyle { get { return formBorderStyle; } set { formBorderStyle = value; } } private bool isMovable = true; [Category(MetroDefaults.PropertyCategory.Appearance)] public bool Movable { get { return isMovable; } set { isMovable = value; } } public new Padding Padding { get { return base.Padding; } set { value.Top = Math.Max(value.Top, DisplayHeader ? 60 : 30); base.Padding = value; } } protected override Padding DefaultPadding { get { return new Padding(20, DisplayHeader ? 60 : 20, 20, 20); } } private bool displayHeader = true; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(true)] public bool DisplayHeader { get { return displayHeader; } set { if (value != displayHeader) { Padding p = base.Padding; p.Top += value ? 30 : -30; base.Padding = p; } displayHeader = value; } } private bool isResizable = true; [Category(MetroDefaults.PropertyCategory.Appearance)] public bool Resizable { get { return isResizable; } set { isResizable = value; } } private MetroFormShadowType shadowType = MetroFormShadowType.Flat; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(MetroFormShadowType.Flat)] public MetroFormShadowType ShadowType { get { return IsMdiChild ? MetroFormShadowType.None : shadowType; } set { shadowType = value; } } [Browsable(false)] public new FormBorderStyle FormBorderStyle { get { return base.FormBorderStyle; } set { base.FormBorderStyle = value; } } public new Form MdiParent { get { return base.MdiParent; } set { if (value != null) { RemoveShadow(); shadowType = MetroFormShadowType.None; } base.MdiParent = value; } } private const int borderWidth = 5; private Bitmap _image = null; private Image backImage; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(null)] public Image BackImage { get { return backImage; } set { backImage = value; if(value != null) _image = ApplyInvert(new Bitmap(value)); Refresh(); } } private Padding backImagePadding; [Category(MetroDefaults.PropertyCategory.Appearance)] public Padding BackImagePadding { get { return backImagePadding; } set { backImagePadding = value; Refresh(); } } private int backMaxSize; [Category(MetroDefaults.PropertyCategory.Appearance)] public int BackMaxSize { get { return backMaxSize; } set { backMaxSize = value; Refresh(); } } private BackLocation backLocation; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(BackLocation.TopLeft)] public BackLocation BackLocation { get { return backLocation; } set { backLocation = value; Refresh(); } } private bool _imageinvert; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(true)] public bool ApplyImageInvert { get { return _imageinvert; } set { _imageinvert = value; Refresh(); } } #endregion #region Constructor public MetroForm() { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true); FormBorderStyle = FormBorderStyle.None; Name = "MetroForm"; StartPosition = FormStartPosition.CenterScreen; TransparencyKey = Color.Lavender; } protected override void Dispose(bool disposing) { if (disposing) { RemoveShadow(); } base.Dispose(disposing); } #endregion #region Paint Methods public Bitmap ApplyInvert(Bitmap bitmapImage) { byte A, R, G, B; Color pixelColor; for (int y = 0; y < bitmapImage.Height; y++) { for (int x = 0; x < bitmapImage.Width; x++) { pixelColor = bitmapImage.GetPixel(x, y); A = pixelColor.A; R = (byte)(255 - pixelColor.R); G = (byte)(255 - pixelColor.G); B = (byte)(255 - pixelColor.B); if (R <= 0) R= 17; if (G <= 0) G= 17; if (B <= 0) B= 17; //bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B)); bitmapImage.SetPixel(x, y, Color.FromArgb((int)R, (int)G, (int)B)); } } return bitmapImage; } protected override void OnPaint(PaintEventArgs e) { Color backColor = MetroPaint.BackColor.Form(Theme); Color foreColor = MetroPaint.ForeColor.Title(Theme); e.Graphics.Clear(backColor); using (SolidBrush b = MetroPaint.GetStyleBrush(Style)) { Rectangle topRect = new Rectangle(0, 0, Width, borderWidth); e.Graphics.FillRectangle(b, topRect); } if (BorderStyle != MetroFormBorderStyle.None) { Color c = MetroPaint.BorderColor.Form(Theme); using (Pen pen = new Pen(c)) { e.Graphics.DrawLines(pen, new[] { new Point(0, borderWidth), new Point(0, Height - 1), new Point(Width - 1, Height - 1), new Point(Width - 1, borderWidth) }); } } if (backImage != null && backMaxSize != 0) { Image img = MetroImage.ResizeImage(backImage, new Rectangle(0, 0, backMaxSize, backMaxSize)); if (_imageinvert) { img = MetroImage.ResizeImage((Theme == MetroThemeStyle.Dark) ? _image : backImage, new Rectangle(0, 0, backMaxSize, backMaxSize)); } switch (backLocation) { case BackLocation.TopLeft: e.Graphics.DrawImage(img, 0 + backImagePadding.Left, 0 + backImagePadding.Top); break; case BackLocation.TopRight: e.Graphics.DrawImage(img, ClientRectangle.Right - (backImagePadding.Right + img.Width), 0 + backImagePadding.Top); break; case BackLocation.BottomLeft: e.Graphics.DrawImage(img, 0 + backImagePadding.Left, ClientRectangle.Bottom - (img.Height + backImagePadding.Bottom)); break; case BackLocation.BottomRight: e.Graphics.DrawImage(img, ClientRectangle.Right - (backImagePadding.Right + img.Width), ClientRectangle.Bottom - (img.Height + backImagePadding.Bottom)); break; } } if (displayHeader) { Rectangle bounds = new Rectangle(20, 20, ClientRectangle.Width - 2 * 20, 40); TextFormatFlags flags = TextFormatFlags.EndEllipsis | GetTextFormatFlags(); TextRenderer.DrawText(e.Graphics, Text, MetroFonts.Title, bounds, foreColor, flags); } if (Resizable && (SizeGripStyle == SizeGripStyle.Auto || SizeGripStyle == SizeGripStyle.Show)) { using (SolidBrush b = new SolidBrush(MetroPaint.ForeColor.Button.Disabled(Theme))) { Size resizeHandleSize = new Size(2, 2); e.Graphics.FillRectangles(b, new Rectangle[] { new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-6), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-10,ClientRectangle.Height-10), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-10,ClientRectangle.Height-6), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-10), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-14,ClientRectangle.Height-6), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-14), resizeHandleSize) }); } } } private TextFormatFlags GetTextFormatFlags() { switch (TextAlign) { case MetroFormTextAlign.Left: return TextFormatFlags.Left; case MetroFormTextAlign.Center: return TextFormatFlags.HorizontalCenter; case MetroFormTextAlign.Right: return TextFormatFlags.Right; } throw new InvalidOperationException(); } #endregion #region Management Methods protected override void OnClosing(CancelEventArgs e) { if (!(this is MetroTaskWindow)) MetroTaskWindow.ForceClose(); base.OnClosing(e); } protected override void OnClosed(EventArgs e) { RemoveShadow(); base.OnClosed(e); } [SecuritySafeCritical] public bool FocusMe() { return WinApi.SetForegroundWindow(Handle); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (DesignMode) return; switch (StartPosition) { case FormStartPosition.CenterParent: CenterToParent(); break; case FormStartPosition.CenterScreen: if (IsMdiChild) { CenterToParent(); } else { CenterToScreen(); } break; } RemoveCloseButton(); if (ControlBox) { AddWindowButton(WindowButtons.Close); if (MaximizeBox) AddWindowButton(WindowButtons.Maximize); if (MinimizeBox) AddWindowButton(WindowButtons.Minimize); UpdateWindowButtonPosition(); } CreateShadow(); } protected override void OnActivated(EventArgs e) { base.OnActivated(e); if (shadowType == MetroFormShadowType.AeroShadow && IsAeroThemeEnabled() && IsDropShadowSupported()) { int val = 2; DwmApi.DwmSetWindowAttribute(Handle, 2, ref val, 4); var m = new DwmApi.MARGINS { cyBottomHeight = 1, cxLeftWidth = 0, cxRightWidth = 0, cyTopHeight = 0 }; DwmApi.DwmExtendFrameIntoClientArea(Handle, ref m); } } protected override void OnEnabledChanged(EventArgs e) { base.OnEnabledChanged(e); Invalidate(); } protected override void OnResizeEnd(EventArgs e) { base.OnResizeEnd(e); UpdateWindowButtonPosition(); } protected override void WndProc(ref Message m) { if (DesignMode) { base.WndProc(ref m); return; } switch (m.Msg) { case (int)WinApi.Messages.WM_SYSCOMMAND: int sc = m.WParam.ToInt32() & 0xFFF0; switch (sc) { case (int)WinApi.Messages.SC_MOVE: if (!Movable) return; break; case (int)WinApi.Messages.SC_MAXIMIZE: break; case (int)WinApi.Messages.SC_RESTORE: break; } break; case (int)WinApi.Messages.WM_NCLBUTTONDBLCLK: case (int)WinApi.Messages.WM_LBUTTONDBLCLK: if (!MaximizeBox) return; break; case (int)WinApi.Messages.WM_NCHITTEST: WinApi.HitTest ht = HitTestNCA(m.HWnd, m.WParam, m.LParam); if (ht != WinApi.HitTest.HTCLIENT) { m.Result = (IntPtr)ht; return; } break; case (int)WinApi.Messages.WM_DWMCOMPOSITIONCHANGED: break; } base.WndProc(ref m); switch (m.Msg) { case (int)WinApi.Messages.WM_GETMINMAXINFO: OnGetMinMaxInfo(m.HWnd, m.LParam); break; case (int)WinApi.Messages.WM_SIZE: MetroFormButton btn; windowButtonList.TryGetValue(WindowButtons.Maximize, out btn); if (WindowState == FormWindowState.Normal) shadowForm.Visible = true;btn.Text = "1"; if(WindowState== FormWindowState.Maximized) btn.Text = "2"; break; } } [SecuritySafeCritical] private unsafe void OnGetMinMaxInfo(IntPtr hwnd, IntPtr lParam) { WinApi.MINMAXINFO* pmmi = (WinApi.MINMAXINFO*)lParam; Screen s = Screen.FromHandle(hwnd); pmmi->ptMaxSize.x = s.WorkingArea.Width; pmmi->ptMaxSize.y = s.WorkingArea.Height; pmmi->ptMaxPosition.x = Math.Abs(s.WorkingArea.Left - s.Bounds.Left); pmmi->ptMaxPosition.y = Math.Abs(s.WorkingArea.Top - s.Bounds.Top); //if (MinimumSize.Width > 0) pmmi->ptMinTrackSize.x = MinimumSize.Width; //if (MinimumSize.Height > 0) pmmi->ptMinTrackSize.y = MinimumSize.Height; //if (MaximumSize.Width > 0) pmmi->ptMaxTrackSize.x = MaximumSize.Width; //if (MaximumSize.Height > 0) pmmi->ptMaxTrackSize.y = MaximumSize.Height; } private WinApi.HitTest HitTestNCA(IntPtr hwnd, IntPtr wparam, IntPtr lparam) { //Point vPoint = PointToClient(new Point((int)lparam & 0xFFFF, (int)lparam >> 16 & 0xFFFF)); //Point vPoint = PointToClient(new Point((Int16)lparam, (Int16)((int)lparam >> 16))); Point vPoint = new Point((Int16)lparam, (Int16)((int)lparam >> 16)); int vPadding = Math.Max(Padding.Right, Padding.Bottom); if (Resizable) { if (RectangleToScreen(new Rectangle(ClientRectangle.Width - vPadding, ClientRectangle.Height - vPadding, vPadding, vPadding)).Contains(vPoint)) return WinApi.HitTest.HTBOTTOMRIGHT; } if (RectangleToScreen(new Rectangle(borderWidth, borderWidth, ClientRectangle.Width - 2 * borderWidth, 50)).Contains(vPoint)) return WinApi.HitTest.HTCAPTION; return WinApi.HitTest.HTCLIENT; } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButtons.Left && Movable) { if (WindowState == FormWindowState.Maximized) return; if (Width - borderWidth > e.Location.X && e.Location.X > borderWidth && e.Location.Y > borderWidth) { MoveControl(); } } } [SecuritySafeCritical] private void MoveControl() { WinApi.ReleaseCapture(); WinApi.SendMessage(Handle, (int)WinApi.Messages.WM_NCLBUTTONDOWN, (int)WinApi.HitTest.HTCAPTION, 0); } [SecuritySafeCritical] private static bool IsAeroThemeEnabled() { if (Environment.OSVersion.Version.Major <= 5) return false; bool aeroEnabled; DwmApi.DwmIsCompositionEnabled(out aeroEnabled); return aeroEnabled; } private static bool IsDropShadowSupported() { return Environment.OSVersion.Version.Major > 5 && SystemInformation.IsDropShadowEnabled; } #endregion #region Window Buttons private enum WindowButtons { Minimize, Maximize, Close } private Dictionary<WindowButtons, MetroFormButton> windowButtonList; private void AddWindowButton(WindowButtons button) { if (windowButtonList == null) windowButtonList = new Dictionary<WindowButtons, MetroFormButton>(); if (windowButtonList.ContainsKey(button)) return; MetroFormButton newButton = new MetroFormButton(); if (button == WindowButtons.Close) { newButton.Text = "r"; } else if (button == WindowButtons.Minimize) { newButton.Text = "0"; } else if (button == WindowButtons.Maximize) { if (WindowState == FormWindowState.Normal) newButton.Text = "1"; else newButton.Text = "2"; } newButton.Style = Style; newButton.Theme = Theme; newButton.Tag = button; newButton.Size = new Size(25, 20); newButton.Anchor = AnchorStyles.Top | AnchorStyles.Right; newButton.TabStop = false; //remove the form controls from the tab stop newButton.Click += WindowButton_Click; Controls.Add(newButton); windowButtonList.Add(button, newButton); } private void WindowButton_Click(object sender, EventArgs e) { var btn = sender as MetroFormButton; if (btn != null) { var btnFlag = (WindowButtons)btn.Tag; if (btnFlag == WindowButtons.Close) { Close(); } else if (btnFlag == WindowButtons.Minimize) { WindowState = FormWindowState.Minimized; } else if (btnFlag == WindowButtons.Maximize) { if (WindowState == FormWindowState.Normal) { WindowState = FormWindowState.Maximized; btn.Text = "2"; } else { WindowState = FormWindowState.Normal; btn.Text = "1"; } } } } private void UpdateWindowButtonPosition() { if (!ControlBox) return; Dictionary<int, WindowButtons> priorityOrder = new Dictionary<int, WindowButtons>(3) { {0, WindowButtons.Close}, {1, WindowButtons.Maximize}, {2, WindowButtons.Minimize} }; Point firstButtonLocation = new Point(ClientRectangle.Width - borderWidth - 25, borderWidth); int lastDrawedButtonPosition = firstButtonLocation.X - 25; MetroFormButton firstButton = null; if (windowButtonList.Count == 1) { foreach (KeyValuePair<WindowButtons, MetroFormButton> button in windowButtonList) { button.Value.Location = firstButtonLocation; } } else { foreach (KeyValuePair<int, WindowButtons> button in priorityOrder) { bool buttonExists = windowButtonList.ContainsKey(button.Value); if (firstButton == null && buttonExists) { firstButton = windowButtonList[button.Value]; firstButton.Location = firstButtonLocation; continue; } if (firstButton == null || !buttonExists) continue; windowButtonList[button.Value].Location = new Point(lastDrawedButtonPosition, borderWidth); lastDrawedButtonPosition = lastDrawedButtonPosition - 25; } } Refresh(); } private class MetroFormButton : Button, IMetroControl { #region Interface [Category(MetroDefaults.PropertyCategory.Appearance)] public event EventHandler<MetroPaintEventArgs> CustomPaintBackground; protected virtual void OnCustomPaintBackground(MetroPaintEventArgs e) { if (GetStyle(ControlStyles.UserPaint) && CustomPaintBackground != null) { CustomPaintBackground(this, e); } } [Category(MetroDefaults.PropertyCategory.Appearance)] public event EventHandler<MetroPaintEventArgs> CustomPaint; protected virtual void OnCustomPaint(MetroPaintEventArgs e) { if (GetStyle(ControlStyles.UserPaint) && CustomPaint != null) { CustomPaint(this, e); } } [Category(MetroDefaults.PropertyCategory.Appearance)] public event EventHandler<MetroPaintEventArgs> CustomPaintForeground; protected virtual void OnCustomPaintForeground(MetroPaintEventArgs e) { if (GetStyle(ControlStyles.UserPaint) && CustomPaintForeground != null) { CustomPaintForeground(this, e); } } private MetroColorStyle metroStyle = MetroColorStyle.Default; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(MetroColorStyle.Default)] public MetroColorStyle Style { get { if (DesignMode || metroStyle != MetroColorStyle.Default) { return metroStyle; } if (StyleManager != null && metroStyle == MetroColorStyle.Default) { return StyleManager.Style; } if (StyleManager == null && metroStyle == MetroColorStyle.Default) { return MetroDefaults.Style; } return metroStyle; } set { metroStyle = value; } } private MetroThemeStyle metroTheme = MetroThemeStyle.Default; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(MetroThemeStyle.Default)] public MetroThemeStyle Theme { get { if (DesignMode || metroTheme != MetroThemeStyle.Default) { return metroTheme; } if (StyleManager != null && metroTheme == MetroThemeStyle.Default) { return StyleManager.Theme; } if (StyleManager == null && metroTheme == MetroThemeStyle.Default) { return MetroDefaults.Theme; } return metroTheme; } set { metroTheme = value; } } private MetroStyleManager metroStyleManager = null; [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public MetroStyleManager StyleManager { get { return metroStyleManager; } set { metroStyleManager = value; } } private bool useCustomBackColor = false; [DefaultValue(false)] [Category(MetroDefaults.PropertyCategory.Appearance)] public bool UseCustomBackColor { get { return useCustomBackColor; } set { useCustomBackColor = value; } } private bool useCustomForeColor = false; [DefaultValue(false)] [Category(MetroDefaults.PropertyCategory.Appearance)] public bool UseCustomForeColor { get { return useCustomForeColor; } set { useCustomForeColor = value; } } private bool useStyleColors = false; [DefaultValue(false)] [Category(MetroDefaults.PropertyCategory.Appearance)] public bool UseStyleColors { get { return useStyleColors; } set { useStyleColors = value; } } [Browsable(false)] [Category(MetroDefaults.PropertyCategory.Behaviour)] [DefaultValue(false)] public bool UseSelectable { get { return GetStyle(ControlStyles.Selectable); } set { SetStyle(ControlStyles.Selectable, value); } } #endregion #region Fields private bool isHovered = false; private bool isPressed = false; #endregion #region Constructor public MetroFormButton() { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true); } #endregion #region Paint Methods protected override void OnPaint(PaintEventArgs e) { Color backColor, foreColor; MetroThemeStyle _Theme = Theme; if (Parent != null) { if (Parent is IMetroForm) { _Theme = ((IMetroForm)Parent).Theme; backColor = MetroPaint.BackColor.Form(_Theme); } else if (Parent is IMetroControl) { backColor = MetroPaint.GetStyleColor(Style); } else { backColor = Parent.BackColor; } } else { backColor = MetroPaint.BackColor.Form(_Theme); } if (isHovered && !isPressed && Enabled) { foreColor = MetroPaint.ForeColor.Button.Normal(_Theme); backColor = MetroPaint.BackColor.Button.Normal(_Theme); } else if (isHovered && isPressed && Enabled) { foreColor = MetroPaint.ForeColor.Button.Press(_Theme); backColor = MetroPaint.GetStyleColor(Style); } else if (!Enabled) { foreColor = MetroPaint.ForeColor.Button.Disabled(_Theme); backColor = MetroPaint.BackColor.Button.Disabled(_Theme); } else { foreColor = MetroPaint.ForeColor.Button.Normal(_Theme); } e.Graphics.Clear(backColor); Font buttonFont = new Font("Webdings", 12.25f, GraphicsUnit.Pixel); TextRenderer.DrawText(e.Graphics, Text, buttonFont, ClientRectangle, foreColor, backColor, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis); } #endregion #region Mouse Methods protected override void OnMouseEnter(EventArgs e) { isHovered = true; Invalidate(); base.OnMouseEnter(e); } protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { isPressed = true; Invalidate(); } base.OnMouseDown(e); } protected override void OnMouseUp(MouseEventArgs e) { isPressed = false; Invalidate(); base.OnMouseUp(e); } protected override void OnMouseLeave(EventArgs e) { isHovered = false; Invalidate(); base.OnMouseLeave(e); } #endregion } #endregion #region Shadows private const int CS_DROPSHADOW = 0x20000; const int WS_MINIMIZEBOX = 0x20000; protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.Style |= WS_MINIMIZEBOX; if (ShadowType == MetroFormShadowType.SystemShadow) cp.ClassStyle |= CS_DROPSHADOW; return cp; } } private Form shadowForm; private void CreateShadow() { switch (ShadowType) { case MetroFormShadowType.Flat: shadowForm = new MetroFlatDropShadow(this); return; case MetroFormShadowType.DropShadow: shadowForm = new MetroRealisticDropShadow(this); return; } } private void RemoveShadow() { if (shadowForm == null || shadowForm.IsDisposed) return; shadowForm.Visible = false; Owner = shadowForm.Owner; shadowForm.Owner = null; shadowForm.Dispose(); shadowForm = null; } #region MetroShadowBase protected abstract class MetroShadowBase : Form { protected Form TargetForm { get; private set; } private readonly int shadowSize; private readonly int wsExStyle; protected MetroShadowBase(Form targetForm, int shadowSize, int wsExStyle) { TargetForm = targetForm; this.shadowSize = shadowSize; this.wsExStyle = wsExStyle; TargetForm.Activated += OnTargetFormActivated; TargetForm.ResizeBegin += OnTargetFormResizeBegin; TargetForm.ResizeEnd += OnTargetFormResizeEnd; TargetForm.VisibleChanged += OnTargetFormVisibleChanged; TargetForm.SizeChanged += OnTargetFormSizeChanged; TargetForm.Move += OnTargetFormMove; TargetForm.Resize += OnTargetFormResize; if (TargetForm.Owner != null) Owner = TargetForm.Owner; TargetForm.Owner = this; MaximizeBox = false; MinimizeBox = false; ShowInTaskbar = false; ShowIcon = false; FormBorderStyle = FormBorderStyle.None; Bounds = GetShadowBounds(); } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle |= wsExStyle; return cp; } } private Rectangle GetShadowBounds() { Rectangle r = TargetForm.Bounds; r.Inflate(shadowSize, shadowSize); return r; } protected abstract void PaintShadow(); protected abstract void ClearShadow(); #region Event Handlers private bool isBringingToFront; protected override void OnDeactivate(EventArgs e) { base.OnDeactivate(e); isBringingToFront = true; } private void OnTargetFormActivated(object sender, EventArgs e) { if (Visible) Update(); if (isBringingToFront) { Visible = true; isBringingToFront = false; return; } BringToFront(); } private void OnTargetFormVisibleChanged(object sender, EventArgs e) { Visible = TargetForm.Visible && TargetForm.WindowState != FormWindowState.Minimized; Update(); } private long lastResizedOn; private bool IsResizing { get { return lastResizedOn > 0; } } private void OnTargetFormResizeBegin(object sender, EventArgs e) { lastResizedOn = DateTime.Now.Ticks; } private void OnTargetFormMove(object sender, EventArgs e) { if (!TargetForm.Visible || TargetForm.WindowState != FormWindowState.Normal) { Visible = false; } else { Bounds = GetShadowBounds(); } } private void OnTargetFormResize(object sender, EventArgs e) { ClearShadow(); } private void OnTargetFormSizeChanged(object sender, EventArgs e) { Bounds = GetShadowBounds(); if (IsResizing) { return; } PaintShadowIfVisible(); } private void OnTargetFormResizeEnd(object sender, EventArgs e) { lastResizedOn = 0; PaintShadowIfVisible(); } private void PaintShadowIfVisible() { if (TargetForm.Visible && TargetForm.WindowState != FormWindowState.Minimized) PaintShadow(); } #endregion #region Constants protected const int WS_EX_TRANSPARENT = 0x20; protected const int WS_EX_LAYERED = 0x80000; protected const int WS_EX_NOACTIVATE = 0x8000000; private const int TICKS_PER_MS = 10000; private const long RESIZE_REDRAW_INTERVAL = 1000 * TICKS_PER_MS; #endregion } #endregion #region Aero DropShadow protected class MetroAeroDropShadow : MetroShadowBase { public MetroAeroDropShadow(Form targetForm) : base(targetForm, 0, WS_EX_TRANSPARENT | WS_EX_NOACTIVATE ) { FormBorderStyle = FormBorderStyle.SizableToolWindow; } protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { if (specified == BoundsSpecified.Size) return; base.SetBoundsCore(x, y, width, height, specified); } protected override void PaintShadow() { Visible = true; } protected override void ClearShadow() { } } #endregion #region Flat DropShadow protected class MetroFlatDropShadow : MetroShadowBase { private Point Offset = new Point(-6, -6); public MetroFlatDropShadow(Form targetForm) : base(targetForm, 6, WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE) { } protected override void OnLoad(EventArgs e) { base.OnLoad(e); PaintShadow(); } protected override void OnPaint(PaintEventArgs e) { Visible = true; PaintShadow(); } protected override void PaintShadow() { using( Bitmap getShadow = DrawBlurBorder() ) SetBitmap(getShadow, 255); } protected override void ClearShadow() { Bitmap img = new Bitmap(Width, Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(img); g.Clear(Color.Transparent); g.Flush(); g.Dispose(); SetBitmap(img, 255); img.Dispose(); } #region Drawing methods [SecuritySafeCritical] private void SetBitmap(Bitmap bitmap, byte opacity) { if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) throw new ApplicationException("The bitmap must be 32ppp with alpha-channel."); IntPtr screenDc = WinApi.GetDC(IntPtr.Zero); IntPtr memDc = WinApi.CreateCompatibleDC(screenDc); IntPtr hBitmap = IntPtr.Zero; IntPtr oldBitmap = IntPtr.Zero; try { hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); oldBitmap = WinApi.SelectObject(memDc, hBitmap); WinApi.SIZE size = new WinApi.SIZE(bitmap.Width, bitmap.Height); WinApi.POINT pointSource = new WinApi.POINT(0, 0); WinApi.POINT topPos = new WinApi.POINT(Left, Top); WinApi.BLENDFUNCTION blend = new WinApi.BLENDFUNCTION(); blend.BlendOp = WinApi.AC_SRC_OVER; blend.BlendFlags = 0; blend.SourceConstantAlpha = opacity; blend.AlphaFormat = WinApi.AC_SRC_ALPHA; WinApi.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, WinApi.ULW_ALPHA); } finally { WinApi.ReleaseDC(IntPtr.Zero, screenDc); if (hBitmap != IntPtr.Zero) { WinApi.SelectObject(memDc, oldBitmap); WinApi.DeleteObject(hBitmap); } WinApi.DeleteDC(memDc); } } private Bitmap DrawBlurBorder() { return (Bitmap)DrawOutsetShadow(Color.Black, new Rectangle(0, 0, ClientRectangle.Width, ClientRectangle.Height)); } private Image DrawOutsetShadow(Color color, Rectangle shadowCanvasArea) { Rectangle rOuter = shadowCanvasArea; Rectangle rInner = new Rectangle(shadowCanvasArea.X + (-Offset.X - 1), shadowCanvasArea.Y + (-Offset.Y - 1), shadowCanvasArea.Width - (-Offset.X * 2 - 1), shadowCanvasArea.Height - (-Offset.Y * 2 - 1)); Bitmap img = new Bitmap(rOuter.Width, rOuter.Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(img); g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; using (Brush bgBrush = new SolidBrush(Color.FromArgb(30, Color.Black))) { g.FillRectangle(bgBrush, rOuter); } using (Brush bgBrush = new SolidBrush(Color.FromArgb(60, Color.Black))) { g.FillRectangle(bgBrush, rInner); } g.Flush(); g.Dispose(); return img; } #endregion } #endregion #region Realistic DropShadow protected class MetroRealisticDropShadow : MetroShadowBase { public MetroRealisticDropShadow(Form targetForm) : base(targetForm, 15, WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE) { } protected override void OnLoad(EventArgs e) { base.OnLoad(e); PaintShadow(); } protected override void OnPaint(PaintEventArgs e) { Visible = true; PaintShadow(); } protected override void PaintShadow() { using( Bitmap getShadow = DrawBlurBorder() ) SetBitmap(getShadow, 255); } protected override void ClearShadow() { Bitmap img = new Bitmap(Width, Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(img); g.Clear(Color.Transparent); g.Flush(); g.Dispose(); SetBitmap(img, 255); img.Dispose(); } #region Drawing methods [SecuritySafeCritical] private void SetBitmap(Bitmap bitmap, byte opacity) { if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) throw new ApplicationException("The bitmap must be 32ppp with alpha-channel."); IntPtr screenDc = WinApi.GetDC(IntPtr.Zero); IntPtr memDc = WinApi.CreateCompatibleDC(screenDc); IntPtr hBitmap = IntPtr.Zero; IntPtr oldBitmap = IntPtr.Zero; try { hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); oldBitmap = WinApi.SelectObject(memDc, hBitmap); WinApi.SIZE size = new WinApi.SIZE(bitmap.Width, bitmap.Height); WinApi.POINT pointSource = new WinApi.POINT(0, 0); WinApi.POINT topPos = new WinApi.POINT(Left, Top); WinApi.BLENDFUNCTION blend = new WinApi.BLENDFUNCTION { BlendOp = WinApi.AC_SRC_OVER, BlendFlags = 0, SourceConstantAlpha = opacity, AlphaFormat = WinApi.AC_SRC_ALPHA }; WinApi.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, WinApi.ULW_ALPHA); } finally { WinApi.ReleaseDC(IntPtr.Zero, screenDc); if (hBitmap != IntPtr.Zero) { WinApi.SelectObject(memDc, oldBitmap); WinApi.DeleteObject(hBitmap); } WinApi.DeleteDC(memDc); } } private Bitmap DrawBlurBorder() { return (Bitmap)DrawOutsetShadow(0, 0, 40, 1, Color.Black, new Rectangle(1, 1, ClientRectangle.Width, ClientRectangle.Height)); } private Image DrawOutsetShadow(int hShadow, int vShadow, int blur, int spread, Color color, Rectangle shadowCanvasArea) { Rectangle rOuter = shadowCanvasArea; Rectangle rInner = shadowCanvasArea; rInner.Offset(hShadow, vShadow); rInner.Inflate(-blur, -blur); rOuter.Inflate(spread, spread); rOuter.Offset(hShadow, vShadow); Rectangle originalOuter = rOuter; Bitmap img = new Bitmap(originalOuter.Width, originalOuter.Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(img); g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; var currentBlur = 0; do { var transparency = (rOuter.Height - rInner.Height) / (double)(blur * 2 + spread * 2); var shadowColor = Color.FromArgb(((int)(200 * (transparency * transparency))), color); var rOutput = rInner; rOutput.Offset(-originalOuter.Left, -originalOuter.Top); DrawRoundedRectangle(g, rOutput, currentBlur, Pens.Transparent, shadowColor); rInner.Inflate(1, 1); currentBlur = (int)((double)blur * (1 - (transparency * transparency))); } while (rOuter.Contains(rInner)); g.Flush(); g.Dispose(); return img; } private void DrawRoundedRectangle(Graphics g, Rectangle bounds, int cornerRadius, Pen drawPen, Color fillColor) { int strokeOffset = Convert.ToInt32(Math.Ceiling(drawPen.Width)); bounds = Rectangle.Inflate(bounds, -strokeOffset, -strokeOffset); var gfxPath = new GraphicsPath(); if (cornerRadius > 0) { gfxPath.AddArc(bounds.X, bounds.Y, cornerRadius, cornerRadius, 180, 90); gfxPath.AddArc(bounds.X + bounds.Width - cornerRadius, bounds.Y, cornerRadius, cornerRadius, 270, 90); gfxPath.AddArc(bounds.X + bounds.Width - cornerRadius, bounds.Y + bounds.Height - cornerRadius, cornerRadius, cornerRadius, 0, 90); gfxPath.AddArc(bounds.X, bounds.Y + bounds.Height - cornerRadius, cornerRadius, cornerRadius, 90, 90); } else { gfxPath.AddRectangle(bounds); } gfxPath.CloseAllFigures(); if (cornerRadius > 5) { using (SolidBrush b = new SolidBrush(fillColor)) { g.FillPath(b, gfxPath); } } if (drawPen != Pens.Transparent) { using (Pen p = new Pen(drawPen.Color)) { p.EndCap = p.StartCap = LineCap.Round; g.DrawPath(p, gfxPath); } } } #endregion } #endregion #endregion #region Helper Methods [SecuritySafeCritical] public void RemoveCloseButton() { IntPtr hMenu = WinApi.GetSystemMenu(Handle, false); if (hMenu == IntPtr.Zero) return; int n = WinApi.GetMenuItemCount(hMenu); if (n <= 0) return; WinApi.RemoveMenu(hMenu, (uint)(n - 1), WinApi.MfByposition | WinApi.MfRemove); WinApi.RemoveMenu(hMenu, (uint)(n - 2), WinApi.MfByposition | WinApi.MfRemove); WinApi.DrawMenuBar(Handle); } private Rectangle MeasureText(Graphics g, Rectangle clientRectangle, Font font, string text, TextFormatFlags flags) { var proposedSize = new Size(int.MaxValue, int.MinValue); var actualSize = TextRenderer.MeasureText(g, text, font, proposedSize, flags); return new Rectangle(clientRectangle.X, clientRectangle.Y, actualSize.Width, actualSize.Height); } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Controls.ComboBox.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Controls { public partial class ComboBox : System.Windows.Controls.Primitives.Selector { #region Methods and constructors public ComboBox() { } protected override System.Windows.DependencyObject GetContainerForItemOverride() { return default(System.Windows.DependencyObject); } protected override bool IsItemItsOwnContainerOverride(Object item) { return default(bool); } public override void OnApplyTemplate() { } protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return default(System.Windows.Automation.Peers.AutomationPeer); } protected virtual new void OnDropDownClosed(EventArgs e) { } protected virtual new void OnDropDownOpened(EventArgs e) { } protected override void OnIsKeyboardFocusWithinChanged(System.Windows.DependencyPropertyChangedEventArgs e) { } protected override void OnIsMouseCapturedChanged(System.Windows.DependencyPropertyChangedEventArgs e) { } protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e) { } protected override void OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e) { } protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e) { } protected override void OnSelectionChanged(SelectionChangedEventArgs e) { } protected override void PrepareContainerForItemOverride(System.Windows.DependencyObject element, Object item) { } #endregion #region Properties and indexers internal protected override bool HandlesScrolling { get { return default(bool); } } public bool IsDropDownOpen { get { return default(bool); } set { } } public bool IsEditable { get { return default(bool); } set { } } public bool IsReadOnly { get { return default(bool); } set { } } public bool IsSelectionBoxHighlighted { get { return default(bool); } } public double MaxDropDownHeight { get { return default(double); } set { } } public Object SelectionBoxItem { get { return default(Object); } private set { } } public string SelectionBoxItemStringFormat { get { return default(string); } private set { } } public System.Windows.DataTemplate SelectionBoxItemTemplate { get { return default(System.Windows.DataTemplate); } private set { } } public bool StaysOpenOnEdit { get { return default(bool); } set { } } public string Text { get { return default(string); } set { } } #endregion #region Events public event EventHandler DropDownClosed { add { } remove { } } public event EventHandler DropDownOpened { add { } remove { } } #endregion #region Fields public readonly static System.Windows.DependencyProperty IsDropDownOpenProperty; public readonly static System.Windows.DependencyProperty IsEditableProperty; public readonly static System.Windows.DependencyProperty IsReadOnlyProperty; public readonly static System.Windows.DependencyProperty MaxDropDownHeightProperty; public readonly static System.Windows.DependencyProperty SelectionBoxItemProperty; public readonly static System.Windows.DependencyProperty SelectionBoxItemStringFormatProperty; public readonly static System.Windows.DependencyProperty SelectionBoxItemTemplateProperty; public readonly static System.Windows.DependencyProperty StaysOpenOnEditProperty; public readonly static System.Windows.DependencyProperty TextProperty; #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using FluentModelBuilder.Alterations; using FluentModelBuilder.Builder; using FluentModelBuilder.Builder.Sources; namespace FluentModelBuilder.Configuration { /// <summary> /// Starting point for automodelbuilder configuration /// </summary> public static class From { #region Type Sources /// <summary> /// Map classes from provided type source /// </summary> /// <param name="source">Type source to use</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder Source(ITypeSource source) => new AutoModelBuilder().AddTypeSource(source); /// <summary> /// Map classes from provided type source /// </summary> /// <typeparam name="TSource">Type source to use</typeparam> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder Source<TSource>() where TSource : ITypeSource => new AutoModelBuilder().AddTypeSource<TSource>(); /// <summary> /// Map classes from provided type source with supplied configuration /// </summary> /// <param name="source">Type source to use</param> /// <param name="configuration">Configuration to use</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder Source(ITypeSource source, IEntityAutoConfiguration configuration) => new AutoModelBuilder(configuration).AddTypeSource(source); /// <summary> /// Map classes from provided type source with supplied configuration /// </summary> /// <typeparam name="TSource">Type source to use</typeparam> /// <param name="configuration">Configuration to use</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder Source<TSource>(IEntityAutoConfiguration configuration) where TSource : ITypeSource => new AutoModelBuilder(configuration).AddTypeSource<TSource>(); /// <summary> /// Map classes from provided type source with supplied expression /// </summary> /// <param name="source">Type source to use</param> /// <param name="expression">Configuration to use</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder Source(ITypeSource source, Func<Type, bool> expression) => new AutoModelBuilder().AddTypeSource(source).Where(expression); /// <summary> /// Map classes from provided type source with supplied expression /// </summary> /// <typeparam name="TSource">Type source to use</typeparam> /// <param name="expression">Configuration to use</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder Source<TSource>(Func<Type, bool> expression) where TSource : ITypeSource => new AutoModelBuilder().AddTypeSource<TSource>().Where(expression); #endregion #region Alterations public static AutoModelBuilder Alteration(IAutoModelBuilderAlteration alteration) => Empty().AddAlteration(alteration); public static AutoModelBuilder Alteration(IAutoModelBuilderAlteration alteration, IEntityAutoConfiguration configuration) => Empty(configuration).AddAlteration(alteration); public static AutoModelBuilder Alterations(IEnumerable<IAutoModelBuilderAlteration> alterations) => Empty().AddAlterations(alterations); public static AutoModelBuilder Alterations(IEnumerable<IAutoModelBuilderAlteration> alterations, IEntityAutoConfiguration configuration) => Empty(configuration).AddAlterations(alterations); public static AutoModelBuilder Alteration(Type type) => Empty().AddAlteration(type); public static AutoModelBuilder Alteration(Type type, IEntityAutoConfiguration configuration) => Empty(configuration).AddAlteration(type); public static AutoModelBuilder Alteration<TAlteration>() where TAlteration : IAutoModelBuilderAlteration => Empty().AddAlteration<TAlteration>(); public static AutoModelBuilder Alteration<TAlteration>(IEntityAutoConfiguration configuration) where TAlteration : IAutoModelBuilderAlteration => Empty().AddAlteration<TAlteration>(); #endregion #region Assemblies /// <summary> /// Map classes from provided assemblies /// </summary> /// <param name="assemblies">Assemblies to scan</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder Assemblies(params Assembly[] assemblies) => Source(new CombinedAssemblyTypeSource(assemblies.Select(x => new AssemblyTypeSource(x)))); /// <summary> /// Map classes from provided assemblies /// </summary> /// <param name="configuration">Configuration to use</param> /// <param name="assemblies">Assemblies to scan</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder Assemblies(IEntityAutoConfiguration configuration, params Assembly[] assemblies) => Source(new CombinedAssemblyTypeSource(assemblies.Select(x => new AssemblyTypeSource(x))), configuration); /// <summary> /// Map classes from provided assemblies /// </summary> /// <param name="configuration">Configuration to use</param> /// <param name="assemblies">Assemblies to scan</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder Assemblies(IEntityAutoConfiguration configuration, IEnumerable<Assembly> assemblies) => Source(new CombinedAssemblyTypeSource(assemblies.Select(x => new AssemblyTypeSource(x))), configuration); /// <summary> /// Map classes from provided assembly /// </summary> /// <param name="assembly">Assembly to scan</param> /// <returns></returns> public static AutoModelBuilder Assembly(Assembly assembly) => Source(new AssemblyTypeSource(assembly)); /// <summary> /// Map classes from provided assembly with supplied configuration /// </summary> /// <param name="assembly">Assembly to scan</param> /// <param name="configuration">Configuration to use</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder Assembly(Assembly assembly, IEntityAutoConfiguration configuration) => Source(new AssemblyTypeSource(assembly), configuration); /// <summary> /// Map classes from provided assembly with supplied expression /// </summary> /// <param name="assembly">Assembly to scan</param> /// <param name="expression">Expression to use to filter types</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder Assembly(Assembly assembly, Func<Type, bool> expression) => Source(new AssemblyTypeSource(assembly), expression); /// <summary> /// Map classes from the assembly containing /// <typeparam name="T"></typeparam> /// </summary> /// <typeparam name="T">Type contained in the required assembly</typeparam> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder AssemblyOf<T>() => Assembly(typeof (T).GetTypeInfo().Assembly); /// <summary> /// Map classes from the assembly containing /// <typeparam name="T"></typeparam> /// with supplied configuration /// </summary> /// <typeparam name="T">Type contained in the required assembly</typeparam> /// <param name="configuration">Configuration to use</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder AssemblyOf<T>(IEntityAutoConfiguration configuration) => Assembly(typeof (T).GetTypeInfo().Assembly, configuration); /// <summary> /// Map classes from the assembly containing /// <typeparam name="T"></typeparam> /// with supplied expression /// </summary> /// <typeparam name="T">Type contained in the required assembly</typeparam> /// <param name="expression">Expression to use</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder AssemblyOf<T>(Func<Type, bool> expression) => Assembly(typeof (T).GetTypeInfo().Assembly, expression); /// <summary> /// Map classes from the assembly containing the provided type /// </summary> /// <param name="type">Type contained in the required assembly</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder AssemblyOf(Type type) => Assembly(type.GetTypeInfo().Assembly); /// <summary> /// Map classes from the assembly containing the provided type /// with supplied configuration /// </summary> /// <param name="type">Type contained in the required assembly</param> /// <param name="configuration">Configuration to use</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder AssemblyOf(Type type, IEntityAutoConfiguration configuration) => Assembly(type.GetTypeInfo().Assembly, configuration); /// <summary> /// Map classes from the assembly containing the provided type /// with supplied expression /// </summary> /// <param name="type">Type contained in the required assembly</param> /// <param name="expression">Expression to use</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder AssemblyOf(Type type, Func<Type, bool> expression) => Assembly(type.GetTypeInfo().Assembly, expression); #endregion #region Empty /// <summary> /// Map classes based on all manual specifications /// </summary> /// <remarks> /// You would use this if you didn't want to use any assembly or source by default, but rather /// manually configure entire AutoModelBuilder yourself. /// </remarks> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder Empty() => new AutoModelBuilder(); /// <summary> /// Map classes based on all manual specifications with supplied configuration /// </summary> /// <param name="configuration">Configuration to use</param> /// <returns>AutoModelBuilder</returns> public static AutoModelBuilder Empty(IEntityAutoConfiguration configuration) => new AutoModelBuilder(configuration); #endregion /// <summary> /// Map classes based on all manual specifications with supplied expression /// </summary> /// <param name="expression"></param> /// <returns></returns> public static AutoModelBuilder Expression(Func<Type, bool> expression) => Empty().Where(expression); } }
using System; using System.IO; using System.Runtime.InteropServices; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using SolidWorks.Interop.swpublished; using SolidWorksTools; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab; namespace ALITECS.SWx.SESE { /// <summary> /// Summary description for SESE. /// </summary> [Guid("ff6692f4-1c7b-4058-b865-8c45967bca16"), ComVisible(true)] [SwAddin( Description = "SolidWorks Easy STL Export", Title = "SESE", LoadAtStartup = true )] public class SwAddin : ISwAddin { #region Local Variables private int addinID = 0; private ISldWorks iSwApp = null; // Public Properties public ISldWorks SwApp { get { return iSwApp; } } #endregion Local Variables #region SolidWorks Registration [ComRegisterFunctionAttribute] public static void RegisterFunction(Type t) { #region Get Custom Attribute: SwAddinAttribute SwAddinAttribute SWattr = null; Type type = typeof(SwAddin); foreach (System.Attribute attr in type.GetCustomAttributes(false)) { if (attr is SwAddinAttribute) { SWattr = attr as SwAddinAttribute; break; } } #endregion Get Custom Attribute: SwAddinAttribute try { Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.LocalMachine; Microsoft.Win32.RegistryKey hkcu = Microsoft.Win32.Registry.CurrentUser; string keyname = "SOFTWARE\\SolidWorks\\Addins\\{" + t.GUID.ToString() + "}"; Microsoft.Win32.RegistryKey addinkey = hklm.CreateSubKey(keyname); addinkey.SetValue(null, 0); addinkey.SetValue("Description", SWattr.Description); addinkey.SetValue("Title", SWattr.Title); keyname = "Software\\SolidWorks\\AddInsStartup\\{" + t.GUID.ToString() + "}"; addinkey = hkcu.CreateSubKey(keyname); addinkey.SetValue(null, Convert.ToInt32(SWattr.LoadAtStartup), Microsoft.Win32.RegistryValueKind.DWord); } catch (System.NullReferenceException nl) { Console.WriteLine("There was a problem registering this dll: SWattr is null. \n\"" + nl.Message + "\""); System.Windows.Forms.MessageBox.Show("There was a problem registering this dll: SWattr is null.\n\"" + nl.Message + "\""); } catch (System.Exception e) { Console.WriteLine(e.Message); System.Windows.Forms.MessageBox.Show("There was a problem registering the function: \n\"" + e.Message + "\""); } } [ComUnregisterFunctionAttribute] public static void UnregisterFunction(Type t) { try { Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.LocalMachine; Microsoft.Win32.RegistryKey hkcu = Microsoft.Win32.Registry.CurrentUser; string keyname = "SOFTWARE\\SolidWorks\\Addins\\{" + t.GUID.ToString() + "}"; hklm.DeleteSubKey(keyname); keyname = "Software\\SolidWorks\\AddInsStartup\\{" + t.GUID.ToString() + "}"; hkcu.DeleteSubKey(keyname); } catch (System.NullReferenceException nl) { Console.WriteLine("There was a problem unregistering this dll: " + nl.Message); System.Windows.Forms.MessageBox.Show("There was a problem unregistering this dll: \n\"" + nl.Message + "\""); } catch (System.Exception e) { Console.WriteLine("There was a problem unregistering this dll: " + e.Message); System.Windows.Forms.MessageBox.Show("There was a problem unregistering this dll: \n\"" + e.Message + "\""); } } #endregion SolidWorks Registration #region ISwAddin Implementation public SwAddin() { } public bool ConnectToSW(object ThisSW, int cookie) { iSwApp = (ISldWorks)ThisSW; addinID = cookie; //Setup callbacks iSwApp.SetAddinCallbackInfo(0, this, addinID); iSwApp.AddMenuItem4((int)swDocumentTypes_e.swDocPART, addinID, "Export STLs", -1, "ExportPartSTLs", "", "", ""); return true; } public bool DisconnectFromSW() { System.Runtime.InteropServices.Marshal.ReleaseComObject(iSwApp); iSwApp = null; //The addin _must_ call GC.Collect() here in order to retrieve all managed code pointers GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); return true; } #endregion ISwAddin Implementation #region UI Callbacks public void ExportPartSTLs() { int errors = 0; int warnings = 0; var swxVersion = iSwApp.RevisionNumber().Split('.'); ModelDoc2 mdoc = iSwApp.ActiveDoc; PartDoc pdoc = iSwApp.ActiveDoc; SelectData swSelectData = default(SelectData); swSelectData = (SelectData)mdoc.SelectionManager.CreateSelectData(); // get all solid bodies of the part object[] bodies = pdoc.GetBodies2(0, false); // the the full path of the opened document string path = mdoc.GetPathName(); var activeConfigurationName = (string)mdoc.GetActiveConfiguration().Name; var configurationCount = mdoc.GetConfigurationCount(); foreach (string configurationName in mdoc.GetConfigurationNames()) { mdoc.ShowConfiguration2(configurationName); if (bodies.Length > 1) // if there are more than one body in the part { foreach (Body2 body in bodies) { body.HideBody(false); // set export coordinate system to one which is named "STL_" + body's name mdoc.Extension.SetUserPreferenceString((int)swUserPreferenceStringValue_e.swFileSaveAsCoordinateSystem, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, "STL_" + body.Name); if (int.Parse(swxVersion[0]) <= 25) { body.Select2(false, swSelectData); // select the body } else { foreach (Body2 body2 in bodies) { if (body2.Name != body.Name) body2.HideBody(true); } } // save an STL in the same directory as the document but named after the body string filename = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + "_" + body.Name + (configurationCount > 1 ? "_" + configurationName : "") + ".stl"; mdoc.Extension.SaveAs(filename, 0, 3, null, errors, warnings); } if (int.Parse(swxVersion[0]) > 25) { foreach (Body2 body2 in bodies) { body2.HideBody(false); } } } else // if there is only one body { // set export coordinate system to one which is named "STL" mdoc.Extension.SetUserPreferenceString((int)swUserPreferenceStringValue_e.swFileSaveAsCoordinateSystem, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, "STL"); mdoc.ClearSelection2(true); // save an STL in the same directory as the document named after the document string filename = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + (configurationCount > 1 ? "_" + configurationName : "") + ".stl"; mdoc.Extension.SaveAs(filename, 0, 3, null, errors, warnings); } } mdoc.ShowConfiguration2(activeConfigurationName); } #endregion UI Callbacks } }
#region License /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #endregion using System; using System.Net.WebSockets; using System.Threading.Tasks; using Gremlin.Net.Driver.Messages; using Gremlin.Net.Structure.IO; using Gremlin.Net.Structure.IO.GraphSON; namespace Gremlin.Net.Driver { /// <summary> /// Provides a mechanism for submitting Gremlin requests to one Gremlin Server. /// </summary> public class GremlinClient : IGremlinClient { private readonly ConnectionPool _connectionPool; /// <summary> /// Initializes a new instance of the <see cref="GremlinClient" /> class for the specified Gremlin Server. /// </summary> /// <param name="gremlinServer">The <see cref="GremlinServer" /> the requests should be sent to.</param> /// <param name="graphSONReader">A <see cref="GraphSONReader" /> instance to read received GraphSON data.</param> /// <param name="graphSONWriter">a <see cref="GraphSONWriter" /> instance to write GraphSON data.</param> /// <param name="connectionPoolSettings">The <see cref="ConnectionPoolSettings" /> for the connection pool.</param> /// <param name="webSocketConfiguration"> /// A delegate that will be invoked with the <see cref="ClientWebSocketOptions" /> /// object used to configure WebSocket connections. /// </param> /// <param name="sessionId">The session Id if Gremlin Client in session mode, defaults to null as session-less Client.</param> [Obsolete("This constructor is obsolete. Use the constructor that takes a IMessageSerializer instead.")] public GremlinClient(GremlinServer gremlinServer, GraphSONReader graphSONReader, GraphSONWriter graphSONWriter, ConnectionPoolSettings connectionPoolSettings = null, Action<ClientWebSocketOptions> webSocketConfiguration = null, string sessionId = null) : this(gremlinServer, graphSONReader, graphSONWriter, SerializationTokens.GraphSON3MimeType, connectionPoolSettings, webSocketConfiguration, sessionId) { } /// <summary> /// Initializes a new instance of the <see cref="GremlinClient" /> class for the specified Gremlin Server. /// </summary> /// <param name="gremlinServer">The <see cref="GremlinServer" /> the requests should be sent to.</param> /// <param name="graphSONReader">A <see cref="GraphSONReader" /> instance to read received GraphSON data.</param> /// <param name="graphSONWriter">a <see cref="GraphSONWriter" /> instance to write GraphSON data.</param> /// <param name="mimeType">The GraphSON version mime type, defaults to latest supported by the server.</param> /// <param name="connectionPoolSettings">The <see cref="ConnectionPoolSettings" /> for the connection pool.</param> /// <param name="webSocketConfiguration"> /// A delegate that will be invoked with the <see cref="ClientWebSocketOptions" /> /// object used to configure WebSocket connections. /// </param> /// <param name="sessionId">The session Id if Gremlin Client in session mode, defaults to null as session-less Client.</param> [Obsolete("This constructor is obsolete. Use the constructor that takes a IMessageSerializer instead.")] public GremlinClient(GremlinServer gremlinServer, GraphSONReader graphSONReader, GraphSONWriter graphSONWriter, string mimeType, ConnectionPoolSettings connectionPoolSettings = null, Action<ClientWebSocketOptions> webSocketConfiguration = null, string sessionId = null) { IMessageSerializer messageSerializer; switch (mimeType) { case SerializationTokens.GraphSON3MimeType: VerifyGraphSONArgumentTypeForMimeType<GraphSON3Reader>(graphSONReader, nameof(graphSONReader), mimeType); VerifyGraphSONArgumentTypeForMimeType<GraphSON3Writer>(graphSONWriter, nameof(graphSONWriter), mimeType); messageSerializer = new GraphSON3MessageSerializer( (GraphSON3Reader) graphSONReader ?? new GraphSON3Reader(), (GraphSON3Writer) graphSONWriter ?? new GraphSON3Writer()); break; case SerializationTokens.GraphSON2MimeType: VerifyGraphSONArgumentTypeForMimeType<GraphSON2Reader>(graphSONReader, nameof(graphSONReader), mimeType); VerifyGraphSONArgumentTypeForMimeType<GraphSON2Writer>(graphSONWriter, nameof(graphSONWriter), mimeType); messageSerializer = new GraphSON2MessageSerializer( (GraphSON2Reader) graphSONReader ?? new GraphSON2Reader(), (GraphSON2Writer) graphSONWriter ?? new GraphSON2Writer()); break; default: throw new ArgumentException(nameof(mimeType), $"{mimeType} not supported"); } var connectionFactory = new ConnectionFactory(gremlinServer, messageSerializer, new WebSocketSettings { WebSocketConfigurationCallback = webSocketConfiguration }, sessionId); // make sure one connection in pool as session mode if (!string.IsNullOrEmpty(sessionId)) { if (connectionPoolSettings != null) { if (connectionPoolSettings.PoolSize != 1) throw new ArgumentOutOfRangeException(nameof(connectionPoolSettings), "PoolSize must be 1 in session mode!"); } else { connectionPoolSettings = new ConnectionPoolSettings {PoolSize = 1}; } } _connectionPool = new ConnectionPool(connectionFactory, connectionPoolSettings ?? new ConnectionPoolSettings()); } private static void VerifyGraphSONArgumentTypeForMimeType<T>(object argument, string argumentName, string mimeType) { if (argument != null && !(argument is T)) { throw new ArgumentException( $"{argumentName} is not a {typeof(T).Name} but the mime type is: {mimeType}", argumentName); } } /// <summary> /// Initializes a new instance of the <see cref="GremlinClient" /> class for the specified Gremlin Server. /// </summary> /// <param name="gremlinServer">The <see cref="GremlinServer" /> the requests should be sent to.</param> /// <param name="messageSerializer"> /// A <see cref="IMessageSerializer" /> instance to serialize messages sent to and received /// from the server. /// </param> /// <param name="connectionPoolSettings">The <see cref="ConnectionPoolSettings" /> for the connection pool.</param> /// <param name="webSocketConfiguration"> /// A delegate that will be invoked with the <see cref="ClientWebSocketOptions" /> /// object used to configure WebSocket connections. /// </param> /// <param name="sessionId">The session Id if Gremlin Client in session mode, defaults to null as session-less Client.</param> /// <param name="disableCompression"> /// Whether to disable compression. Compression is only supported since .NET 6. /// There it is also enabled by default. /// /// Note that compression might make your application susceptible to attacks like CRIME/BREACH. Compression /// should therefore be turned off if your application sends sensitive data to the server as well as data /// that could potentially be controlled by an untrusted user. /// </param> public GremlinClient(GremlinServer gremlinServer, IMessageSerializer messageSerializer = null, ConnectionPoolSettings connectionPoolSettings = null, Action<ClientWebSocketOptions> webSocketConfiguration = null, string sessionId = null, bool disableCompression = false) { messageSerializer ??= new GraphSON3MessageSerializer(); var webSocketSettings = new WebSocketSettings { WebSocketConfigurationCallback = webSocketConfiguration #if NET6_0_OR_GREATER , UseCompression = !disableCompression #endif }; var connectionFactory = new ConnectionFactory(gremlinServer, messageSerializer, webSocketSettings, sessionId); // make sure one connection in pool as session mode if (!string.IsNullOrEmpty(sessionId)) { if (connectionPoolSettings != null) { if (connectionPoolSettings.PoolSize != 1) throw new ArgumentOutOfRangeException(nameof(connectionPoolSettings), "PoolSize must be 1 in session mode!"); } else { connectionPoolSettings = new ConnectionPoolSettings {PoolSize = 1}; } } _connectionPool = new ConnectionPool(connectionFactory, connectionPoolSettings ?? new ConnectionPoolSettings()); } /// <summary> /// Gets the number of open connections. /// </summary> public int NrConnections => _connectionPool.NrConnections; /// <inheritdoc /> public async Task<ResultSet<T>> SubmitAsync<T>(RequestMessage requestMessage) { using var connection = _connectionPool.GetAvailableConnection(); return await connection.SubmitAsync<T>(requestMessage).ConfigureAwait(false); } #region IDisposable Support private bool _disposed; /// <inheritdoc /> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases the resources used by the <see cref="GremlinClient" /> instance. /// </summary> /// <param name="disposing">Specifies whether managed resources should be released.</param> protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) _connectionPool?.Dispose(); _disposed = true; } } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.CloudSecurityToken.v1 { /// <summary>The CloudSecurityToken Service.</summary> public class CloudSecurityTokenService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public CloudSecurityTokenService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public CloudSecurityTokenService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { V1 = new V1Resource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "sts"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://sts.googleapis.com/"; #else "https://sts.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://sts.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Gets the V1 resource.</summary> public virtual V1Resource V1 { get; } } /// <summary>A base abstract class for CloudSecurityToken requests.</summary> public abstract class CloudSecurityTokenBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new CloudSecurityTokenBaseServiceRequest instance.</summary> protected CloudSecurityTokenBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes CloudSecurityToken parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "v1" collection of methods.</summary> public class V1Resource { private const string Resource = "v1"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public V1Resource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Gets information about a Google OAuth 2.0 access token issued by the Google Cloud [Security Token Service /// API](https://cloud.google.com/iam/docs/reference/sts/rest). /// </summary> /// <param name="body">The body of the request.</param> public virtual IntrospectRequest Introspect(Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1IntrospectTokenRequest body) { return new IntrospectRequest(service, body); } /// <summary> /// Gets information about a Google OAuth 2.0 access token issued by the Google Cloud [Security Token Service /// API](https://cloud.google.com/iam/docs/reference/sts/rest). /// </summary> public class IntrospectRequest : CloudSecurityTokenBaseServiceRequest<Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1IntrospectTokenResponse> { /// <summary>Constructs a new Introspect request.</summary> public IntrospectRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1IntrospectTokenRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1IntrospectTokenRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "introspect"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/introspect"; /// <summary>Initializes Introspect parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary> /// Exchanges a credential for a Google OAuth 2.0 access token. The token asserts an external identity within a /// workload identity pool, or it applies a Credential Access Boundary to a Google access token. When you call /// this method, do not send the `Authorization` HTTP header in the request. This method does not require the /// `Authorization` header, and using the header can cause the request to fail. /// </summary> /// <param name="body">The body of the request.</param> public virtual TokenRequest Token(Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1ExchangeTokenRequest body) { return new TokenRequest(service, body); } /// <summary> /// Exchanges a credential for a Google OAuth 2.0 access token. The token asserts an external identity within a /// workload identity pool, or it applies a Credential Access Boundary to a Google access token. When you call /// this method, do not send the `Authorization` HTTP header in the request. This method does not require the /// `Authorization` header, and using the header can cause the request to fail. /// </summary> public class TokenRequest : CloudSecurityTokenBaseServiceRequest<Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1ExchangeTokenResponse> { /// <summary>Constructs a new Token request.</summary> public TokenRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1ExchangeTokenRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1ExchangeTokenRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "token"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/token"; /// <summary>Initializes Token parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } } namespace Google.Apis.CloudSecurityToken.v1.Data { /// <summary>Associates `members` with a `role`.</summary> public class GoogleIamV1Binding : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The condition that is associated with this binding. If the condition evaluates to `true`, then this binding /// applies to the current request. If the condition evaluates to `false`, then this binding does not apply to /// the current request. However, a different role binding might grant the same role to one or more of the /// members in this binding. To learn which resources support conditions in their IAM policies, see the [IAM /// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("condition")] public virtual GoogleTypeExpr Condition { get; set; } /// <summary> /// Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following /// values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a /// Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated /// with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific /// Google account. For example, `alice@example.com` . * `serviceAccount:{emailid}`: An email address that /// represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`: /// An email address that represents a Google group. For example, `admins@example.com`. * /// `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that /// has been recently deleted. For example, `alice@example.com?uid=123456789012345678901`. If the user is /// recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. * /// `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a /// service account that has been recently deleted. For example, /// `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. If the service account is undeleted, /// this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the /// binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing /// a Google group that has been recently deleted. For example, `admins@example.com?uid=123456789012345678901`. /// If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role /// in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that /// domain. For example, `google.com` or `example.com`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("members")] public virtual System.Collections.Generic.IList<string> Members { get; set; } /// <summary> /// Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("role")] public virtual string Role { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// An access boundary defines the upper bound of what a principal may access. It includes a list of access boundary /// rules that each defines the resource that may be allowed as well as permissions that may be used on those /// resources. /// </summary> public class GoogleIdentityStsV1AccessBoundary : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// A list of access boundary rules which defines the upper bound of the permission a principal may carry. If /// multiple rules are specified, the effective access boundary is the union of all the access boundary rules /// attached. One access boundary can contain at most 10 rules. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("accessBoundaryRules")] public virtual System.Collections.Generic.IList<GoogleIdentityStsV1AccessBoundaryRule> AccessBoundaryRules { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>An access boundary rule defines an upper bound of IAM permissions on a single resource.</summary> public class GoogleIdentityStsV1AccessBoundaryRule : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The availability condition further constrains the access allowed by the access boundary rule. If the /// condition evaluates to `true`, then this access boundary rule will provide access to the specified resource, /// assuming the principal has the required permissions for the resource. If the condition does not evaluate to /// `true`, then access to the specified resource will not be available. Note that all access boundary rules in /// an access boundary are evaluated together as a union. As such, another access boundary rule may allow access /// to the resource, even if this access boundary rule does not allow access. To learn which resources support /// conditions in their IAM policies, see the [IAM /// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). The maximum length of the /// `expression` field is 2048 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("availabilityCondition")] public virtual GoogleTypeExpr AvailabilityCondition { get; set; } /// <summary> /// A list of permissions that may be allowed for use on the specified resource. The only supported values in /// the list are IAM roles, following the format of google.iam.v1.Binding.role. Example value: /// `inRole:roles/logging.viewer` for predefined roles and /// `inRole:organizations/{ORGANIZATION_ID}/roles/logging.viewer` for custom roles. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("availablePermissions")] public virtual System.Collections.Generic.IList<string> AvailablePermissions { get; set; } /// <summary> /// The full resource name of a Google Cloud resource entity. The format definition is at /// https://cloud.google.com/apis/design/resource_names. Example value: /// `//cloudresourcemanager.googleapis.com/projects/my-project`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("availableResource")] public virtual string AvailableResource { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for ExchangeToken.</summary> public class GoogleIdentityStsV1ExchangeTokenRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The full resource name of the identity provider; for example: /// `//iam.googleapis.com/projects//locations/global/workloadIdentityPools//providers/`. Required when /// exchanging an external credential for a Google access token. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("audience")] public virtual string Audience { get; set; } /// <summary> /// Required. The grant type. Must be `urn:ietf:params:oauth:grant-type:token-exchange`, which indicates a token /// exchange. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("grantType")] public virtual string GrantType { get; set; } /// <summary> /// A set of features that Security Token Service supports, in addition to the standard OAuth 2.0 token /// exchange, formatted as a serialized JSON object of Options. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("options")] public virtual string Options { get; set; } /// <summary> /// Required. An identifier for the type of requested security token. Must be /// `urn:ietf:params:oauth:token-type:access_token`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("requestedTokenType")] public virtual string RequestedTokenType { get; set; } /// <summary> /// The OAuth 2.0 scopes to include on the resulting access token, formatted as a list of space-delimited, /// case-sensitive strings. Required when exchanging an external credential for a Google access token. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("scope")] public virtual string Scope { get; set; } /// <summary> /// Required. The input token. This token is either an external credential issued by a workload identity pool /// provider, or a short-lived access token issued by Google. If the token is an OIDC JWT, it must use the JWT /// format defined in [RFC 7523](https://tools.ietf.org/html/rfc7523), and the `subject_token_type` must be /// either `urn:ietf:params:oauth:token-type:jwt` or `urn:ietf:params:oauth:token-type:id_token`. The following /// headers are required: - `kid`: The identifier of the signing key securing the JWT. - `alg`: The /// cryptographic algorithm securing the JWT. Must be `RS256` or `ES256`. The following payload fields are /// required. For more information, see [RFC 7523, Section 3](https://tools.ietf.org/html/rfc7523#section-3): - /// `iss`: The issuer of the token. The issuer must provide a discovery document at the URL /// `/.well-known/openid-configuration`, where `` is the value of this field. The document must be formatted /// according to section 4.2 of the [OIDC 1.0 Discovery /// specification](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse). - /// `iat`: The issue time, in seconds, since the Unix epoch. Must be in the past. - `exp`: The expiration time, /// in seconds, since the Unix epoch. Must be less than 48 hours after `iat`. Shorter expiration times are more /// secure. If possible, we recommend setting an expiration time less than 6 hours. - `sub`: The identity /// asserted in the JWT. - `aud`: For workload identity pools, this must be a value specified in the allowed /// audiences for the workload identity pool provider, or one of the audiences allowed by default if no /// audiences were specified. See /// https://cloud.google.com/iam/docs/reference/rest/v1/projects.locations.workloadIdentityPools.providers#oidc /// Example header: ``` { "alg": "RS256", "kid": "us-east-11" } ``` Example payload: ``` { "iss": /// "https://accounts.google.com", "iat": 1517963104, "exp": 1517966704, "aud": /// "//iam.googleapis.com/projects/1234567890123/locations/global/workloadIdentityPools/my-pool/providers/my-provider", /// "sub": "113475438248934895348", "my_claims": { "additional_claim": "value" } } ``` If `subject_token` is for /// AWS, it must be a serialized `GetCallerIdentity` token. This token contains the same information as a /// request to the AWS /// [`GetCallerIdentity()`](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity) method, /// as well as the AWS [signature](https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html) /// for the request information. Use Signature Version 4. Format the request as URL-encoded JSON, and set the /// `subject_token_type` parameter to `urn:ietf:params:aws:token-type:aws4_request`. The following parameters /// are required: - `url`: The URL of the AWS STS endpoint for `GetCallerIdentity()`, such as /// `https://sts.amazonaws.com?Action=GetCallerIdentity&amp;amp;Version=2011-06-15`. Regional endpoints are also /// supported. - `method`: The HTTP request method: `POST`. - `headers`: The HTTP request headers, which must /// include: - `Authorization`: The request signature. - `x-amz-date`: The time you will send the request, /// formatted as an [ISO8601 /// Basic](https://docs.aws.amazon.com/general/latest/gr/sigv4_elements.html#sigv4_elements_date) string. This /// value is typically set to the current time and is used to help prevent replay attacks. - `host`: The /// hostname of the `url` field; for example, `sts.amazonaws.com`. - `x-goog-cloud-target-resource`: The full, /// canonical resource name of the workload identity pool provider, with or without an `https:` prefix. To help /// ensure data integrity, we recommend including this header in the `SignedHeaders` field of the signed /// request. For example: //iam.googleapis.com/projects//locations/global/workloadIdentityPools//providers/ /// https://iam.googleapis.com/projects//locations/global/workloadIdentityPools//providers/ If you are using /// temporary security credentials provided by AWS, you must also include the header `x-amz-security-token`, /// with the value set to the session token. The following example shows a `GetCallerIdentity` token: ``` { /// "headers": [ {"key": "x-amz-date", "value": "20200815T015049Z"}, {"key": "Authorization", "value": /// "AWS4-HMAC-SHA256+Credential=$credential,+SignedHeaders=host;x-amz-date;x-goog-cloud-target-resource,+Signature=$signature"}, /// {"key": "x-goog-cloud-target-resource", "value": /// "//iam.googleapis.com/projects//locations/global/workloadIdentityPools//providers/"}, {"key": "host", /// "value": "sts.amazonaws.com"} . ], "method": "POST", "url": /// "https://sts.amazonaws.com?Action=GetCallerIdentity&amp;amp;Version=2011-06-15" } ``` You can also use a /// Google-issued OAuth 2.0 access token with this field to obtain an access token with new security attributes /// applied, such as a Credential Access Boundary. In this case, set `subject_token_type` to /// `urn:ietf:params:oauth:token-type:access_token`. If an access token already contains security attributes, /// you cannot apply additional security attributes. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("subjectToken")] public virtual string SubjectToken { get; set; } /// <summary> /// Required. An identifier that indicates the type of the security token in the `subject_token` parameter. /// Supported values are `urn:ietf:params:oauth:token-type:jwt`, `urn:ietf:params:oauth:token-type:id_token`, /// `urn:ietf:params:aws:token-type:aws4_request`, and `urn:ietf:params:oauth:token-type:access_token`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("subjectTokenType")] public virtual string SubjectTokenType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for ExchangeToken.</summary> public class GoogleIdentityStsV1ExchangeTokenResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// An OAuth 2.0 security token, issued by Google, in response to the token exchange request. Tokens can vary in /// size, depending in part on the size of mapped claims, up to a maximum of 12288 bytes (12 KB). Google /// reserves the right to change the token size and the maximum length at any time. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("access_token")] public virtual string AccessToken { get; set; } /// <summary> /// The amount of time, in seconds, between the time when the access token was issued and the time when the /// access token will expire. This field is absent when the `subject_token` in the request is a Google-issued, /// short-lived access token. In this case, the access token has the same expiration time as the /// `subject_token`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("expires_in")] public virtual System.Nullable<int> ExpiresIn { get; set; } /// <summary>The token type. Always matches the value of `requested_token_type` from the request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("issued_token_type")] public virtual string IssuedTokenType { get; set; } /// <summary>The type of access token. Always has the value `Bearer`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("token_type")] public virtual string TokenType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for IntrospectToken.</summary> public class GoogleIdentityStsV1IntrospectTokenRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. The OAuth 2.0 security token issued by the Security Token Service API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("token")] public virtual string Token { get; set; } /// <summary> /// Optional. The type of the given token. Supported values are `urn:ietf:params:oauth:token-type:access_token` /// and `access_token`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("tokenTypeHint")] public virtual string TokenTypeHint { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for IntrospectToken.</summary> public class GoogleIdentityStsV1IntrospectTokenResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A boolean value that indicates whether the provided access token is currently active.</summary> [Newtonsoft.Json.JsonPropertyAttribute("active")] public virtual System.Nullable<bool> Active { get; set; } /// <summary>The client identifier for the OAuth 2.0 client that requested the provided token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("client_id")] public virtual string ClientId { get; set; } /// <summary> /// The expiration timestamp, measured in the number of seconds since January 1 1970 UTC, indicating when this /// token will expire. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("exp")] public virtual System.Nullable<long> Exp { get; set; } /// <summary> /// The issued timestamp, measured in the number of seconds since January 1 1970 UTC, indicating when this token /// was originally issued. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("iat")] public virtual System.Nullable<long> Iat { get; set; } /// <summary>The issuer of the provided token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("iss")] public virtual string Iss { get; set; } /// <summary>A list of scopes associated with the provided token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("scope")] public virtual string Scope { get; set; } /// <summary> /// The unique user ID associated with the provided token. For Google Accounts, this value is based on the /// Google Account's user ID. For federated identities, this value is based on the identity pool ID and the /// value of the mapped `google.subject` attribute. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("sub")] public virtual string Sub { get; set; } /// <summary> /// The human-readable identifier for the token principal subject. For example, if the provided token is /// associated with a workload identity pool, this field contains a value in the following format: /// `principal://iam.googleapis.com/projects//locations/global/workloadIdentityPools//subject/` /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("username")] public virtual string Username { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// An `Options` object configures features that the Security Token Service supports, but that are not supported by /// standard OAuth 2.0 token exchange endpoints, as defined in https://tools.ietf.org/html/rfc8693. /// </summary> public class GoogleIdentityStsV1Options : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// An access boundary that defines the upper bound of permissions the credential may have. The value should be /// a JSON object of AccessBoundary. The access boundary can include up to 10 rules. The size of the parameter /// value should not exceed 2048 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("accessBoundary")] public virtual GoogleIdentityStsV1AccessBoundary AccessBoundary { get; set; } /// <summary> /// The intended audience(s) of the credential. The audience value(s) should be the name(s) of services intended /// to receive the credential. Example: `["https://pubsub.googleapis.com/", "https://storage.googleapis.com/"]`. /// A maximum of 5 audiences can be included. For each provided audience, the maximum length is 262 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("audiences")] public virtual System.Collections.Generic.IList<string> Audiences { get; set; } /// <summary> /// A Google project used for quota and billing purposes when the credential is used to access Google APIs. The /// provided project overrides the project bound to the credential. The value must be a project number or a /// project ID. Example: `my-sample-project-191923`. The maximum length is 32 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("userProject")] public virtual string UserProject { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// An access boundary defines the upper bound of what a principal may access. It includes a list of access boundary /// rules that each defines the resource that may be allowed as well as permissions that may be used on those /// resources. /// </summary> public class GoogleIdentityStsV1betaAccessBoundary : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// A list of access boundary rules which defines the upper bound of the permission a principal may carry. If /// multiple rules are specified, the effective access boundary is the union of all the access boundary rules /// attached. One access boundary can contain at most 10 rules. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("accessBoundaryRules")] public virtual System.Collections.Generic.IList<GoogleIdentityStsV1betaAccessBoundaryRule> AccessBoundaryRules { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>An access boundary rule defines an upper bound of IAM permissions on a single resource.</summary> public class GoogleIdentityStsV1betaAccessBoundaryRule : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The availability condition further constrains the access allowed by the access boundary rule. If the /// condition evaluates to `true`, then this access boundary rule will provide access to the specified resource, /// assuming the principal has the required permissions for the resource. If the condition does not evaluate to /// `true`, then access to the specified resource will not be available. Note that all access boundary rules in /// an access boundary are evaluated together as a union. As such, another access boundary rule may allow access /// to the resource, even if this access boundary rule does not allow access. To learn which resources support /// conditions in their IAM policies, see the [IAM /// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). The maximum length of the /// `expression` field is 2048 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("availabilityCondition")] public virtual GoogleTypeExpr AvailabilityCondition { get; set; } /// <summary> /// A list of permissions that may be allowed for use on the specified resource. The only supported values in /// the list are IAM roles, following the format of google.iam.v1.Binding.role. Example value: /// `inRole:roles/logging.viewer` for predefined roles and /// `inRole:organizations/{ORGANIZATION_ID}/roles/logging.viewer` for custom roles. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("availablePermissions")] public virtual System.Collections.Generic.IList<string> AvailablePermissions { get; set; } /// <summary> /// The full resource name of a Google Cloud resource entity. The format definition is at /// https://cloud.google.com/apis/design/resource_names. Example value: /// `//cloudresourcemanager.googleapis.com/projects/my-project`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("availableResource")] public virtual string AvailableResource { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// An `Options` object configures features that the Security Token Service supports, but that are not supported by /// standard OAuth 2.0 token exchange endpoints, as defined in https://tools.ietf.org/html/rfc8693. /// </summary> public class GoogleIdentityStsV1betaOptions : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// An access boundary that defines the upper bound of permissions the credential may have. The value should be /// a JSON object of AccessBoundary. The access boundary can include up to 10 rules. The size of the parameter /// value should not exceed 2048 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("accessBoundary")] public virtual GoogleIdentityStsV1betaAccessBoundary AccessBoundary { get; set; } /// <summary> /// The intended audience(s) of the credential. The audience value(s) should be the name(s) of services intended /// to receive the credential. Example: `["https://pubsub.googleapis.com/", "https://storage.googleapis.com/"]`. /// A maximum of 5 audiences can be included. For each provided audience, the maximum length is 262 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("audiences")] public virtual System.Collections.Generic.IList<string> Audiences { get; set; } /// <summary> /// A Google project used for quota and billing purposes when the credential is used to access Google APIs. The /// provided project overrides the project bound to the credential. The value must be a project number or a /// project ID. Example: `my-sample-project-191923`. The maximum length is 32 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("userProject")] public virtual string UserProject { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Represents a textual expression in the Common Expression Language (CEL) syntax. CEL is a C-like expression /// language. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec. Example /// (Comparison): title: "Summary size limit" description: "Determines if a summary is less than 100 chars" /// expression: "document.summary.size() &amp;lt; 100" Example (Equality): title: "Requestor is owner" description: /// "Determines if requestor is the document owner" expression: "document.owner == request.auth.claims.email" /// Example (Logic): title: "Public documents" description: "Determine whether the document should be publicly /// visible" expression: "document.type != 'private' &amp;amp;&amp;amp; document.type != 'internal'" Example (Data /// Manipulation): title: "Notification string" description: "Create a notification string with a timestamp." /// expression: "'New message received at ' + string(document.create_time)" The exact variables and functions that /// may be referenced within an expression are determined by the service that evaluates it. See the service /// documentation for additional information. /// </summary> public class GoogleTypeExpr : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. Description of the expression. This is a longer text which describes the expression, e.g. when /// hovered over it in a UI. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary>Textual representation of an expression in Common Expression Language syntax.</summary> [Newtonsoft.Json.JsonPropertyAttribute("expression")] public virtual string Expression { get; set; } /// <summary> /// Optional. String indicating the location of the expression for error reporting, e.g. a file name and a /// position in the file. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("location")] public virtual string Location { get; set; } /// <summary> /// Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs /// which allow to enter the expression. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
/* * 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 System.IO; using System.Threading; using System.Xml; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Region.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; namespace OpenSim.Region.CoreModules.Avatar.Attachments { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AttachmentsModule")] public class AttachmentsModule : IAttachmentsModule, INonSharedRegionModule { #region INonSharedRegionModule private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public int DebugLevel { get; set; } /// <summary> /// Period to sleep per 100 prims in order to avoid CPU spikes when an avatar with many attachments logs in/changes /// outfit or many avatars with a medium levels of attachments login/change outfit simultaneously. /// </summary> /// <remarks> /// A value of 0 will apply no pause. The pause is specified in milliseconds. /// </remarks> public int ThrottlePer100PrimsRezzed { get; set; } private Scene m_scene; private IInventoryAccessModule m_invAccessModule; /// <summary> /// Are attachments enabled? /// </summary> public bool Enabled { get; private set; } public string Name { get { return "Attachments Module"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { IConfig config = source.Configs["Attachments"]; if (config != null) { Enabled = config.GetBoolean("Enabled", true); ThrottlePer100PrimsRezzed = config.GetInt("ThrottlePer100PrimsRezzed", 0); } else { Enabled = true; } } public void AddRegion(Scene scene) { m_scene = scene; if (Enabled) { // Only register module with scene if it is enabled. All callers check for a null attachments module. // Ideally, there should be a null attachments module for when this core attachments module has been // disabled. Registering only when enabled allows for other attachments module implementations. m_scene.RegisterModuleInterface<IAttachmentsModule>(this); m_scene.EventManager.OnNewClient += SubscribeToClientEvents; m_scene.EventManager.OnStartScript += (localID, itemID) => HandleScriptStateChange(localID, true); m_scene.EventManager.OnStopScript += (localID, itemID) => HandleScriptStateChange(localID, false); MainConsole.Instance.Commands.AddCommand( "Debug", false, "debug attachments log", "debug attachments log [0|1]", "Turn on attachments debug logging", " <= 0 - turns off debug logging\n" + " >= 1 - turns on attachment message debug logging", HandleDebugAttachmentsLog); MainConsole.Instance.Commands.AddCommand( "Debug", false, "debug attachments throttle", "debug attachments throttle <ms>", "Turn on attachments throttling.", "This requires a millisecond value. " + " == 0 - disable throttling.\n" + " > 0 - sleeps for this number of milliseconds per 100 prims rezzed.", HandleDebugAttachmentsThrottle); MainConsole.Instance.Commands.AddCommand( "Debug", false, "debug attachments status", "debug attachments status", "Show current attachments debug status", HandleDebugAttachmentsStatus); } // TODO: Should probably be subscribing to CloseClient too, but this doesn't yet give us IClientAPI } private void HandleDebugAttachmentsLog(string module, string[] args) { int debugLevel; if (!(args.Length == 4 && int.TryParse(args[3], out debugLevel))) { MainConsole.Instance.OutputFormat("Usage: debug attachments log [0|1]"); } else { DebugLevel = debugLevel; MainConsole.Instance.OutputFormat( "Set event queue debug level to {0} in {1}", DebugLevel, m_scene.Name); } } private void HandleDebugAttachmentsThrottle(string module, string[] args) { int ms; if (args.Length == 4 && int.TryParse(args[3], out ms)) { ThrottlePer100PrimsRezzed = ms; MainConsole.Instance.OutputFormat( "Attachments rez throttle per 100 prims is now {0} in {1}", ThrottlePer100PrimsRezzed, m_scene.Name); return; } MainConsole.Instance.OutputFormat("Usage: debug attachments throttle <ms>"); } private void HandleDebugAttachmentsStatus(string module, string[] args) { MainConsole.Instance.OutputFormat("Settings for {0}", m_scene.Name); MainConsole.Instance.OutputFormat("Debug logging level: {0}", DebugLevel); MainConsole.Instance.OutputFormat("Throttle per 100 prims: {0}ms", ThrottlePer100PrimsRezzed); } /// <summary> /// Listen for client triggered running state changes so that we can persist the script's object if necessary. /// </summary> /// <param name='localID'></param> /// <param name='itemID'></param> private void HandleScriptStateChange(uint localID, bool started) { SceneObjectGroup sog = m_scene.GetGroupByPrim(localID); if (sog != null && sog.IsAttachment) { if (!started) { // FIXME: This is a convoluted way for working out whether the script state has changed to stop // because it has been manually stopped or because the stop was called in UpdateDetachedObject() below // This needs to be handled in a less tangled way. ScenePresence sp = m_scene.GetScenePresence(sog.AttachedAvatar); if (sp.ControllingClient.IsActive) sog.HasGroupChanged = true; } else { sog.HasGroupChanged = true; } } } public void RemoveRegion(Scene scene) { m_scene.UnregisterModuleInterface<IAttachmentsModule>(this); if (Enabled) m_scene.EventManager.OnNewClient -= SubscribeToClientEvents; } public void RegionLoaded(Scene scene) { m_invAccessModule = m_scene.RequestModuleInterface<IInventoryAccessModule>(); } public void Close() { RemoveRegion(m_scene); } #endregion #region IAttachmentsModule public void CopyAttachments(IScenePresence sp, AgentData ad) { lock (sp.AttachmentsSyncLock) { // Attachment objects List<SceneObjectGroup> attachments = sp.GetAttachments(); if (attachments.Count > 0) { ad.AttachmentObjects = new List<ISceneObject>(); ad.AttachmentObjectStates = new List<string>(); // IScriptModule se = m_scene.RequestModuleInterface<IScriptModule>(); sp.InTransitScriptStates.Clear(); foreach (SceneObjectGroup sog in attachments) { // We need to make a copy and pass that copy // because of transfers withn the same sim ISceneObject clone = sog.CloneForNewScene(); // Attachment module assumes that GroupPosition holds the offsets...! ((SceneObjectGroup)clone).RootPart.GroupPosition = sog.RootPart.AttachedPos; ((SceneObjectGroup)clone).IsAttachment = false; ad.AttachmentObjects.Add(clone); string state = sog.GetStateSnapshot(); ad.AttachmentObjectStates.Add(state); sp.InTransitScriptStates.Add(state); // Let's remove the scripts of the original object here sog.RemoveScriptInstances(true); } } } } public void CopyAttachments(AgentData ad, IScenePresence sp) { if (ad.AttachmentObjects != null && ad.AttachmentObjects.Count > 0) { lock (sp.AttachmentsSyncLock) sp.ClearAttachments(); int i = 0; foreach (ISceneObject so in ad.AttachmentObjects) { ((SceneObjectGroup)so).LocalId = 0; ((SceneObjectGroup)so).RootPart.ClearUpdateSchedule(); so.SetState(ad.AttachmentObjectStates[i++], m_scene); m_scene.IncomingCreateObject(Vector3.Zero, so); } } } public void RezAttachments(IScenePresence sp) { if (!Enabled) return; if (null == sp.Appearance) { m_log.WarnFormat("[ATTACHMENTS MODULE]: Appearance has not been initialized for agent {0}", sp.UUID); return; } if (sp.GetAttachments().Count > 0) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Not doing simulator-side attachment rez for {0} in {1} as their viewer has already rezzed attachments", m_scene.Name, sp.Name); return; } if (DebugLevel > 0) m_log.DebugFormat("[ATTACHMENTS MODULE]: Rezzing any attachments for {0} from simulator-side", sp.Name); List<AvatarAttachment> attachments = sp.Appearance.GetAttachments(); foreach (AvatarAttachment attach in attachments) { uint attachmentPt = (uint)attach.AttachPoint; // m_log.DebugFormat( // "[ATTACHMENTS MODULE]: Doing initial rez of attachment with itemID {0}, assetID {1}, point {2} for {3} in {4}", // attach.ItemID, attach.AssetID, p, sp.Name, m_scene.RegionInfo.RegionName); // For some reason assetIDs are being written as Zero's in the DB -- need to track tat down // But they're not used anyway, the item is being looked up for now, so let's proceed. //if (UUID.Zero == assetID) //{ // m_log.DebugFormat("[ATTACHMENT]: Cannot rez attachment in point {0} with itemID {1}", p, itemID); // continue; //} try { // If we're an NPC then skip all the item checks and manipulations since we don't have an // inventory right now. RezSingleAttachmentFromInventoryInternal( sp, sp.PresenceType == PresenceType.Npc ? UUID.Zero : attach.ItemID, attach.AssetID, attachmentPt, true); } catch (Exception e) { UUID agentId = (sp.ControllingClient == null) ? default(UUID) : sp.ControllingClient.AgentId; m_log.ErrorFormat("[ATTACHMENTS MODULE]: Unable to rez attachment with itemID {0}, assetID {1}, point {2} for {3}: {4}\n{5}", attach.ItemID, attach.AssetID, attachmentPt, agentId, e.Message, e.StackTrace); } } } public void DeRezAttachments(IScenePresence sp) { if (!Enabled) return; if (DebugLevel > 0) m_log.DebugFormat("[ATTACHMENTS MODULE]: Saving changed attachments for {0}", sp.Name); List<SceneObjectGroup> attachments = sp.GetAttachments(); if (attachments.Count <= 0) return; Dictionary<SceneObjectGroup, string> scriptStates = new Dictionary<SceneObjectGroup, string>(); foreach (SceneObjectGroup so in attachments) { // Scripts MUST be snapshotted before the object is // removed from the scene because doing otherwise will // clobber the run flag // This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from // scripts performing attachment operations at the same time. Getting object states stops the scripts. scriptStates[so] = PrepareScriptInstanceForSave(so, false); } lock (sp.AttachmentsSyncLock) { foreach (SceneObjectGroup so in attachments) UpdateDetachedObject(sp, so, scriptStates[so]); sp.ClearAttachments(); } } public void DeleteAttachmentsFromScene(IScenePresence sp, bool silent) { if (!Enabled) return; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Deleting attachments from scene {0} for {1}, silent = {2}", m_scene.RegionInfo.RegionName, sp.Name, silent); foreach (SceneObjectGroup sop in sp.GetAttachments()) { sop.Scene.DeleteSceneObject(sop, silent); } sp.ClearAttachments(); } public bool AttachObject( IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool append) { if (!Enabled) return false; return AttachObjectInternal(sp, group, attachmentPt, silent, addToInventory, false, append); } /// <summary> /// Internal method which actually does all the work for attaching an object. /// </summary> /// <returns>The object attached.</returns> /// <param name='sp'></param> /// <param name='group'>The object to attach.</param> /// <param name='attachmentPt'></param> /// <param name='silent'></param> /// <param name='addToInventory'>If true then add object to user inventory.</param> /// <param name='resumeScripts'>If true then scripts are resumed on the attached object.</param> /// <param name='append'>Append to attachment point rather than replace.</param> private bool AttachObjectInternal( IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool resumeScripts, bool append) { if (group.GetSittingAvatarsCount() != 0) { if (DebugLevel > 0) m_log.WarnFormat( "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since {4} avatars are still sitting on it", group.Name, group.LocalId, sp.Name, attachmentPt, group.GetSittingAvatarsCount()); return false; } Vector3 attachPos = group.AbsolutePosition; // If the attachment point isn't the same as the one previously used // set it's offset position = 0 so that it appears on the attachment point // and not in a weird location somewhere unknown. if (attachmentPt != (uint)AttachmentPoint.Default && attachmentPt != group.AttachmentPoint) { attachPos = Vector3.Zero; } // if the attachment point is the same as previous, make sure we get the saved // position info. if (attachmentPt != 0 && attachmentPt == group.RootPart.Shape.LastAttachPoint) { attachPos = group.RootPart.AttachedPos; } // AttachmentPt 0 means the client chose to 'wear' the attachment. if (attachmentPt == (uint)AttachmentPoint.Default) { // Check object for stored attachment point attachmentPt = group.AttachmentPoint; } // if we didn't find an attach point, look for where it was last attached if (attachmentPt == 0) { attachmentPt = (uint)group.RootPart.Shape.LastAttachPoint; attachPos = group.RootPart.AttachedPos; group.HasGroupChanged = true; } // if we still didn't find a suitable attachment point....... if (attachmentPt == 0) { // Stick it on left hand with Zero Offset from the attachment point. attachmentPt = (uint)AttachmentPoint.LeftHand; attachPos = Vector3.Zero; } group.AttachmentPoint = attachmentPt; group.AbsolutePosition = attachPos; List<SceneObjectGroup> attachments = sp.GetAttachments(attachmentPt); if (attachments.Contains(group)) { if (DebugLevel > 0) m_log.WarnFormat( "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since it's already attached", group.Name, group.LocalId, sp.Name, attachmentPt); return false; } // If we already have 5, remove the oldest until only 4 are left. Skip over temp ones while (attachments.Count >= 5) { if (attachments[0].FromItemID != UUID.Zero) DetachSingleAttachmentToInv(sp, attachments[0]); attachments.RemoveAt(0); } // If we're not appending, remove the rest as well if (attachments.Count != 0 && !append) { foreach (SceneObjectGroup g in attachments) { if (g.FromItemID != UUID.Zero) DetachSingleAttachmentToInv(sp, g); } } lock (sp.AttachmentsSyncLock) { if (addToInventory && sp.PresenceType != PresenceType.Npc) UpdateUserInventoryWithAttachment(sp, group, attachmentPt, append); AttachToAgent(sp, group, attachmentPt, attachPos, silent); if (resumeScripts) { // Fire after attach, so we don't get messy perms dialogs // 4 == AttachedRez group.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 4); group.ResumeScripts(); } // Do this last so that event listeners have access to all the effects of the attachment m_scene.EventManager.TriggerOnAttach(group.LocalId, group.FromItemID, sp.UUID); } return true; } private void UpdateUserInventoryWithAttachment(IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool append) { // Add the new attachment to inventory if we don't already have it. UUID newAttachmentItemID = group.FromItemID; if (newAttachmentItemID == UUID.Zero) newAttachmentItemID = AddSceneObjectAsNewAttachmentInInv(sp, group).ID; ShowAttachInUserInventory(sp, attachmentPt, newAttachmentItemID, group, append); } public SceneObjectGroup RezSingleAttachmentFromInventory(IScenePresence sp, UUID itemID, uint AttachmentPt) { if (!Enabled) return null; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: RezSingleAttachmentFromInventory to point {0} from item {1} for {2} in {3}", (AttachmentPoint)AttachmentPt, itemID, sp.Name, m_scene.Name); // We check the attachments in the avatar appearance here rather than the objects attached to the // ScenePresence itself so that we can ignore calls by viewer 2/3 to attach objects on startup. We are // already doing this in ScenePresence.MakeRootAgent(). Simulator-side attaching needs to be done // because pre-outfit folder viewers (most version 1 viewers) require it. bool alreadyOn = false; List<AvatarAttachment> existingAttachments = sp.Appearance.GetAttachments(); foreach (AvatarAttachment existingAttachment in existingAttachments) { if (existingAttachment.ItemID == itemID) { alreadyOn = true; break; } } if (alreadyOn) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Ignoring request by {0} to wear item {1} at {2} since it is already worn", sp.Name, itemID, AttachmentPt); return null; } bool append = (AttachmentPt & 0x80) != 0; AttachmentPt &= 0x7f; return RezSingleAttachmentFromInventoryInternal(sp, itemID, UUID.Zero, AttachmentPt, append); } public void RezMultipleAttachmentsFromInventory(IScenePresence sp, List<KeyValuePair<UUID, uint>> rezlist) { if (!Enabled) return; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Rezzing {0} attachments from inventory for {1} in {2}", rezlist.Count, sp.Name, m_scene.Name); foreach (KeyValuePair<UUID, uint> rez in rezlist) { RezSingleAttachmentFromInventory(sp, rez.Key, rez.Value); } } public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId) { DetachSingleAttachmentToGround(sp, soLocalId, sp.AbsolutePosition, Quaternion.Identity); } public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId, Vector3 absolutePos, Quaternion absoluteRot) { if (!Enabled) return; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: DetachSingleAttachmentToGround() for {0}, object {1}", sp.UUID, soLocalId); SceneObjectGroup so = m_scene.GetGroupByPrim(soLocalId); if (so == null) return; if (so.AttachedAvatar != sp.UUID) return; UUID inventoryID = so.FromItemID; // As per Linden spec, drop is disabled for temp attachs if (inventoryID == UUID.Zero) return; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: In DetachSingleAttachmentToGround(), object is {0} {1}, associated item is {2}", so.Name, so.LocalId, inventoryID); lock (sp.AttachmentsSyncLock) { if (!m_scene.Permissions.CanRezObject( so.PrimCount, sp.UUID, sp.AbsolutePosition)) return; bool changed = false; if (inventoryID != UUID.Zero) changed = sp.Appearance.DetachAttachment(inventoryID); if (changed && m_scene.AvatarFactory != null) m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID); sp.RemoveAttachment(so); so.FromItemID = UUID.Zero; SceneObjectPart rootPart = so.RootPart; so.AbsolutePosition = absolutePos; if (absoluteRot != Quaternion.Identity) { so.UpdateGroupRotationR(absoluteRot); } so.AttachedAvatar = UUID.Zero; rootPart.SetParentLocalId(0); so.ClearPartAttachmentData(); rootPart.ApplyPhysics(rootPart.GetEffectiveObjectFlags(), rootPart.VolumeDetectActive); so.HasGroupChanged = true; so.RootPart.Shape.LastAttachPoint = (byte)so.AttachmentPoint; rootPart.Rezzed = DateTime.Now; rootPart.RemFlag(PrimFlags.TemporaryOnRez); so.AttachToBackup(); m_scene.EventManager.TriggerParcelPrimCountTainted(); rootPart.ScheduleFullUpdate(); rootPart.ClearUndoState(); List<UUID> uuids = new List<UUID>(); uuids.Add(inventoryID); m_scene.InventoryService.DeleteItems(sp.UUID, uuids); sp.ControllingClient.SendRemoveInventoryItem(inventoryID); } m_scene.EventManager.TriggerOnAttach(so.LocalId, so.UUID, UUID.Zero); } public void DetachSingleAttachmentToInv(IScenePresence sp, SceneObjectGroup so) { if (so.AttachedAvatar != sp.UUID) { m_log.WarnFormat( "[ATTACHMENTS MODULE]: Tried to detach object {0} from {1} {2} but attached avatar id was {3} in {4}", so.Name, sp.Name, sp.UUID, so.AttachedAvatar, m_scene.RegionInfo.RegionName); return; } if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Detaching object {0} {1} (FromItemID {2}) for {3} in {4}", so.Name, so.LocalId, so.FromItemID, sp.Name, m_scene.Name); // Scripts MUST be snapshotted before the object is // removed from the scene because doing otherwise will // clobber the run flag // This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from // scripts performing attachment operations at the same time. Getting object states stops the scripts. string scriptedState = PrepareScriptInstanceForSave(so, true); lock (sp.AttachmentsSyncLock) { // Save avatar attachment information // m_log.Debug("[ATTACHMENTS MODULE]: Detaching from UserID: " + sp.UUID + ", ItemID: " + itemID); bool changed = sp.Appearance.DetachAttachment(so.FromItemID); if (changed && m_scene.AvatarFactory != null) m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID); sp.RemoveAttachment(so); UpdateDetachedObject(sp, so, scriptedState); } } public void UpdateAttachmentPosition(SceneObjectGroup sog, Vector3 pos) { if (!Enabled) return; sog.UpdateGroupPosition(pos); sog.HasGroupChanged = true; } #endregion #region AttachmentModule private methods // This is public but is not part of the IAttachmentsModule interface. // RegionCombiner module needs to poke at it to deliver client events. // This breaks the encapsulation of the module and should get fixed somehow. public void SubscribeToClientEvents(IClientAPI client) { client.OnRezSingleAttachmentFromInv += Client_OnRezSingleAttachmentFromInv; client.OnRezMultipleAttachmentsFromInv += Client_OnRezMultipleAttachmentsFromInv; client.OnObjectAttach += Client_OnObjectAttach; client.OnObjectDetach += Client_OnObjectDetach; client.OnDetachAttachmentIntoInv += Client_OnDetachAttachmentIntoInv; client.OnObjectDrop += Client_OnObjectDrop; } // This is public but is not part of the IAttachmentsModule interface. // RegionCombiner module needs to poke at it to deliver client events. // This breaks the encapsulation of the module and should get fixed somehow. public void UnsubscribeFromClientEvents(IClientAPI client) { client.OnRezSingleAttachmentFromInv -= Client_OnRezSingleAttachmentFromInv; client.OnRezMultipleAttachmentsFromInv -= Client_OnRezMultipleAttachmentsFromInv; client.OnObjectAttach -= Client_OnObjectAttach; client.OnObjectDetach -= Client_OnObjectDetach; client.OnDetachAttachmentIntoInv -= Client_OnDetachAttachmentIntoInv; client.OnObjectDrop -= Client_OnObjectDrop; } /// <summary> /// Update the attachment asset for the new sog details if they have changed. /// </summary> /// <remarks> /// This is essential for preserving attachment attributes such as permission. Unlike normal scene objects, /// these details are not stored on the region. /// </remarks> /// <param name="sp"></param> /// <param name="grp"></param> /// <param name="saveAllScripted"></param> private void UpdateKnownItem(IScenePresence sp, SceneObjectGroup grp, string scriptedState) { if (grp.FromItemID == UUID.Zero) { // We can't save temp attachments grp.HasGroupChanged = false; return; } // Saving attachments for NPCs messes them up for the real owner! INPCModule module = m_scene.RequestModuleInterface<INPCModule>(); if (module != null) { if (module.IsNPC(sp.UUID, m_scene)) return; } if (grp.HasGroupChanged) { m_log.DebugFormat( "[ATTACHMENTS MODULE]: Updating asset for attachment {0}, attachpoint {1}", grp.UUID, grp.AttachmentPoint); string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp, scriptedState); InventoryItemBase item = new InventoryItemBase(grp.FromItemID, sp.UUID); item = m_scene.InventoryService.GetItem(item); if (item != null) { AssetBase asset = m_scene.CreateAsset( grp.GetPartName(grp.LocalId), grp.GetPartDescription(grp.LocalId), (sbyte)AssetType.Object, Utils.StringToBytes(sceneObjectXml), sp.UUID); m_scene.AssetService.Store(asset); item.AssetID = asset.FullID; item.Description = asset.Description; item.Name = asset.Name; item.AssetType = asset.Type; item.InvType = (int)InventoryType.Object; m_scene.InventoryService.UpdateItem(item); // If the name of the object has been changed whilst attached then we want to update the inventory // item in the viewer. if (sp.ControllingClient != null) sp.ControllingClient.SendInventoryItemCreateUpdate(item, 0); } grp.HasGroupChanged = false; // Prevent it being saved over and over } else if (DebugLevel > 0) { m_log.DebugFormat( "[ATTACHMENTS MODULE]: Don't need to update asset for unchanged attachment {0}, attachpoint {1}", grp.UUID, grp.AttachmentPoint); } } /// <summary> /// Attach this scene object to the given avatar. /// </summary> /// <remarks> /// This isn't publicly available since attachments should always perform the corresponding inventory /// operation (to show the attach in user inventory and update the asset with positional information). /// </remarks> /// <param name="sp"></param> /// <param name="so"></param> /// <param name="attachmentpoint"></param> /// <param name="attachOffset"></param> /// <param name="silent"></param> private void AttachToAgent( IScenePresence sp, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Adding attachment {0} to avatar {1} in pt {2} pos {3} {4}", so.Name, sp.Name, attachmentpoint, attachOffset, so.RootPart.AttachedPos); so.DetachFromBackup(); // Remove from database and parcel prim count m_scene.DeleteFromStorage(so.UUID); m_scene.EventManager.TriggerParcelPrimCountTainted(); so.AttachedAvatar = sp.UUID; if (so.RootPart.PhysActor != null) so.RootPart.RemoveFromPhysics(); so.AbsolutePosition = attachOffset; so.RootPart.AttachedPos = attachOffset; so.IsAttachment = true; so.RootPart.SetParentLocalId(sp.LocalId); so.AttachmentPoint = attachmentpoint; sp.AddAttachment(so); if (!silent) { if (so.HasPrivateAttachmentPoint) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Killing private HUD {0} for avatars other than {1} at attachment point {2}", so.Name, sp.Name, so.AttachmentPoint); // As this scene object can now only be seen by the attaching avatar, tell everybody else in the // scene that it's no longer in their awareness. m_scene.ForEachClient( client => { if (client.AgentId != so.AttachedAvatar) client.SendKillObject(new List<uint>() { so.LocalId }); }); } // Fudge below is an extremely unhelpful comment. It's probably here so that the scheduled full update // will succeed, as that will not update if an attachment is selected. so.IsSelected = false; // fudge.... so.ScheduleGroupForFullUpdate(); } // In case it is later dropped again, don't let // it get cleaned up so.RootPart.RemFlag(PrimFlags.TemporaryOnRez); } /// <summary> /// Add a scene object as a new attachment in the user inventory. /// </summary> /// <param name="remoteClient"></param> /// <param name="grp"></param> /// <returns>The user inventory item created that holds the attachment.</returns> private InventoryItemBase AddSceneObjectAsNewAttachmentInInv(IScenePresence sp, SceneObjectGroup grp) { if (m_invAccessModule == null) return null; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Called AddSceneObjectAsAttachment for object {0} {1} for {2}", grp.Name, grp.LocalId, sp.Name); InventoryItemBase newItem = m_invAccessModule.CopyToInventory( DeRezAction.TakeCopy, m_scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object).ID, new List<SceneObjectGroup> { grp }, sp.ControllingClient, true)[0]; // sets itemID so client can show item as 'attached' in inventory grp.FromItemID = newItem.ID; return newItem; } /// <summary> /// Prepares the script instance for save. /// </summary> /// <remarks> /// This involves triggering the detach event and getting the script state (which also stops the script) /// This MUST be done outside sp.AttachmentsSyncLock, since otherwise there is a chance of deadlock if a /// running script is performing attachment operations. /// </remarks> /// <returns> /// The script state ready for persistence. /// </returns> /// <param name='grp'> /// </param> /// <param name='fireDetachEvent'> /// If true, then fire the script event before we save its state. /// </param> private string PrepareScriptInstanceForSave(SceneObjectGroup grp, bool fireDetachEvent) { if (fireDetachEvent) m_scene.EventManager.TriggerOnAttach(grp.LocalId, grp.FromItemID, UUID.Zero); using (StringWriter sw = new StringWriter()) { using (XmlTextWriter writer = new XmlTextWriter(sw)) { grp.SaveScriptedState(writer); } return sw.ToString(); } } private void UpdateDetachedObject(IScenePresence sp, SceneObjectGroup so, string scriptedState) { // Don't save attachments for HG visitors, it // messes up their inventory. When a HG visitor logs // out on a foreign grid, their attachments will be // reloaded in the state they were in when they left // the home grid. This is best anyway as the visited // grid may use an incompatible script engine. bool saveChanged = sp.PresenceType != PresenceType.Npc && (m_scene.UserManagementModule == null || m_scene.UserManagementModule.IsLocalGridUser(sp.UUID)); // Remove the object from the scene so no more updates // are sent. Doing this before the below changes will ensure // updates can't cause "HUD artefacts" m_scene.DeleteSceneObject(so, false, false); // Prepare sog for storage so.AttachedAvatar = UUID.Zero; so.RootPart.SetParentLocalId(0); so.IsAttachment = false; if (saveChanged) { // We cannot use AbsolutePosition here because that would // attempt to cross the prim as it is detached so.ForEachPart(x => { x.GroupPosition = so.RootPart.AttachedPos; }); UpdateKnownItem(sp, so, scriptedState); } // Now, remove the scripts so.RemoveScriptInstances(true); } protected SceneObjectGroup RezSingleAttachmentFromInventoryInternal( IScenePresence sp, UUID itemID, UUID assetID, uint attachmentPt, bool append) { if (m_invAccessModule == null) return null; SceneObjectGroup objatt; if (itemID != UUID.Zero) objatt = m_invAccessModule.RezObject(sp.ControllingClient, itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true, false, false, sp.UUID, true); else objatt = m_invAccessModule.RezObject(sp.ControllingClient, null, assetID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true, false, false, sp.UUID, true); if (objatt == null) { m_log.WarnFormat( "[ATTACHMENTS MODULE]: Could not retrieve item {0} for attaching to avatar {1} at point {2}", itemID, sp.Name, attachmentPt); return null; } if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Rezzed single object {0} with {1} prims for attachment to {2} on point {3} in {4}", objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name); // HasGroupChanged is being set from within RezObject. Ideally it would be set by the caller. objatt.HasGroupChanged = false; bool tainted = false; if (attachmentPt != 0 && attachmentPt != objatt.AttachmentPoint) tainted = true; // FIXME: Detect whether it's really likely for AttachObject to throw an exception in the normal // course of events. If not, then it's probably not worth trying to recover the situation // since this is more likely to trigger further exceptions and confuse later debugging. If // exceptions can be thrown in expected error conditions (not NREs) then make this consistent // since other normal error conditions will simply return false instead. // This will throw if the attachment fails try { AttachObjectInternal(sp, objatt, attachmentPt, false, true, true, append); } catch (Exception e) { m_log.ErrorFormat( "[ATTACHMENTS MODULE]: Failed to attach {0} {1} for {2}, exception {3}{4}", objatt.Name, objatt.UUID, sp.Name, e.Message, e.StackTrace); // Make sure the object doesn't stick around and bail sp.RemoveAttachment(objatt); m_scene.DeleteSceneObject(objatt, false); return null; } if (tainted) objatt.HasGroupChanged = true; if (ThrottlePer100PrimsRezzed > 0) { int throttleMs = (int)Math.Round((float)objatt.PrimCount / 100 * ThrottlePer100PrimsRezzed); if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Throttling by {0}ms after rez of {1} with {2} prims for attachment to {3} on point {4} in {5}", throttleMs, objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name); Thread.Sleep(throttleMs); } return objatt; } /// <summary> /// Update the user inventory to reflect an attachment /// </summary> /// <param name="sp"></param> /// <param name="AttachmentPt"></param> /// <param name="itemID"></param> /// <param name="att"></param> private void ShowAttachInUserInventory(IScenePresence sp, uint AttachmentPt, UUID itemID, SceneObjectGroup att, bool append) { // m_log.DebugFormat( // "[USER INVENTORY]: Updating attachment {0} for {1} at {2} using item ID {3}", // att.Name, sp.Name, AttachmentPt, itemID); if (UUID.Zero == itemID) { m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error inventory item ID."); return; } if (0 == AttachmentPt) { m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error attachment point."); return; } InventoryItemBase item = new InventoryItemBase(itemID, sp.UUID); item = m_scene.InventoryService.GetItem(item); if (item == null) return; int attFlag = append ? 0x80 : 0; bool changed = sp.Appearance.SetAttachment((int)AttachmentPt | attFlag, itemID, item.AssetID); if (changed && m_scene.AvatarFactory != null) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Queueing appearance save for {0}, attachment {1} point {2} in ShowAttachInUserInventory()", sp.Name, att.Name, AttachmentPt); m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID); } } #endregion #region Client Event Handlers private ISceneEntity Client_OnRezSingleAttachmentFromInv(IClientAPI remoteClient, UUID itemID, uint AttachmentPt) { if (!Enabled) return null; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Rezzing attachment to point {0} from item {1} for {2}", (AttachmentPoint)AttachmentPt, itemID, remoteClient.Name); ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId); if (sp == null) { m_log.ErrorFormat( "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezSingleAttachmentFromInventory()", remoteClient.Name, remoteClient.AgentId); return null; } return RezSingleAttachmentFromInventory(sp, itemID, AttachmentPt); } private void Client_OnRezMultipleAttachmentsFromInv(IClientAPI remoteClient, List<KeyValuePair<UUID, uint>> rezlist) { if (!Enabled) return; ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId); if (sp != null) RezMultipleAttachmentsFromInventory(sp, rezlist); else m_log.ErrorFormat( "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezMultipleAttachmentsFromInventory()", remoteClient.Name, remoteClient.AgentId); } private void Client_OnObjectAttach(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, bool silent) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Attaching object local id {0} to {1} point {2} from ground (silent = {3})", objectLocalID, remoteClient.Name, AttachmentPt, silent); if (!Enabled) return; try { ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId); if (sp == null) { m_log.ErrorFormat( "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1}", remoteClient.Name, remoteClient.AgentId); return; } // If we can't take it, we can't attach it! SceneObjectPart part = m_scene.GetSceneObjectPart(objectLocalID); if (part == null) return; if (!m_scene.Permissions.CanTakeObject(part.UUID, remoteClient.AgentId)) { remoteClient.SendAgentAlertMessage( "You don't have sufficient permissions to attach this object", false); return; } bool append = (AttachmentPt & 0x80) != 0; AttachmentPt &= 0x7f; // Calls attach with a Zero position if (AttachObject(sp, part.ParentGroup, AttachmentPt, false, true, append)) { if (DebugLevel > 0) m_log.Debug( "[ATTACHMENTS MODULE]: Saving avatar attachment. AgentID: " + remoteClient.AgentId + ", AttachmentPoint: " + AttachmentPt); // Save avatar attachment information m_scene.EventManager.TriggerOnAttach(objectLocalID, part.ParentGroup.FromItemID, remoteClient.AgentId); } } catch (Exception e) { m_log.ErrorFormat("[ATTACHMENTS MODULE]: exception upon Attach Object {0}{1}", e.Message, e.StackTrace); } } private void Client_OnObjectDetach(uint objectLocalID, IClientAPI remoteClient) { if (!Enabled) return; ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId); SceneObjectGroup group = m_scene.GetGroupByPrim(objectLocalID); if (sp != null && group != null && group.FromItemID != UUID.Zero) DetachSingleAttachmentToInv(sp, group); } private void Client_OnDetachAttachmentIntoInv(UUID itemID, IClientAPI remoteClient) { if (!Enabled) return; ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId); if (sp != null) { List<SceneObjectGroup> attachments = sp.GetAttachments(); foreach (SceneObjectGroup group in attachments) { if (group.FromItemID == itemID && group.FromItemID != UUID.Zero) { DetachSingleAttachmentToInv(sp, group); return; } } } } private void Client_OnObjectDrop(uint soLocalId, IClientAPI remoteClient) { if (!Enabled) return; ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId); if (sp != null) DetachSingleAttachmentToGround(sp, soLocalId); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; namespace ClosedXML.Excel { internal class XLPageSetup : IXLPageSetup { public XLPageSetup(XLPageSetup defaultPageOptions, XLWorksheet worksheet) { if (defaultPageOptions != null) { PrintAreas = new XLPrintAreas(defaultPageOptions.PrintAreas as XLPrintAreas, worksheet); CenterHorizontally = defaultPageOptions.CenterHorizontally; CenterVertically = defaultPageOptions.CenterVertically; FirstPageNumber = defaultPageOptions.FirstPageNumber; HorizontalDpi = defaultPageOptions.HorizontalDpi; PageOrientation = defaultPageOptions.PageOrientation; VerticalDpi = defaultPageOptions.VerticalDpi; FirstRowToRepeatAtTop = defaultPageOptions.FirstRowToRepeatAtTop; LastRowToRepeatAtTop = defaultPageOptions.LastRowToRepeatAtTop; FirstColumnToRepeatAtLeft = defaultPageOptions.FirstColumnToRepeatAtLeft; LastColumnToRepeatAtLeft = defaultPageOptions.LastColumnToRepeatAtLeft; ShowComments = defaultPageOptions.ShowComments; PaperSize = defaultPageOptions.PaperSize; _pagesTall = defaultPageOptions.PagesTall; _pagesWide = defaultPageOptions.PagesWide; _scale = defaultPageOptions.Scale; if (defaultPageOptions.Margins != null) { Margins = new XLMargins { Top = defaultPageOptions.Margins.Top, Bottom = defaultPageOptions.Margins.Bottom, Left = defaultPageOptions.Margins.Left, Right = defaultPageOptions.Margins.Right, Header = defaultPageOptions.Margins.Header, Footer = defaultPageOptions.Margins.Footer }; } AlignHFWithMargins = defaultPageOptions.AlignHFWithMargins; ScaleHFWithDocument = defaultPageOptions.ScaleHFWithDocument; ShowGridlines = defaultPageOptions.ShowGridlines; ShowRowAndColumnHeadings = defaultPageOptions.ShowRowAndColumnHeadings; BlackAndWhite = defaultPageOptions.BlackAndWhite; DraftQuality = defaultPageOptions.DraftQuality; PageOrder = defaultPageOptions.PageOrder; ColumnBreaks = defaultPageOptions.ColumnBreaks.ToList(); RowBreaks = defaultPageOptions.RowBreaks.ToList(); Header = new XLHeaderFooter(defaultPageOptions.Header as XLHeaderFooter, worksheet); Footer = new XLHeaderFooter(defaultPageOptions.Footer as XLHeaderFooter, worksheet); PrintErrorValue = defaultPageOptions.PrintErrorValue; } else { PrintAreas = new XLPrintAreas(worksheet); Header = new XLHeaderFooter(worksheet); Footer = new XLHeaderFooter(worksheet); ColumnBreaks = new List<Int32>(); RowBreaks = new List<Int32>(); } } public IXLPrintAreas PrintAreas { get; private set; } public Int32 FirstRowToRepeatAtTop { get; private set; } public Int32 LastRowToRepeatAtTop { get; private set; } public void SetRowsToRepeatAtTop(String range) { var arrRange = range.Replace("$", "").Split(':'); SetRowsToRepeatAtTop(Int32.Parse(arrRange[0]), Int32.Parse(arrRange[1])); } public void SetRowsToRepeatAtTop(Int32 firstRowToRepeatAtTop, Int32 lastRowToRepeatAtTop) { if (firstRowToRepeatAtTop <= 0) throw new ArgumentOutOfRangeException("The first row has to be greater than zero."); if (firstRowToRepeatAtTop > lastRowToRepeatAtTop) throw new ArgumentOutOfRangeException("The first row has to be less than the second row."); FirstRowToRepeatAtTop = firstRowToRepeatAtTop; LastRowToRepeatAtTop = lastRowToRepeatAtTop; } public Int32 FirstColumnToRepeatAtLeft { get; private set; } public Int32 LastColumnToRepeatAtLeft { get; private set; } public void SetColumnsToRepeatAtLeft(String range) { var arrRange = range.Replace("$", "").Split(':'); if (Int32.TryParse(arrRange[0], out int iTest)) SetColumnsToRepeatAtLeft(Int32.Parse(arrRange[0]), Int32.Parse(arrRange[1])); else SetColumnsToRepeatAtLeft(arrRange[0], arrRange[1]); } public void SetColumnsToRepeatAtLeft(String firstColumnToRepeatAtLeft, String lastColumnToRepeatAtLeft) { SetColumnsToRepeatAtLeft(XLHelper.GetColumnNumberFromLetter(firstColumnToRepeatAtLeft), XLHelper.GetColumnNumberFromLetter(lastColumnToRepeatAtLeft)); } public void SetColumnsToRepeatAtLeft(Int32 firstColumnToRepeatAtLeft, Int32 lastColumnToRepeatAtLeft) { if (firstColumnToRepeatAtLeft <= 0) throw new ArgumentOutOfRangeException("The first column has to be greater than zero."); if (firstColumnToRepeatAtLeft > lastColumnToRepeatAtLeft) throw new ArgumentOutOfRangeException("The first column has to be less than the second column."); FirstColumnToRepeatAtLeft = firstColumnToRepeatAtLeft; LastColumnToRepeatAtLeft = lastColumnToRepeatAtLeft; } public XLPageOrientation PageOrientation { get; set; } public XLPaperSize PaperSize { get; set; } public Int32 HorizontalDpi { get; set; } public Int32 VerticalDpi { get; set; } public Int64 FirstPageNumber { get; set; } public Boolean CenterHorizontally { get; set; } public Boolean CenterVertically { get; set; } public XLPrintErrorValues PrintErrorValue { get; set; } public IXLMargins Margins { get; set; } private Int32 _pagesWide; public Int32 PagesWide { get { return _pagesWide; } set { _pagesWide = value; if (_pagesWide >0) _scale = 0; } } private Int32 _pagesTall; public Int32 PagesTall { get { return _pagesTall; } set { _pagesTall = value; if (_pagesTall >0) _scale = 0; } } private Int32 _scale; public Int32 Scale { get { return _scale; } set { _scale = value; if (_scale <= 0) return; _pagesTall = 0; _pagesWide = 0; } } public void AdjustTo(Int32 percentageOfNormalSize) { Scale = percentageOfNormalSize; _pagesWide = 0; _pagesTall = 0; } public void FitToPages(Int32 pagesWide, Int32 pagesTall) { _pagesWide = pagesWide; this._pagesTall = pagesTall; _scale = 0; } public IXLHeaderFooter Header { get; private set; } public IXLHeaderFooter Footer { get; private set; } public Boolean ScaleHFWithDocument { get; set; } public Boolean AlignHFWithMargins { get; set; } public Boolean ShowGridlines { get; set; } public Boolean ShowRowAndColumnHeadings { get; set; } public Boolean BlackAndWhite { get; set; } public Boolean DraftQuality { get; set; } public XLPageOrderValues PageOrder { get; set; } public XLShowCommentsValues ShowComments { get; set; } public List<Int32> RowBreaks { get; private set; } public List<Int32> ColumnBreaks { get; private set; } public void AddHorizontalPageBreak(Int32 row) { if (!RowBreaks.Contains(row)) RowBreaks.Add(row); RowBreaks.Sort(); } public void AddVerticalPageBreak(Int32 column) { if (!ColumnBreaks.Contains(column)) ColumnBreaks.Add(column); ColumnBreaks.Sort(); } //public void SetPageBreak(IXLRange range, XLPageBreakLocations breakLocation) //{ // switch (breakLocation) // { // case XLPageBreakLocations.AboveRange: RowBreaks.Add(range.Internals.Worksheet.Row(range.RowNumber)); break; // case XLPageBreakLocations.BelowRange: RowBreaks.Add(range.Internals.Worksheet.Row(range.RowCount())); break; // case XLPageBreakLocations.LeftOfRange: ColumnBreaks.Add(range.Internals.Worksheet.Column(range.ColumnNumber)); break; // case XLPageBreakLocations.RightOfRange: ColumnBreaks.Add(range.Internals.Worksheet.Column(range.ColumnCount())); break; // default: throw new NotImplementedException(); // } //} public IXLPageSetup SetPageOrientation(XLPageOrientation value) { PageOrientation = value; return this; } public IXLPageSetup SetPagesWide(Int32 value) { PagesWide = value; return this; } public IXLPageSetup SetPagesTall(Int32 value) { PagesTall = value; return this; } public IXLPageSetup SetScale(Int32 value) { Scale = value; return this; } public IXLPageSetup SetHorizontalDpi(Int32 value) { HorizontalDpi = value; return this; } public IXLPageSetup SetVerticalDpi(Int32 value) { VerticalDpi = value; return this; } public IXLPageSetup SetFirstPageNumber(Int64 value) { FirstPageNumber = value; return this; } public IXLPageSetup SetCenterHorizontally() { CenterHorizontally = true; return this; } public IXLPageSetup SetCenterHorizontally(Boolean value) { CenterHorizontally = value; return this; } public IXLPageSetup SetCenterVertically() { CenterVertically = true; return this; } public IXLPageSetup SetCenterVertically(Boolean value) { CenterVertically = value; return this; } public IXLPageSetup SetPaperSize(XLPaperSize value) { PaperSize = value; return this; } public IXLPageSetup SetScaleHFWithDocument() { ScaleHFWithDocument = true; return this; } public IXLPageSetup SetScaleHFWithDocument(Boolean value) { ScaleHFWithDocument = value; return this; } public IXLPageSetup SetAlignHFWithMargins() { AlignHFWithMargins = true; return this; } public IXLPageSetup SetAlignHFWithMargins(Boolean value) { AlignHFWithMargins = value; return this; } public IXLPageSetup SetShowGridlines() { ShowGridlines = true; return this; } public IXLPageSetup SetShowGridlines(Boolean value) { ShowGridlines = value; return this; } public IXLPageSetup SetShowRowAndColumnHeadings() { ShowRowAndColumnHeadings = true; return this; } public IXLPageSetup SetShowRowAndColumnHeadings(Boolean value) { ShowRowAndColumnHeadings = value; return this; } public IXLPageSetup SetBlackAndWhite() { BlackAndWhite = true; return this; } public IXLPageSetup SetBlackAndWhite(Boolean value) { BlackAndWhite = value; return this; } public IXLPageSetup SetDraftQuality() { DraftQuality = true; return this; } public IXLPageSetup SetDraftQuality(Boolean value) { DraftQuality = value; return this; } public IXLPageSetup SetPageOrder(XLPageOrderValues value) { PageOrder = value; return this; } public IXLPageSetup SetShowComments(XLShowCommentsValues value) { ShowComments = value; return this; } public IXLPageSetup SetPrintErrorValue(XLPrintErrorValues value) { PrintErrorValue = value; return this; } public Boolean DifferentFirstPageOnHF { get; set; } public IXLPageSetup SetDifferentFirstPageOnHF() { return SetDifferentFirstPageOnHF(true); } public IXLPageSetup SetDifferentFirstPageOnHF(Boolean value) { DifferentFirstPageOnHF = value; return this; } public Boolean DifferentOddEvenPagesOnHF { get; set; } public IXLPageSetup SetDifferentOddEvenPagesOnHF() { return SetDifferentOddEvenPagesOnHF(true); } public IXLPageSetup SetDifferentOddEvenPagesOnHF(Boolean value) { DifferentOddEvenPagesOnHF = value; return this; } } }
using System; using System.IO; using System.Collections.Generic; using System.Linq; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; namespace IO.Swagger.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IDefaultApi { /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <param name="body"></param> /// <returns>string</returns> string AddDeed (DeedApplication body); /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <param name="body"></param> /// <returns>ApiResponse of string</returns> ApiResponse<string> AddDeedWithHttpInfo (DeedApplication body); /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <param name="body"></param> /// <returns>Task of string</returns> System.Threading.Tasks.Task<string> AddDeedAsync (DeedApplication body); /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <param name="body"></param> /// <returns>Task of ApiResponse (string)</returns> System.Threading.Tasks.Task<ApiResponse<string>> AddDeedAsyncWithHttpInfo (DeedApplication body); } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public class DefaultApi : IDefaultApi { /// <summary> /// Initializes a new instance of the <see cref="DefaultApi"/> class. /// </summary> /// <returns></returns> public DefaultApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); } /// <summary> /// Initializes a new instance of the <see cref="DefaultApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public DefaultApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = 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 'Configuraiton.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> /// 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> /// Deed The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <param name="body"></param> /// <returns>string</returns> public string AddDeed (DeedApplication body) { ApiResponse<string> response = AddDeedWithHttpInfo(body); return response.Data; } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <param name="body"></param> /// <returns>ApiResponse of string</returns> public ApiResponse< string > AddDeedWithHttpInfo (DeedApplication body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling AddDeed"); var path_ = "/deed/"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // to determine the Accept header String[] http_header_accepts = new String[] { "text/plain" }; String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter // make the HTTP request IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); int statusCode = (int) response.StatusCode; if (statusCode >= 400) throw new ApiException (statusCode, "Error calling AddDeed: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException (statusCode, "Error calling AddDeed: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<string>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string) Configuration.ApiClient.Deserialize(response, typeof(string))); } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <param name="body"></param> /// <returns>Task of string</returns> public async System.Threading.Tasks.Task<string> AddDeedAsync (DeedApplication body) { ApiResponse<string> response = await AddDeedAsyncWithHttpInfo(body); return response.Data; } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <param name="body"></param> /// <returns>Task of ApiResponse (string)</returns> public async System.Threading.Tasks.Task<ApiResponse<string>> AddDeedAsyncWithHttpInfo (DeedApplication body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling AddDeed"); var path_ = "/deed/"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // to determine the Accept header String[] http_header_accepts = new String[] { "text/plain" }; String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter // make the HTTP request IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); int statusCode = (int) response.StatusCode; if (statusCode >= 400) throw new ApiException (statusCode, "Error calling AddDeed: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException (statusCode, "Error calling AddDeed: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<string>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string) Configuration.ApiClient.Deserialize(response, typeof(string))); } } }
using System; using System.Collections.Generic; using System.Data; using Examine; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Cms.Core.Routing; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Web; using Umbraco.Cms.Web.Common.DependencyInjection; namespace Umbraco.Extensions { public static class FriendlyPublishedContentExtensions { private static IVariationContextAccessor VariationContextAccessor { get; } = StaticServiceProvider.Instance.GetRequiredService<IVariationContextAccessor>(); private static IPublishedModelFactory PublishedModelFactory { get; } = StaticServiceProvider.Instance.GetRequiredService<IPublishedModelFactory>(); private static IPublishedUrlProvider PublishedUrlProvider { get; } = StaticServiceProvider.Instance.GetRequiredService<IPublishedUrlProvider>(); private static IUserService UserService { get; } = StaticServiceProvider.Instance.GetRequiredService<IUserService>(); private static IUmbracoContextAccessor UmbracoContextAccessor { get; } = StaticServiceProvider.Instance.GetRequiredService<IUmbracoContextAccessor>(); private static ISiteDomainMapper SiteDomainHelper { get; } = StaticServiceProvider.Instance.GetRequiredService<ISiteDomainMapper>(); private static IExamineManager ExamineManager { get; } = StaticServiceProvider.Instance.GetRequiredService<IExamineManager>(); private static IFileService FileService { get; } = StaticServiceProvider.Instance.GetRequiredService<IFileService>(); private static IOptions<WebRoutingSettings> WebRoutingSettings { get; } = StaticServiceProvider.Instance.GetRequiredService<IOptions<WebRoutingSettings>>(); private static IContentTypeService ContentTypeService { get; } = StaticServiceProvider.Instance.GetRequiredService<IContentTypeService>(); private static IPublishedValueFallback PublishedValueFallback { get; } = StaticServiceProvider.Instance.GetRequiredService<IPublishedValueFallback>(); private static IPublishedSnapshot PublishedSnapshot { get { if (!UmbracoContextAccessor.TryGetUmbracoContext(out var umbracoContext)) { return null; } return umbracoContext.PublishedSnapshot; } } private static IMediaTypeService MediaTypeService { get; } = StaticServiceProvider.Instance.GetRequiredService<IMediaTypeService>(); private static IMemberTypeService MemberTypeService { get; } = StaticServiceProvider.Instance.GetRequiredService<IMemberTypeService>(); /// <summary> /// Creates a strongly typed published content model for an internal published content. /// </summary> /// <param name="content">The internal published content.</param> /// <returns>The strongly typed published content model.</returns> public static IPublishedContent CreateModel( this IPublishedContent content) => content.CreateModel(PublishedModelFactory); /// <summary> /// Gets the name of the content item. /// </summary> /// <param name="content">The content item.</param> /// <param name="culture">The specific culture to get the name for. If null is used the current culture is used (Default is null).</param> public static string Name( this IPublishedContent content, string culture = null) => content.Name(VariationContextAccessor, culture); /// <summary> /// Gets the URL segment of the content item. /// </summary> /// <param name="content">The content item.</param> /// <param name="culture">The specific culture to get the URL segment for. If null is used the current culture is used (Default is null).</param> public static string UrlSegment( this IPublishedContent content, string culture = null) => content.UrlSegment(VariationContextAccessor, culture); /// <summary> /// Gets the culture date of the content item. /// </summary> /// <param name="content">The content item.</param> /// <param name="culture">The specific culture to get the name for. If null is used the current culture is used (Default is null).</param> public static DateTime CultureDate( this IPublishedContent content, string culture = null) => content.CultureDate(VariationContextAccessor, culture); /// <summary> /// Returns the current template Alias /// </summary> /// <returns>Empty string if none is set.</returns> public static string GetTemplateAlias(this IPublishedContent content) => content.GetTemplateAlias(FileService); public static bool IsAllowedTemplate(this IPublishedContent content, int templateId) => content.IsAllowedTemplate(ContentTypeService, WebRoutingSettings.Value, templateId); public static bool IsAllowedTemplate(this IPublishedContent content, string templateAlias) => content.IsAllowedTemplate(WebRoutingSettings.Value.DisableAlternativeTemplates, WebRoutingSettings.Value.ValidateAlternativeTemplates, templateAlias); public static bool IsAllowedTemplate( this IPublishedContent content, bool disableAlternativeTemplates, bool validateAlternativeTemplates, int templateId) => content.IsAllowedTemplate( ContentTypeService, disableAlternativeTemplates, validateAlternativeTemplates, templateId); public static bool IsAllowedTemplate( this IPublishedContent content, bool disableAlternativeTemplates, bool validateAlternativeTemplates, string templateAlias) => content.IsAllowedTemplate( FileService, ContentTypeService, disableAlternativeTemplates, validateAlternativeTemplates, templateAlias); /// <summary> /// Gets a value indicating whether the content has a value for a property identified by its alias. /// </summary> /// <param name="content">The content.</param> /// <param name="alias">The property alias.</param> /// <param name="culture">The variation language.</param> /// <param name="segment">The variation segment.</param> /// <param name="fallback">Optional fallback strategy.</param> /// <returns>A value indicating whether the content has a value for the property identified by the alias.</returns> /// <remarks>Returns true if HasValue is true, or a fallback strategy can provide a value.</remarks> public static bool HasValue( this IPublishedContent content, string alias, string culture = null, string segment = null, Fallback fallback = default) => content.HasValue(PublishedValueFallback, alias, culture, segment, fallback); /// <summary> /// Gets the value of a content's property identified by its alias, if it exists, otherwise a default value. /// </summary> /// <param name="content">The content.</param> /// <param name="alias">The property alias.</param> /// <param name="culture">The variation language.</param> /// <param name="segment">The variation segment.</param> /// <param name="fallback">Optional fallback strategy.</param> /// <param name="defaultValue">The default value.</param> /// <returns>The value of the content's property identified by the alias, if it exists, otherwise a default value.</returns> public static object Value(this IPublishedContent content, string alias, string culture = null, string segment = null, Fallback fallback = default, object defaultValue = default) => content.Value(PublishedValueFallback, alias, culture, segment, fallback, defaultValue); /// <summary> /// Gets the value of a content's property identified by its alias, converted to a specified type. /// </summary> /// <typeparam name="T">The target property type.</typeparam> /// <param name="content">The content.</param> /// <param name="alias">The property alias.</param> /// <param name="culture">The variation language.</param> /// <param name="segment">The variation segment.</param> /// <param name="fallback">Optional fallback strategy.</param> /// <param name="defaultValue">The default value.</param> /// <returns>The value of the content's property identified by the alias, converted to the specified type.</returns> public static T Value<T>(this IPublishedContent content, string alias, string culture = null, string segment = null, Fallback fallback = default, T defaultValue = default) => content.Value<T>(PublishedValueFallback, alias, culture, segment, fallback, defaultValue); /// <summary> /// Returns all DescendantsOrSelf of all content referenced /// </summary> /// <param name="parentNodes"></param> /// <param name="docTypeAlias"></param> /// <param name="culture">The specific culture to filter for. If null is used the current culture is used. (Default is null)</param> /// <returns></returns> /// <remarks> /// This can be useful in order to return all nodes in an entire site by a type when combined with TypedContentAtRoot /// </remarks> public static IEnumerable<IPublishedContent> DescendantsOrSelfOfType( this IEnumerable<IPublishedContent> parentNodes, string docTypeAlias, string culture = null) => parentNodes.DescendantsOrSelfOfType(VariationContextAccessor, docTypeAlias, culture); /// <summary> /// Returns all DescendantsOrSelf of all content referenced /// </summary> /// <param name="parentNodes"></param> /// <param name="variationContextAccessor">Variation context accessor.</param> /// <param name="culture">The specific culture to filter for. If null is used the current culture is used. (Default is null)</param> /// <returns></returns> /// <remarks> /// This can be useful in order to return all nodes in an entire site by a type when combined with TypedContentAtRoot /// </remarks> public static IEnumerable<T> DescendantsOrSelf<T>( this IEnumerable<IPublishedContent> parentNodes, string culture = null) where T : class, IPublishedContent => parentNodes.DescendantsOrSelf<T>(VariationContextAccessor, culture); public static IEnumerable<IPublishedContent> Descendants(this IPublishedContent content, string culture = null) => content.Descendants(VariationContextAccessor, culture); public static IEnumerable<IPublishedContent> Descendants(this IPublishedContent content, int level, string culture = null) => content.Descendants(VariationContextAccessor, level, culture); public static IEnumerable<IPublishedContent> DescendantsOfType(this IPublishedContent content, string contentTypeAlias, string culture = null) => content.DescendantsOfType(VariationContextAccessor, contentTypeAlias, culture); public static IEnumerable<T> Descendants<T>(this IPublishedContent content, string culture = null) where T : class, IPublishedContent => content.Descendants<T>(VariationContextAccessor, culture); public static IEnumerable<T> Descendants<T>(this IPublishedContent content, int level, string culture = null) where T : class, IPublishedContent => content.Descendants<T>(VariationContextAccessor, level, culture); public static IEnumerable<IPublishedContent> DescendantsOrSelf(this IPublishedContent content, string culture = null) => content.DescendantsOrSelf(VariationContextAccessor, culture); public static IEnumerable<IPublishedContent> DescendantsOrSelf(this IPublishedContent content, int level, string culture = null) => content.DescendantsOrSelf(VariationContextAccessor, level, culture); public static IEnumerable<IPublishedContent> DescendantsOrSelfOfType(this IPublishedContent content, string contentTypeAlias, string culture = null) => content.DescendantsOrSelfOfType(VariationContextAccessor, contentTypeAlias, culture); public static IEnumerable<T> DescendantsOrSelf<T>(this IPublishedContent content, string culture = null) where T : class, IPublishedContent => content.DescendantsOrSelf<T>(VariationContextAccessor, culture); public static IEnumerable<T> DescendantsOrSelf<T>(this IPublishedContent content, int level, string culture = null) where T : class, IPublishedContent => content.DescendantsOrSelf<T>(VariationContextAccessor, level, culture); public static IPublishedContent Descendant(this IPublishedContent content, string culture = null) => content.Descendant(VariationContextAccessor, culture); public static IPublishedContent Descendant(this IPublishedContent content, int level, string culture = null) => content.Descendant(VariationContextAccessor, level, culture); public static IPublishedContent DescendantOfType(this IPublishedContent content, string contentTypeAlias, string culture = null) => content.DescendantOfType(VariationContextAccessor, contentTypeAlias, culture); public static T Descendant<T>(this IPublishedContent content, string culture = null) where T : class, IPublishedContent => content.Descendant<T>(VariationContextAccessor, culture); public static T Descendant<T>(this IPublishedContent content, int level, string culture = null) where T : class, IPublishedContent => content.Descendant<T>(VariationContextAccessor, level, culture); public static IPublishedContent DescendantOrSelf(this IPublishedContent content, string culture = null) => content.DescendantOrSelf(VariationContextAccessor, culture); public static IPublishedContent DescendantOrSelf(this IPublishedContent content, int level, string culture = null) => content.DescendantOrSelf(VariationContextAccessor, level, culture); public static IPublishedContent DescendantOrSelfOfType(this IPublishedContent content, string contentTypeAlias, string culture = null) => content.DescendantOrSelfOfType(VariationContextAccessor, contentTypeAlias, culture); public static T DescendantOrSelf<T>(this IPublishedContent content, string culture = null) where T : class, IPublishedContent => content.DescendantOrSelf<T>(VariationContextAccessor, culture); public static T DescendantOrSelf<T>(this IPublishedContent content, int level, string culture = null) where T : class, IPublishedContent => content.DescendantOrSelf<T>(VariationContextAccessor, level, culture); /// <summary> /// Gets the children of the content item. /// </summary> /// <param name="content">The content item.</param> /// <param name="culture"> /// The specific culture to get the URL children for. Default is null which will use the current culture in <see cref="VariationContext"/> /// </param> /// <remarks> /// <para>Gets children that are available for the specified culture.</para> /// <para>Children are sorted by their sortOrder.</para> /// <para> /// For culture, /// if null is used the current culture is used. /// If an empty string is used only invariant children are returned. /// If "*" is used all children are returned. /// </para> /// <para> /// If a variant culture is specified or there is a current culture in the <see cref="VariationContext"/> then the Children returned /// will include both the variant children matching the culture AND the invariant children because the invariant children flow with the current culture. /// However, if an empty string is specified only invariant children are returned. /// </para> /// </remarks> public static IEnumerable<IPublishedContent> Children(this IPublishedContent content, string culture = null) => content.Children(VariationContextAccessor, culture); /// <summary> /// Gets the children of the content, filtered by a predicate. /// </summary> /// <param name="content">The content.</param> /// <param name="predicate">The predicate.</param> /// <param name="culture">The specific culture to filter for. If null is used the current culture is used. (Default is null)</param> /// <returns>The children of the content, filtered by the predicate.</returns> /// <remarks> /// <para>Children are sorted by their sortOrder.</para> /// </remarks> public static IEnumerable<IPublishedContent> Children(this IPublishedContent content, Func<IPublishedContent, bool> predicate, string culture = null) => content.Children(VariationContextAccessor, predicate, culture); /// <summary> /// Gets the children of the content, of any of the specified types. /// </summary> /// <param name="content">The content.</param> /// <param name="culture">The specific culture to filter for. If null is used the current culture is used. (Default is null)</param> /// <param name="contentTypeAlias">The content type alias.</param> /// <returns>The children of the content, of any of the specified types.</returns> public static IEnumerable<IPublishedContent> ChildrenOfType(this IPublishedContent content, string contentTypeAlias, string culture = null) => content.ChildrenOfType(VariationContextAccessor, contentTypeAlias, culture); /// <summary> /// Gets the children of the content, of a given content type. /// </summary> /// <typeparam name="T">The content type.</typeparam> /// <param name="content">The content.</param> /// <param name="culture">The specific culture to filter for. If null is used the current culture is used. (Default is null)</param> /// <returns>The children of content, of the given content type.</returns> /// <remarks> /// <para>Children are sorted by their sortOrder.</para> /// </remarks> public static IEnumerable<T> Children<T>(this IPublishedContent content, string culture = null) where T : class, IPublishedContent => content.Children<T>(VariationContextAccessor, culture); public static IPublishedContent FirstChild(this IPublishedContent content, string culture = null) => content.FirstChild(VariationContextAccessor, culture); /// <summary> /// Gets the first child of the content, of a given content type. /// </summary> public static IPublishedContent FirstChildOfType(this IPublishedContent content, string contentTypeAlias, string culture = null) => content.FirstChildOfType(VariationContextAccessor, contentTypeAlias, culture); public static IPublishedContent FirstChild(this IPublishedContent content, Func<IPublishedContent, bool> predicate, string culture = null) => content.FirstChild(VariationContextAccessor, predicate, culture); public static IPublishedContent FirstChild(this IPublishedContent content, Guid uniqueId, string culture = null) => content.FirstChild(VariationContextAccessor, uniqueId, culture); public static T FirstChild<T>(this IPublishedContent content, string culture = null) where T : class, IPublishedContent => content.FirstChild<T>(VariationContextAccessor, culture); public static T FirstChild<T>(this IPublishedContent content, Func<T, bool> predicate, string culture = null) where T : class, IPublishedContent => content.FirstChild<T>(VariationContextAccessor, predicate, culture); /// <summary> /// Gets the siblings of the content. /// </summary> /// <param name="content">The content.</param> /// <param name="culture">The specific culture to filter for. If null is used the current culture is used. (Default is null)</param> /// <returns>The siblings of the content.</returns> /// <remarks> /// <para>Note that in V7 this method also return the content node self.</para> /// </remarks> public static IEnumerable<IPublishedContent> Siblings(this IPublishedContent content, string culture = null) => content.Siblings(PublishedSnapshot, VariationContextAccessor, culture); /// <summary> /// Gets the siblings of the content, of a given content type. /// </summary> /// <param name="content">The content.</param> /// <param name="contentTypeAlias">The content type alias.</param> /// <param name="culture">The specific culture to filter for. If null is used the current culture is used. (Default is null)</param> /// <returns>The siblings of the content, of the given content type.</returns> /// <remarks> /// <para>Note that in V7 this method also return the content node self.</para> /// </remarks> public static IEnumerable<IPublishedContent> SiblingsOfType(this IPublishedContent content, string contentTypeAlias, string culture = null) => content.SiblingsOfType(PublishedSnapshot, VariationContextAccessor, contentTypeAlias, culture); /// <summary> /// Gets the siblings of the content, of a given content type. /// </summary> /// <typeparam name="T">The content type.</typeparam> /// <param name="content">The content.</param> /// <param name="culture">The specific culture to filter for. If null is used the current culture is used. (Default is null)</param> /// <returns>The siblings of the content, of the given content type.</returns> /// <remarks> /// <para>Note that in V7 this method also return the content node self.</para> /// </remarks> public static IEnumerable<T> Siblings<T>(this IPublishedContent content, string culture = null) where T : class, IPublishedContent => content.Siblings<T>(PublishedSnapshot, VariationContextAccessor, culture); /// <summary> /// Gets the siblings of the content including the node itself to indicate the position. /// </summary> /// <param name="content">The content.</param> /// <param name="culture">The specific culture to filter for. If null is used the current culture is used. (Default is null)</param> /// <returns>The siblings of the content including the node itself.</returns> public static IEnumerable<IPublishedContent> SiblingsAndSelf(this IPublishedContent content, string culture = null) => content.SiblingsAndSelf(PublishedSnapshot, VariationContextAccessor, culture); /// <summary> /// Gets the siblings of the content including the node itself to indicate the position, of a given content type. /// </summary> /// <param name="content">The content.</param> /// <param name="culture">The specific culture to filter for. If null is used the current culture is used. (Default is null)</param> /// <param name="contentTypeAlias">The content type alias.</param> /// <returns>The siblings of the content including the node itself, of the given content type.</returns> public static IEnumerable<IPublishedContent> SiblingsAndSelfOfType(this IPublishedContent content, string contentTypeAlias, string culture = null) => content.SiblingsAndSelfOfType(PublishedSnapshot, VariationContextAccessor, contentTypeAlias, culture); /// <summary> /// Gets the siblings of the content including the node itself to indicate the position, of a given content type. /// </summary> /// <typeparam name="T">The content type.</typeparam> /// <param name="content">The content.</param> /// <param name="culture">The specific culture to filter for. If null is used the current culture is used. (Default is null)</param> /// <returns>The siblings of the content including the node itself, of the given content type.</returns> public static IEnumerable<T> SiblingsAndSelf<T>(this IPublishedContent content, string culture = null) where T : class, IPublishedContent => content.SiblingsAndSelf<T>(PublishedSnapshot, VariationContextAccessor, culture); /// <summary> /// Gets the url of the content item. /// </summary> /// <remarks> /// <para>If the content item is a document, then this method returns the url of the /// document. If it is a media, then this methods return the media url for the /// 'umbracoFile' property. Use the MediaUrl() method to get the media url for other /// properties.</para> /// <para>The value of this property is contextual. It depends on the 'current' request uri, /// if any. In addition, when the content type is multi-lingual, this is the url for the /// specified culture. Otherwise, it is the invariant url.</para> /// </remarks> public static string Url(this IPublishedContent content, string culture = null, UrlMode mode = UrlMode.Default) => content.Url(PublishedUrlProvider, culture, mode); /// <summary> /// Gets the children of the content in a DataTable. /// </summary> /// <param name="content">The content.</param> /// <param name="variationContextAccessor">Variation context accessor.</param> /// <param name="contentTypeService">The content type service.</param> /// <param name="mediaTypeService">The media type service.</param> /// <param name="memberTypeService">The member type service.</param> /// <param name="publishedUrlProvider">The published url provider.</param> /// <param name="contentTypeAliasFilter">An optional content type alias.</param> /// <param name="culture">The specific culture to filter for. If null is used the current culture is used. (Default is null)</param> /// <returns>The children of the content.</returns> public static DataTable ChildrenAsTable(this IPublishedContent content, string contentTypeAliasFilter = "", string culture = null) => content.ChildrenAsTable(VariationContextAccessor, ContentTypeService, MediaTypeService, MemberTypeService, PublishedUrlProvider, contentTypeAliasFilter, culture); /// <summary> /// Gets the url for a media. /// </summary> /// <param name="content">The content item.</param> /// <param name="culture">The culture (use current culture by default).</param> /// <param name="mode">The url mode (use site configuration by default).</param> /// <param name="propertyAlias">The alias of the property (use 'umbracoFile' by default).</param> /// <returns>The url for the media.</returns> /// <remarks> /// <para>The value of this property is contextual. It depends on the 'current' request uri, /// if any. In addition, when the content type is multi-lingual, this is the url for the /// specified culture. Otherwise, it is the invariant url.</para> /// </remarks> public static string MediaUrl( this IPublishedContent content, string culture = null, UrlMode mode = UrlMode.Default, string propertyAlias = Constants.Conventions.Media.File) => content.MediaUrl(PublishedUrlProvider, culture, mode, propertyAlias); /// <summary> /// Gets the name of the content item creator. /// </summary> /// <param name="content">The content item.</param> public static string CreatorName(this IPublishedContent content) => content.CreatorName(UserService); /// <summary> /// Gets the name of the content item writer. /// </summary> /// <param name="content">The content item.</param> public static string WriterName(this IPublishedContent content) => content.WriterName(UserService); /// <summary> /// Gets the culture assigned to a document by domains, in the context of a current Uri. /// </summary> /// <param name="content">The document.</param> /// <param name="current">An optional current Uri.</param> /// <returns>The culture assigned to the document by domains.</returns> /// <remarks> /// <para>In 1:1 multilingual setup, a document contains several cultures (there is not /// one document per culture), and domains, withing the context of a current Uri, assign /// a culture to that document.</para> /// </remarks> public static string GetCultureFromDomains( this IPublishedContent content, Uri current = null) => content.GetCultureFromDomains(UmbracoContextAccessor, SiteDomainHelper, current); public static IEnumerable<PublishedSearchResult> SearchDescendants( this IPublishedContent content, string term, string indexName = null) => content.SearchDescendants(ExamineManager, UmbracoContextAccessor, term, indexName); public static IEnumerable<PublishedSearchResult> SearchChildren( this IPublishedContent content, string term, string indexName = null) => content.SearchChildren(ExamineManager, UmbracoContextAccessor, term, indexName); } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Newtonsoft.Json.Utilities { internal sealed class DynamicProxyMetaObject<T> : DynamicMetaObject { private readonly DynamicProxy<T> _proxy; private readonly bool _dontFallbackFirst; internal DynamicProxyMetaObject(Expression expression, T value, DynamicProxy<T> proxy, bool dontFallbackFirst) : base(expression, BindingRestrictions.Empty, value) { _proxy = proxy; _dontFallbackFirst = dontFallbackFirst; } private new T Value { get { return (T)base.Value; } } private bool IsOverridden(string method) { return ReflectionUtils.IsMethodOverridden(_proxy.GetType(), typeof (DynamicProxy<T>), method); } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { return IsOverridden("TryGetMember") ? CallMethodWithResult("TryGetMember", binder, NoArgs, e => binder.FallbackGetMember(this, e)) : base.BindGetMember(binder); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { return IsOverridden("TrySetMember") ? CallMethodReturnLast("TrySetMember", binder, GetArgs(value), e => binder.FallbackSetMember(this, value, e)) : base.BindSetMember(binder, value); } public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) { return IsOverridden("TryDeleteMember") ? CallMethodNoResult("TryDeleteMember", binder, NoArgs, e => binder.FallbackDeleteMember(this, e)) : base.BindDeleteMember(binder); } public override DynamicMetaObject BindConvert(ConvertBinder binder) { return IsOverridden("TryConvert") ? CallMethodWithResult("TryConvert", binder, NoArgs, e => binder.FallbackConvert(this, e)) : base.BindConvert(binder); } public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { if (!IsOverridden("TryInvokeMember")) return base.BindInvokeMember(binder, args); // // Generate a tree like: // // { // object result; // TryInvokeMember(payload, out result) // ? result // : TryGetMember(payload, out result) // ? FallbackInvoke(result) // : fallbackResult // } // // Then it calls FallbackInvokeMember with this tree as the // "error", giving the language the option of using this // tree or doing .NET binding. // Fallback fallback = e => binder.FallbackInvokeMember(this, args, e); DynamicMetaObject call = BuildCallMethodWithResult( "TryInvokeMember", binder, GetArgArray(args), BuildCallMethodWithResult( "TryGetMember", new GetBinderAdapter(binder), NoArgs, fallback(null), e => binder.FallbackInvoke(e, args, null) ), null ); return _dontFallbackFirst ? call : fallback(call); } public override DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args) { return IsOverridden("TryCreateInstance") ? CallMethodWithResult("TryCreateInstance", binder, GetArgArray(args), e => binder.FallbackCreateInstance(this, args, e)) : base.BindCreateInstance(binder, args); } public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { return IsOverridden("TryInvoke") ? CallMethodWithResult("TryInvoke", binder, GetArgArray(args), e => binder.FallbackInvoke(this, args, e)) : base.BindInvoke(binder, args); } public override DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg) { return IsOverridden("TryBinaryOperation") ? CallMethodWithResult("TryBinaryOperation", binder, GetArgs(arg), e => binder.FallbackBinaryOperation(this, arg, e)) : base.BindBinaryOperation(binder, arg); } public override DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder) { return IsOverridden("TryUnaryOperation") ? CallMethodWithResult("TryUnaryOperation", binder, NoArgs, e => binder.FallbackUnaryOperation(this, e)) : base.BindUnaryOperation(binder); } public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { return IsOverridden("TryGetIndex") ? CallMethodWithResult("TryGetIndex", binder, GetArgArray(indexes), e => binder.FallbackGetIndex(this, indexes, e)) : base.BindGetIndex(binder, indexes); } public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { return IsOverridden("TrySetIndex") ? CallMethodReturnLast("TrySetIndex", binder, GetArgArray(indexes, value), e => binder.FallbackSetIndex(this, indexes, value, e)) : base.BindSetIndex(binder, indexes, value); } public override DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes) { return IsOverridden("TryDeleteIndex") ? CallMethodNoResult("TryDeleteIndex", binder, GetArgArray(indexes), e => binder.FallbackDeleteIndex(this, indexes, e)) : base.BindDeleteIndex(binder, indexes); } private delegate DynamicMetaObject Fallback(DynamicMetaObject errorSuggestion); private readonly static Expression[] NoArgs = new Expression[0]; private static Expression[] GetArgs(params DynamicMetaObject[] args) { return args.Select(arg => Expression.Convert(arg.Expression, typeof(object))).ToArray(); } private static Expression[] GetArgArray(DynamicMetaObject[] args) { return new[] { Expression.NewArrayInit(typeof(object), GetArgs(args)) }; } private static Expression[] GetArgArray(DynamicMetaObject[] args, DynamicMetaObject value) { return new Expression[] { Expression.NewArrayInit(typeof(object), GetArgs(args)), Expression.Convert(value.Expression, typeof(object)) }; } private static ConstantExpression Constant(DynamicMetaObjectBinder binder) { Type t = binder.GetType(); while (!t.IsVisible()) t = t.BaseType(); return Expression.Constant(binder, t); } /// <summary> /// Helper method for generating a MetaObject which calls a /// specific method on Dynamic that returns a result /// </summary> private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback, Fallback fallbackInvoke = null) { // // First, call fallback to do default binding // This produces either an error or a call to a .NET member // DynamicMetaObject fallbackResult = fallback(null); DynamicMetaObject callDynamic = BuildCallMethodWithResult(methodName, binder, args, fallbackResult, fallbackInvoke); // // Now, call fallback again using our new MO as the error // When we do this, one of two things can happen: // 1. Binding will succeed, and it will ignore our call to // the dynamic method, OR // 2. Binding will fail, and it will use the MO we created // above. // return _dontFallbackFirst ? callDynamic : fallback(callDynamic); } private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke) { // // Build a new expression like: // { // object result; // TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult // } // ParameterExpression result = Expression.Parameter(typeof(object), null); IList<Expression> callArgs = new List<Expression>(); callArgs.Add(Expression.Convert(Expression, typeof(T))); callArgs.Add(Constant(binder)); callArgs.AddRange(args); callArgs.Add(result); DynamicMetaObject resultMetaObject = new DynamicMetaObject(result, BindingRestrictions.Empty); // Need to add a conversion if calling TryConvert if (binder.ReturnType != typeof (object)) { UnaryExpression convert = Expression.Convert(resultMetaObject.Expression, binder.ReturnType); // will always be a cast or unbox resultMetaObject = new DynamicMetaObject(convert, resultMetaObject.Restrictions); } if (fallbackInvoke != null) resultMetaObject = fallbackInvoke(resultMetaObject); DynamicMetaObject callDynamic = new DynamicMetaObject( Expression.Block( new[] {result}, Expression.Condition( Expression.Call( Expression.Constant(_proxy), typeof(DynamicProxy<T>).GetMethod(methodName), callArgs ), resultMetaObject.Expression, fallbackResult.Expression, binder.ReturnType ) ), GetRestrictions().Merge(resultMetaObject.Restrictions).Merge(fallbackResult.Restrictions) ); return callDynamic; } /// <summary> /// Helper method for generating a MetaObject which calls a /// specific method on Dynamic, but uses one of the arguments for /// the result. /// </summary> private DynamicMetaObject CallMethodReturnLast(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback) { // // First, call fallback to do default binding // This produces either an error or a call to a .NET member // DynamicMetaObject fallbackResult = fallback(null); // // Build a new expression like: // { // object result; // TrySetMember(payload, result = value) ? result : fallbackResult // } // ParameterExpression result = Expression.Parameter(typeof(object), null); IList<Expression> callArgs = new List<Expression>(); callArgs.Add(Expression.Convert(Expression, typeof (T))); callArgs.Add(Constant(binder)); callArgs.AddRange(args); callArgs[args.Length + 1] = Expression.Assign(result, callArgs[args.Length + 1]); DynamicMetaObject callDynamic = new DynamicMetaObject( Expression.Block( new[] { result }, Expression.Condition( Expression.Call( Expression.Constant(_proxy), typeof(DynamicProxy<T>).GetMethod(methodName), callArgs ), result, fallbackResult.Expression, typeof(object) ) ), GetRestrictions().Merge(fallbackResult.Restrictions) ); // // Now, call fallback again using our new MO as the error // When we do this, one of two things can happen: // 1. Binding will succeed, and it will ignore our call to // the dynamic method, OR // 2. Binding will fail, and it will use the MO we created // above. // return _dontFallbackFirst ? callDynamic : fallback(callDynamic); } /// <summary> /// Helper method for generating a MetaObject which calls a /// specific method on Dynamic, but uses one of the arguments for /// the result. /// </summary> private DynamicMetaObject CallMethodNoResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback) { // // First, call fallback to do default binding // This produces either an error or a call to a .NET member // DynamicMetaObject fallbackResult = fallback(null); IList<Expression> callArgs = new List<Expression>(); callArgs.Add(Expression.Convert(Expression, typeof(T))); callArgs.Add(Constant(binder)); callArgs.AddRange(args); // // Build a new expression like: // if (TryDeleteMember(payload)) { } else { fallbackResult } // DynamicMetaObject callDynamic = new DynamicMetaObject( Expression.Condition( Expression.Call( Expression.Constant(_proxy), typeof(DynamicProxy<T>).GetMethod(methodName), callArgs ), Expression.Empty(), fallbackResult.Expression, typeof (void) ), GetRestrictions().Merge(fallbackResult.Restrictions) ); // // Now, call fallback again using our new MO as the error // When we do this, one of two things can happen: // 1. Binding will succeed, and it will ignore our call to // the dynamic method, OR // 2. Binding will fail, and it will use the MO we created // above. // return _dontFallbackFirst ? callDynamic : fallback(callDynamic); } /// <summary> /// Returns a Restrictions object which includes our current restrictions merged /// with a restriction limiting our type /// </summary> private BindingRestrictions GetRestrictions() { return (Value == null && HasValue) ? BindingRestrictions.GetInstanceRestriction(Expression, null) : BindingRestrictions.GetTypeRestriction(Expression, LimitType); } public override IEnumerable<string> GetDynamicMemberNames() { return _proxy.GetDynamicMemberNames(Value); } // It is okay to throw NotSupported from this binder. This object // is only used by DynamicObject.GetMember--it is not expected to // (and cannot) implement binding semantics. It is just so the DO // can use the Name and IgnoreCase properties. private sealed class GetBinderAdapter : GetMemberBinder { internal GetBinderAdapter(InvokeMemberBinder binder) : base(binder.Name, binder.IgnoreCase) { } public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { throw new NotSupportedException(); } } } } #endif
#if DEBUG //#define TRACE #endif using System; using System.Collections.Generic; using System.Reflection; using Rynchodon.AntennaRelay; using Rynchodon.Attached; using Rynchodon.Autopilot.Data; using Rynchodon.Autopilot.Movement; using Rynchodon.Threading; using Rynchodon.Utility; using Sandbox.Common.ObjectBuilders; using Sandbox.Game.Entities; using Sandbox.Game.GameSystems; using Sandbox.Game.Weapons; using Sandbox.Game.World; using VRage.Game.Entity; using VRage.Game.ModAPI; using VRage.ModAPI; using VRageMath; namespace Rynchodon.Autopilot.Pathfinding { /// <summary> /// Figures out how to get to where the navigator wants to go, supplies the direction and distance to Mover. /// </summary> /// <remarks> /// The process is divided into two parts: high-level/repulsion and low-level/pathfinding. /// Repulsion treats every potential obstruction as a sphere and tries to keep autopilot away from those spheres. /// When autopilot gets too close to a potential obstruction or repulsion is not suitable, Pathfinder switches to pathfinding. /// Pathfinding is based on A* but uses waypoints instead of grid cells as they are more suited to the complex environments and ships in Space Engineers. /// /// Obviously it is a lot more complicated than that but if anyone is actually reading this and has questions, just ask. /// </remarks> public partial class Pathfinder { #region Static public const float SpeedFactor = 3f, VoxelAdd = 10f; private class StaticVariables { public ThreadManager ThreadForeground, ThreadBackground; public MethodInfo RequestJump; public FieldInfo JumpDisplacement; public StaticVariables() { Logger.DebugLog("entered", Logger.severity.TRACE); byte allowedThread = (byte)(Environment.ProcessorCount / 2); ThreadForeground = new ThreadManager(allowedThread, false, "PathfinderForeground"); ThreadBackground = new ThreadManager(allowedThread, true, "PathfinderBackground"); Type[] argTypes = new Type[] { typeof(Vector3D), typeof(long) }; RequestJump = typeof(MyGridJumpDriveSystem).GetMethod("RequestJump", BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, argTypes, null); JumpDisplacement = typeof(MyGridJumpDriveSystem).GetField("m_jumpDirection", BindingFlags.NonPublic | BindingFlags.Instance); } } private static StaticVariables value_static; private static StaticVariables Static { get { if (Globals.WorldClosed) throw new Exception("World closed"); if (value_static == null) value_static = new StaticVariables(); return value_static; } set { value_static = value; } } [OnWorldClose] private static void Unload() { Static = null; } #endregion #region Fields private readonly PathTester m_tester; private readonly FastResourceLock m_runningLock = new FastResourceLock(); private bool m_runInterrupt, m_runHalt, m_navSetChange = true; private ulong m_waitUntil, m_nextJumpAttempt; private LineSegmentD m_lineSegment = new LineSegmentD(); private MyGridJumpDriveSystem m_jumpSystem; // Inputs: rarely change private MyCubeGrid m_autopilotGrid { get { return m_tester.AutopilotGrid; } set { m_tester.AutopilotGrid = value; } } private PseudoBlock m_navBlock; private Destination[] m_destinations; /// <summary>Initially set to m_destinations[0], pathfinder may change this if one of the other destinations is easier to reach.</summary> private Destination m_pickedDestination; private bool m_ignoreVoxel, m_canChangeCourse; // Inputs: always updated private Vector3 m_addToVelocity; private Vector3D m_currentPosition, m_destWorld; private Vector3 m_autopilotVelocity { get { return m_autopilotGrid.Physics.LinearVelocity; } } private float m_autopilotShipBoundingRadius { get { return m_autopilotGrid.PositionComp.LocalVolume.Radius; } } // High Level private SphereClusters m_clusters = new SphereClusters(); /// <summary>First this list is populated by pruning structure, when calculating repulsion it is populated with entities to be avoided.</summary> private List<MyEntity> m_entitiesPruneAvoid = new List<MyEntity>(); /// <summary>List of entities that will repulse the autopilot.</summary> private List<MyEntity> m_entitiesRepulse = new List<MyEntity>(); private bool m_checkVoxel; private Vector3 m_moveDirection; private float m_moveLength; // Results private Obstruction m_obstructingEntity; private MyCubeBlock m_obstructingBlock; private bool m_holdPosition = true; #endregion #region Properties private Logable Log { get { return new Logable(m_autopilotGrid.nameWithId(), m_navBlock?.DisplayName, CurrentState.ToString()); } } public MyEntity ReportedObstruction { get { return m_obstructingBlock ?? m_obstructingEntity.Entity; } } public Mover Mover { get; private set; } public AllNavigationSettings NavSet { get { return Mover.NavSet; } } public RotateChecker RotateCheck { get { return Mover.RotateCheck; } } public InfoString.StringId_Jump JumpComplaint { get; private set; } #endregion /// <summary> /// Creates a Pathfinder for a ShipControllerBlock. /// </summary> /// <param name="block">The autopilot or remote control that needs to find its way in the world.</param> public Pathfinder(ShipControllerBlock block) { Mover = new Mover(block, new RotateChecker(block.CubeBlock, CollectEntities)); m_tester = new PathTester(Mover.Block); NavSet.AfterTaskComplete += NavSet_AfterTaskComplete; } /// <summary> /// Forces Pathfinder to reset. /// </summary> private void NavSet_AfterTaskComplete() { m_navSetChange = true; if (CurrentState != State.Crashed) CurrentState = State.None; } #region On Autopilot Thread /// <summary> /// Forces Pathfinder to stop. /// </summary> public void Halt() { m_runHalt = true; } /// <summary> /// Maintain destination radius from an entity. /// </summary> /// <param name="targetEntity">The entity to maintain position from.</param> public void HoldPosition(IMyEntity targetEntity) { Vector3D myCentre = m_autopilotGrid.GetCentre(); Vector3D targetCentre = targetEntity.GetCentre(); double distanceSquared; Vector3D.DistanceSquared(ref myCentre, ref targetCentre, out distanceSquared); double targetDist = NavSet.Settings_Current.DestinationRadius + m_autopilotGrid.PositionComp.WorldVolume.Radius + targetEntity.WorldVolume.Radius; if (distanceSquared < targetDist * targetDist) MoveTo(destinations: Destination.FromWorld(targetEntity, m_navBlock.WorldPosition)); else { Vector3D offset; Vector3D.Subtract(ref myCentre, ref targetCentre, out offset); offset.Normalize(); Vector3D.Multiply(ref offset, targetDist, out offset); MoveTo(destinations: new Destination(targetEntity, offset)); } } /// <summary> /// Maintain destination radius from an entity. /// </summary> /// <param name="targetEntity">The entity to maintain position from.</param> public void HoldPosition(LastSeen targetEntity) { if (targetEntity.isRecent()) { HoldPosition(targetEntity.Entity); return; } double distanceSquared = Vector3D.DistanceSquared(m_autopilotGrid.GetCentre(), targetEntity.LastKnownPosition); double targetDist = NavSet.Settings_Current.DestinationRadius + m_autopilotGrid.PositionComp.WorldVolume.Radius + targetEntity.Entity.WorldVolume.Radius; if (distanceSquared < targetDist * targetDist) MoveTo(targetEntity.LastKnownVelocity, new Destination(m_navBlock.WorldPosition)); else MoveTo(targetEntity.LastKnownVelocity, new Destination(targetEntity.LastKnownPosition)); } /// <summary> /// Move to an entity given by a LastSeen, performs recent check so navigator will not have to. /// </summary> /// <param name="targetEntity">The destination entity.</param> /// <param name="offset">Destination's offset from the centre of targetEntity.</param> /// <param name="addToVelocity">Velocity to add to autopilot's target velocity.</param> public void MoveTo(LastSeen targetEntity, Vector3D offset = default(Vector3D), Vector3 addToVelocity = default(Vector3)) { Destination dest; if (targetEntity.isRecent()) { dest = new Destination(targetEntity.Entity, ref offset); Log.DebugLog("recent. dest: " + dest); } else { dest = new Destination(targetEntity.LastKnownPosition + offset); addToVelocity += targetEntity.LastKnownVelocity; Log.DebugLog("not recent. dest: " + dest + ", actual position: " + targetEntity.Entity.GetPosition()); } MoveTo(addToVelocity, dest); } /// <summary> /// Pathfind to one or more destinations. Pathfinder will first attempt to move to the first destination and, failing that, will treat all destinations as valid targets. /// </summary> /// <param name="addToVelocity">Velocity to add to autopilot's target velocity.</param> /// <param name="destinations">The destinations that autopilot will try to reach.</param> public void MoveTo(Vector3 addToVelocity = default(Vector3), params Destination[] destinations) { if (CurrentState == State.Crashed) { m_runHalt = true; Mover.MoveAndRotateStop(false); return; } m_runHalt = false; Move(); AllNavigationSettings.SettingsLevel level = Mover.NavSet.Settings_Current; m_addToVelocity = addToVelocity; m_destinations = destinations; m_pickedDestination = m_destinations[0]; if (!m_navSetChange) { Static.ThreadForeground.EnqueueAction(Run); return; } Log.DebugLog("Nav settings changed"); using (m_runningLock.AcquireExclusiveUsing()) { m_runInterrupt = true; m_navBlock = level.NavigationBlock; m_autopilotGrid = (MyCubeGrid)m_navBlock.Grid; m_ignoreVoxel = level.IgnoreAsteroid; m_canChangeCourse = level.PathfinderCanChangeCourse; m_holdPosition = true; m_navSetChange = false; } if (m_navBlock == null) { Log.DebugLog("No nav block"); return; } Static.ThreadForeground.EnqueueAction(Run); } /// <summary> /// Call on autopilot thread. Instructs Mover to calculate movement. /// </summary> private void Move() { MyEntity relative = GetRelativeEntity(); Vector3 disp; Vector3.Multiply(ref m_moveDirection, m_moveLength, out disp); Vector3 targetVelocity = relative != null && relative.Physics != null && !relative.Physics.IsStatic ? relative.Physics.LinearVelocity : Vector3.Zero; if (!m_path.HasTarget) { Vector3 temp; Vector3.Add(ref targetVelocity, ref m_addToVelocity, out temp); targetVelocity = temp; } if (m_navSetChange || m_runInterrupt || m_runHalt) return; if (m_holdPosition) { //Log.DebugLog("Holding position"); Mover.CalcMove(m_navBlock, ref Vector3.Zero, ref targetVelocity); return; } Log.TraceLog("Should not be moving! disp: " + disp, Logger.severity.DEBUG, condition: CurrentState != State.Unobstructed && CurrentState != State.FollowingPath); Log.TraceLog("moving: " + disp + ", targetVelocity: " + targetVelocity); Mover.CalcMove(m_navBlock, ref disp, ref targetVelocity); } #endregion #region Flow /// <summary> /// Main entry point while not pathfinding. /// </summary> private void Run() { if (m_waitUntil > Globals.UpdateCount) { m_holdPosition = true; OnComplete(); return; } if (!m_runningLock.TryAcquireExclusive()) return; try { if (m_runHalt) return; if (m_runInterrupt) { m_path.Clear(); CurrentState = State.None; m_runInterrupt = false; } else if (CurrentState == State.SearchingForPath) return; if (m_jumpSystem != null) { if (m_jumpSystem.GetJumpDriveDirection().HasValue) { JumpComplaint = InfoString.StringId_Jump.Jumping; FillDestWorld(); return; } else { float distance = NavSet.Settings_Current.Distance; FillDestWorld(); if (NavSet.Settings_Current.Distance < distance - MyGridJumpDriveSystem.MIN_JUMP_DISTANCE * 0.5d) { Log.DebugLog("Jump completed, distance travelled: " + (distance - NavSet.Settings_Current.Distance), Logger.severity.INFO); m_nextJumpAttempt = 0uL; JumpComplaint = InfoString.StringId_Jump.None; } else { Log.DebugLog("Jump failed, distance travelled: " + (distance - NavSet.Settings_Current.Distance), Logger.severity.WARNING); JumpComplaint = InfoString.StringId_Jump.Failed; } m_jumpSystem = null; } } else FillDestWorld(); TestCurrentPath(); // if the current path is obstructed, it is not possible to jump if (!m_holdPosition) { if (TryJump()) m_holdPosition = true; } else JumpComplaint = InfoString.StringId_Jump.None; OnComplete(); } catch { Log.AlwaysLog("Pathfinder crashed", Logger.severity.ERROR); CurrentState = State.Crashed; throw; } finally { m_runningLock.ReleaseExclusive(); } PostRun(); } /// <summary> /// Clears entity lists. /// </summary> private void OnComplete() { m_entitiesPruneAvoid.Clear(); m_entitiesRepulse.Clear(); } /// <summary> /// Queues the next action to foreground or background thread. /// </summary> private void PostRun() { if (m_runHalt) return; if (m_runInterrupt) Static.ThreadForeground.EnqueueAction(Run); else if (CurrentState == State.SearchingForPath) Static.ThreadBackground.EnqueueAction(ContinuePathfinding); } #endregion #region Common /// <summary> /// Sets m_destWorld to the correct value. /// </summary> private void FillDestWorld() { m_currentPosition = m_autopilotGrid.GetCentre(); Vector3D finalDestWorld = m_pickedDestination.WorldPosition() + m_currentPosition - m_navBlock.WorldPosition; double distance; Vector3D.Distance(ref finalDestWorld, ref m_currentPosition, out distance); NavSet.Settings_Current.Distance = (float)distance; Log.DebugLog("Missing obstruction", Logger.severity.ERROR, condition: m_path.HasTarget && m_obstructingEntity.Entity == null); m_destWorld = m_path.HasTarget ? m_path.GetTarget() + m_obstructingEntity.GetPosition() : finalDestWorld; Log.TraceLog("final dest world: " + finalDestWorld + ", picked: " + m_pickedDestination.WorldPosition() + ", current position: " + m_currentPosition + ", offset: " + (m_currentPosition - m_navBlock.WorldPosition) + ", distance: " + distance + ", is final: " + (m_path.Count == 0) + ", dest world: " + m_destWorld); } /// <summary> /// Gets the top most entity of the destination entity, if it exists. /// </summary> /// <returns>The top most destination entity or null.</returns> private MyEntity GetTopMostDestEntity() { return m_pickedDestination.Entity != null ? (MyEntity)m_pickedDestination.Entity.GetTopMostParent() : null; } /// <summary> /// Get the entity autopilot will navigate relative to. /// </summary> /// <returns>The entity autopilot will navigate relative to.</returns> private MyEntity GetRelativeEntity() { Obstruction obstruct = m_obstructingEntity; return obstruct.Entity != null && obstruct.MatchPosition ? obstruct.Entity : GetTopMostDestEntity(); } /// <summary> /// Tests whether of not the specified entity is moving away and is not the top-most destination entity. /// </summary> /// <param name="obstruction">The entity to test for moving away.</param> /// <returns>True iff the entity is moving away.</returns> private bool ObstructionMovingAway(MyEntity obstruction) { Log.DebugLog("obstruction == null", Logger.severity.FATAL, condition: obstruction == null); MyEntity topDest = GetTopMostDestEntity(); Vector3D destVelocity = topDest != null && topDest.Physics != null ? topDest.Physics.LinearVelocity : Vector3.Zero; Vector3D obstVlocity = obstruction.Physics != null ? obstruction.Physics.LinearVelocity : Vector3.Zero; double distSq; Vector3D.DistanceSquared(ref destVelocity, ref obstVlocity, out distSq); if (distSq < 1d) return false; if (obstVlocity.LengthSquared() < 0.01d) return false; Vector3D position = obstruction.GetCentre(); Vector3D nextPosition; Vector3D.Add(ref position, ref obstVlocity, out nextPosition); double current; Vector3D.DistanceSquared(ref m_currentPosition, ref position, out current); double next; Vector3D.DistanceSquared(ref m_currentPosition, ref nextPosition, out next); Log.DebugLog("Obstruction is moving away", condition: current < next); return current < next; } #endregion #region Collect Entities /// <summary> /// Fill m_entitiesPruneAvoid with nearby entities. /// Fill m_entitiesRepulse from m_entitiesPruneAvoid, ignoring some entitites. /// </summary> private void FillEntitiesLists() { Profiler.StartProfileBlock(); m_entitiesPruneAvoid.Clear(); m_entitiesRepulse.Clear(); BoundingSphereD sphere = new BoundingSphereD() { Center = m_currentPosition, Radius = m_autopilotShipBoundingRadius + (m_autopilotVelocity.Length() + 1000f) * SpeedFactor }; MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref sphere, m_entitiesPruneAvoid); foreach (MyEntity entity in CollectEntities(m_entitiesPruneAvoid)) if (!NavSet.Settings_Current.ShouldIgnoreEntity(entity)) m_entitiesRepulse.Add(entity); Profiler.EndProfileBlock(); } /// <summary> /// Enumerable for entities which are not normally ignored. /// </summary> /// <param name="fromPruning">The list of entities from MyGamePruningStrucure</param> /// <returns>Enumerable for entities which are not normally ignored.</returns> private IEnumerable<MyEntity> CollectEntities(List<MyEntity> fromPruning) { for (int i = fromPruning.Count - 1; i >= 0; i--) { MyEntity entity = fromPruning[i]; if (entity is MyCubeGrid) { MyCubeGrid grid = (MyCubeGrid)entity; if (grid == m_autopilotGrid) continue; if (!grid.Save) continue; if (AttachedGrid.IsGridAttached(m_autopilotGrid, grid, AttachedGrid.AttachmentKind.Physics)) continue; } else if (entity is MyVoxelBase) { if (!m_ignoreVoxel && (entity is MyVoxelMap || entity is MyPlanet)) yield return entity; continue; } else if (entity is MyAmmoBase) { yield return entity; continue; } else if (!(entity is MyFloatingObject)) continue; if (entity.Physics != null && entity.Physics.Mass > 0f && entity.Physics.Mass < 1000f) continue; yield return entity; } } #endregion #region Test Path /// <summary> /// Test the current path for obstructions, sets the move direction and distance, and starts pathfinding if the current path cannot be travelled. /// </summary> private void TestCurrentPath() { if (m_path.HasTarget) { // don't chase an obstructing entity unless it is the destination if (ObstructionMovingAway(m_obstructingEntity.Entity)) { Log.DebugLog("Obstruction is moving away, I'll just wait here", Logger.severity.TRACE); m_path.Clear(); m_obstructingEntity = new Obstruction(); m_obstructingBlock = null; m_holdPosition = true; return; } // if near waypoint, pop it double distSqCurToDest; Vector3D.DistanceSquared(ref m_currentPosition, ref m_destWorld, out distSqCurToDest); bool reachedDest; if (distSqCurToDest < 1d) reachedDest = true; else { Vector3D reached; m_path.GetReached(out reached); Vector3D obstructPosition = m_obstructingEntity.GetPosition(); Vector3D reachedWorld; Vector3D.Add(ref reached, ref obstructPosition, out reachedWorld); double distSqReachToDest; Vector3D.DistanceSquared(ref reachedWorld, ref m_destWorld, out distSqReachToDest); reachedDest = distSqCurToDest < distSqReachToDest * 0.04d; } if (reachedDest) { m_path.ReachedTarget(); Log.DebugLog("Reached waypoint: " + m_path.GetReached() + ", remaining: " + (m_path.Count - 1), Logger.severity.DEBUG); FillDestWorld(); if (!m_path.IsFinished) { FillEntitiesLists(); if (!SetNextPathTarget()) { Log.DebugLog("Failed to set next target, clearing path"); m_path.Clear(); } } } } //Log.DebugLog("Current position: " + m_currentPosition + ", destination: " + m_destWorld); FillEntitiesLists(); Vector3 repulsion; Vector3D disp; Vector3D.Subtract(ref m_destWorld, ref m_currentPosition, out disp); Vector3 dispF = disp; CalcRepulsion(!m_path.HasTarget && m_canChangeCourse, out repulsion); if (repulsion != Vector3.Zero) { if (dispF.LengthSquared() > 1e6f) { float distance = dispF.Length(); Vector3 scaledRepulsion; Vector3.Multiply(ref repulsion, distance * 0.001f, out scaledRepulsion); Vector3.Add(ref dispF, ref scaledRepulsion, out m_moveDirection); Log.TraceLog("Scaled repulsion: " + repulsion + " * " + (distance * 0.001f) + " = " + scaledRepulsion + ", dispF: " + dispF + ", m_targetDirection: " + m_moveDirection); } else { Vector3.Add(ref dispF, ref repulsion, out m_moveDirection); Log.TraceLog("Repulsion: " + repulsion + ", dispF: " + dispF + ", m_targetDirection: " + m_moveDirection); } } else { Log.TraceLog("No repulsion, direction is displacement: " + dispF); m_moveDirection = dispF; } if (m_moveDirection == Vector3.Zero) m_moveLength = 0f; else m_moveLength = m_moveDirection.Normalize(); MyEntity obstructing; MyCubeBlock block; float distReached; if (CurrentObstructed(out obstructing, out block, out distReached) && (!m_path.HasTarget || !TryRepairPath(distReached))) { if (ObstructionMovingAway(obstructing)) { m_holdPosition = true; return; } m_obstructingEntity = new Obstruction() { Entity = obstructing, MatchPosition = m_canChangeCourse }; // when not MatchPosition, ship will still match with destination m_obstructingBlock = block; m_holdPosition = true; Log.DebugLog("Current path is obstructed by " + obstructing.getBestName() + "." + block.getBestName() + ", starting pathfinding", Logger.severity.DEBUG); StartPathfinding(); return; } Log.TraceLog("Move direction: " + m_moveDirection + ", move distance: " + m_moveLength + ", disp: " + dispF); if (!m_path.HasTarget) { CurrentState = State.Unobstructed; m_obstructingEntity = new Obstruction(); m_obstructingBlock = null; } m_holdPosition = false; } /// <summary> /// if autopilot is off course, try to move back towards the line from last reached to current node /// </summary> /// <param name="distReached">Estimated distance along the path before encountering an obstruction. </param> private bool TryRepairPath(float distReached) { if (distReached < 1f) return false; Vector3D lastReached; m_path.GetReached(out lastReached); Vector3D obstructPosition = m_obstructingEntity.GetPosition(); Vector3D lastReachWorld; Vector3D.Add(ref lastReached, ref obstructPosition, out lastReachWorld); m_lineSegment.From = lastReachWorld; m_lineSegment.To = m_destWorld; Vector3D canTravelTo = m_currentPosition + m_moveDirection * distReached; Vector3D target; double tValue = m_lineSegment.ClosestPoint(ref canTravelTo, out target); PathTester.TestInput input; input.Offset = Vector3D.Zero; while (true) { Vector3D direction; Vector3D.Subtract(ref target, ref m_currentPosition, out direction); input.Length = (float)direction.Normalize(); input.Direction = direction; if (input.Length < 1f) { Log.DebugLog("Already on line"); break; } float proximity; if (CanTravelSegment(ref input, out proximity)) { Log.DebugLog("can travel to line"); m_moveDirection = input.Direction; m_moveLength = input.Length; return true; } tValue *= 0.5d; if (tValue <= 1d) { Log.DebugLog("Cannot reach line"); break; } Vector3D disp; Vector3D.Multiply(ref direction, tValue, out disp); Vector3D.Add(ref lastReachWorld, ref disp, out target); } return SetNextPathTarget(); } #endregion #region Calculate Repulsion /// <summary> /// Speed test entities in m_entitiesRepulse to determine which can be ignored, populates m_entitiesPruneAvoid. /// Optionally, calculates the repulsion from entities. /// </summary> /// <param name="calcRepulse">Iff true, repulsion from entities will be calculated.</param> /// <param name="repulsion">The repulsion vector from entities.</param> private void CalcRepulsion(bool calcRepulse, out Vector3 repulsion) { Profiler.StartProfileBlock(); m_entitiesPruneAvoid.Clear(); m_clusters.Clear(); float distAutopilotToFinalDest = NavSet.Settings_Current.Distance; Vector3 autopilotVelocity = m_autopilotVelocity; m_checkVoxel = false; float apRadius = m_autopilotShipBoundingRadius; float closestEntityDist = float.MaxValue; for (int index = m_entitiesRepulse.Count - 1; index >= 0; index--) { MyEntity entity = m_entitiesRepulse[index]; Log.DebugLog("entity is null", Logger.severity.FATAL, condition: entity == null); Log.DebugLog("entity is not top-most", Logger.severity.FATAL, condition: entity.Hierarchy != null && entity.Hierarchy.Parent != null); Vector3D centre = entity.GetCentre(); Vector3D toCentreD; Vector3D.Subtract(ref centre, ref m_currentPosition, out toCentreD); double distCentreToCurrent = toCentreD.Normalize(); Vector3 toCentre = toCentreD; float linearSpeedFactor; double distSqCentreToDest; Vector3D.DistanceSquared(ref centre, ref m_destWorld, out distSqCentreToDest); // determine speed of convergence if (entity.Physics == null) Vector3.Dot(ref autopilotVelocity, ref toCentre, out linearSpeedFactor); else { Vector3 obVel = entity.Physics.LinearVelocity; if (entity is MyAmmoBase) // missiles accelerate and have high damage regardless of speed so avoid them more obVel.X *= 10f; obVel.Y *= 10f; obVel.Z *= 10f; Vector3 relVel; Vector3.Subtract(ref autopilotVelocity, ref obVel, out relVel); Vector3.Dot(ref relVel, ref toCentre, out linearSpeedFactor); } if (linearSpeedFactor <= 0f) linearSpeedFactor = 0f; else linearSpeedFactor *= SpeedFactor; MyPlanet planet = entity as MyPlanet; if (planet != null) { float maxRadius = planet.MaximumRadius; if (distCentreToCurrent - apRadius - linearSpeedFactor < maxRadius) m_checkVoxel = true; if (calcRepulse) { float gravLimit = planet.GetGravityLimit() + 4000f; float gllsf = gravLimit + linearSpeedFactor; if (gllsf * gllsf < distSqCentreToDest) { // destination is not near planet SphereClusters.RepulseSphere sphere = new SphereClusters.RepulseSphere() { Centre = centre, FixedRadius = maxRadius, VariableRadius = gravLimit - maxRadius + linearSpeedFactor }; sphere.SetEntity(entity); //Log.TraceLog("Far planet sphere: " + sphere); m_clusters.Add(ref sphere); } else { // destination is near planet, keep autopilot further from the planet based on speed and distance to destination SphereClusters.RepulseSphere sphere = new SphereClusters.RepulseSphere() { Centre = centre, FixedRadius = Math.Sqrt(distSqCentreToDest), VariableRadius = Math.Min(linearSpeedFactor + distAutopilotToFinalDest * 0.1f, distAutopilotToFinalDest * 0.25f) }; sphere.SetEntity(entity); //Log.TraceLog("Nearby planet sphere: " + sphere); m_clusters.Add(ref sphere); } } continue; } //boundingRadius += entity.PositionComp.LocalVolume.Radius; float fixedRadius = apRadius + entity.PositionComp.LocalVolume.Radius; if (distCentreToCurrent < fixedRadius + linearSpeedFactor) { // Entity is too close to autopilot for repulsion. float distBetween = (float)distCentreToCurrent - fixedRadius; if (distBetween < closestEntityDist) closestEntityDist = distBetween; AvoidEntity(entity); continue; } fixedRadius = Math.Min(fixedRadius * 4f, fixedRadius + 2000f); if (distSqCentreToDest < fixedRadius * fixedRadius) { if (distAutopilotToFinalDest < distCentreToCurrent) { // Entity is near destination and autopilot is nearing destination AvoidEntity(entity); continue; } double minGain = entity.PositionComp.LocalVolume.Radius; if (minGain <= 10d) minGain = 10d; if (distSqCentreToDest < minGain * minGain) { // Entity is too close to destination for cicling it to be much use AvoidEntity(entity); continue; } } if (calcRepulse) { SphereClusters.RepulseSphere sphere = new SphereClusters.RepulseSphere() { Centre = centre, FixedRadius = fixedRadius, VariableRadius = linearSpeedFactor }; sphere.SetEntity(entity); //Log.TraceLog("sphere: " + sphere); m_clusters.Add(ref sphere); } } NavSet.Settings_Task_NavWay.SpeedMaxRelative = Math.Max(closestEntityDist * Mover.DistanceSpeedFactor, 5f); // when following a path, only collect entites to avoid, do not repulse if (!calcRepulse) { Profiler.EndProfileBlock(); repulsion = Vector3.Zero; return; } m_clusters.AddMiddleSpheres(); //Log.DebugLog("repulsion spheres: " + m_clusters.Clusters.Count); repulsion = Vector3.Zero; for (int indexO = m_clusters.Clusters.Count - 1; indexO >= 0; indexO--) { List<SphereClusters.RepulseSphere> cluster = m_clusters.Clusters[indexO]; for (int indexI = cluster.Count - 1; indexI >= 0; indexI--) { SphereClusters.RepulseSphere sphere = cluster[indexI]; CalcRepulsion(ref sphere, ref repulsion); } } Profiler.EndProfileBlock(); } /// <summary> /// For most entities add it to m_entitiesPruneAvoid. For voxel set m_checkVoxel. /// </summary> /// <param name="entity">If it is a voxel, set m_checkVoxel = true, otherwise added to m_entitiesPruneAvoid.</param> private void AvoidEntity(MyEntity entity) { Log.TraceLog("Avoid: " + entity.nameWithId()); if (entity is MyVoxelBase) m_checkVoxel = true; else m_entitiesPruneAvoid.Add(entity); } /// <summary> /// Calculate repulsion for a specified sphere. /// </summary> /// <param name="sphere">The sphere which is repulsing the autopilot.</param> /// <param name="repulsion">Vector to which the repulsive force of sphere will be added.</param> private void CalcRepulsion(ref SphereClusters.RepulseSphere sphere, ref Vector3 repulsion) { Vector3D toCurrentD; Vector3D.Subtract(ref m_currentPosition, ref sphere.Centre, out toCurrentD); Vector3 toCurrent = toCurrentD; float toCurrentLenSq = toCurrent.LengthSquared(); float maxRepulseDist = (float)sphere.RepulseRadius; float maxRepulseDistSq = maxRepulseDist * maxRepulseDist; if (toCurrentLenSq > maxRepulseDistSq) { // Autopilot is outside the maximum bounds of repulsion. return; } float toCurrentLen = (float)Math.Sqrt(toCurrentLenSq); float repulseMagnitude = maxRepulseDist - toCurrentLen; Vector3 sphereRepulsion; Vector3.Multiply(ref toCurrent, repulseMagnitude / toCurrentLen, out sphereRepulsion); Log.TraceLog("repulsion of " + sphereRepulsion + " from sphere: " + sphere); repulsion.X += sphereRepulsion.X; repulsion.Y += sphereRepulsion.Y; repulsion.Z += sphereRepulsion.Z; } #endregion #region Obstruction Test /// <summary> /// For testing if the current path is obstructed by any entity in m_entitiesPruneAvoid. /// </summary> /// <param name="obstructingEntity">An entity that is blocking the current path.</param> /// <param name="obstructBlock">The block to report as blocking the path.</param> /// <param name="distance">Estimated distance along the path before encountering an obstruction.</param> /// <returns>True iff the current path is obstructed.</returns> private bool CurrentObstructed(out MyEntity obstructingEntity, out MyCubeBlock obstructBlock, out float distance) { //Log.DebugLog("m_moveDirection: " + m_moveDirection, Logger.severity.FATAL, condition: Math.Abs(m_moveDirection.LengthSquared() - 1f) > 0.01f); //Log.DebugLog("m_moveLength: " + m_moveLength, Logger.severity.FATAL, condition: Math.Abs(m_moveLength) < 0.1f); MyCubeBlock ignoreBlock = NavSet.Settings_Current.DestinationEntity as MyCubeBlock; // if destination is obstructing it needs to be checked first, so we would match speed with destination MyEntity destTop = GetTopMostDestEntity(); PathTester.TestInput input = new PathTester.TestInput() { Direction = m_moveDirection, Length = m_moveLength }; PathTester.TestInput adjustedInput; if (destTop != null && m_pickedDestination.Position != Vector3D.Zero && m_entitiesPruneAvoid.Contains(destTop)) { m_tester.AdjustForCurrentVelocity(ref input, out adjustedInput, destTop, true); if (adjustedInput.Length != 0f) { PathTester.GridTestResult result; if (m_tester.ObstructedBy(destTop, ignoreBlock, ref adjustedInput, out result)) { //Log.DebugLog("Obstructed by " + destTop.nameWithId() + "." + obstructBlock, Logger.severity.DEBUG); obstructingEntity = destTop; obstructBlock = result.ObstructingBlock; distance = result.Distance; return true; } } } // check voxel next so that the ship will not match an obstruction that is on a collision course if (m_checkVoxel) { //Log.DebugLog("raycasting voxels"); m_tester.AdjustForCurrentVelocity(ref input, out adjustedInput, null, false); if (adjustedInput.Length != 0f) { PathTester.VoxelTestResult voxelResult; if (m_tester.RayCastIntersectsVoxel(ref adjustedInput, out voxelResult)) { //Log.DebugLog("Obstructed by voxel " + hitVoxel + " at " + hitPosition+ ", autopilotVelocity: " + autopilotVelocity + ", m_moveDirection: " + m_moveDirection); obstructingEntity = voxelResult.ObstructingVoxel; obstructBlock = null; distance = voxelResult.Distance; return true; } } } // check remaining entities //Log.DebugLog("checking " + m_entitiesPruneAvoid.Count + " entites - destination entity - voxels"); if (m_entitiesPruneAvoid.Count != 0) for (int i = m_entitiesPruneAvoid.Count - 1; i >= 0; i--) { //Log.DebugLog("entity: " + m_entitiesPruneAvoid[i]); obstructingEntity = m_entitiesPruneAvoid[i]; if (obstructingEntity == destTop || obstructingEntity is MyVoxelBase) // already checked continue; m_tester.AdjustForCurrentVelocity(ref input, out adjustedInput, obstructingEntity, false); if (adjustedInput.Length != 0f) { PathTester.GridTestResult result; if (m_tester.ObstructedBy(obstructingEntity, ignoreBlock, ref adjustedInput, out result)) { //Log.DebugLog("Obstructed by " + obstructingEntity.nameWithId() + "." + obstructBlock, Logger.severity.DEBUG); obstructBlock = (MyCubeBlock)result.ObstructingBlock; distance = result.Distance; return true; } } } //Log.DebugLog("No obstruction"); obstructingEntity = null; obstructBlock = null; distance = 0f; return false; } #endregion #region Jump /// <summary> /// Attempt to jump the ship towards m_pickedDestination. /// </summary> /// <returns>True if the ship is going to jump.</returns> private bool TryJump() { if (Globals.UpdateCount < m_nextJumpAttempt) return false; m_nextJumpAttempt = Globals.UpdateCount + 100uL; if (NavSet.Settings_Current.MinDistToJump < MyGridJumpDriveSystem.MIN_JUMP_DISTANCE || NavSet.Settings_Current.Distance < NavSet.Settings_Current.MinDistToJump) { //Log.DebugLog("not allowed to jump, distance: " + NavSet.Settings_Current.Distance + ", min dist: " + NavSet.Settings_Current.MinDistToJump); JumpComplaint = InfoString.StringId_Jump.None; return false; } // search for a drive foreach (IMyCubeGrid grid in AttachedGrid.AttachedGrids(Mover.Block.CubeGrid, AttachedGrid.AttachmentKind.Terminal, true)) { CubeGridCache cache = CubeGridCache.GetFor(grid); if (cache == null) { Log.DebugLog("Missing a CubeGridCache"); return false; } foreach (MyJumpDrive jumpDrive in cache.BlocksOfType(typeof(MyObjectBuilder_JumpDrive))) if (jumpDrive.CanJumpAndHasAccess(Mover.Block.CubeBlock.OwnerId)) { m_nextJumpAttempt = Globals.UpdateCount + 1000uL; return RequestJump(); } } //Log.DebugLog("No usable jump drives", Logger.severity.TRACE); JumpComplaint = InfoString.StringId_Jump.NotCharged; return false; } /// <summary> /// Based on MyGridJumpDriveSystem.RequestJump. If the ship is allowed to jump, requests the jump system jump the ship. /// </summary> /// <returns>True if Pathfinder has requested a jump.</returns> private bool RequestJump() { MyCubeBlock apBlock = (MyCubeBlock)Mover.Block.CubeBlock; MyCubeGrid apGrid = apBlock.CubeGrid; if (!Vector3.IsZero(MyGravityProviderSystem.CalculateNaturalGravityInPoint(apGrid.WorldMatrix.Translation))) { //Log.DebugLog("Cannot jump, in gravity"); JumpComplaint = InfoString.StringId_Jump.InGravity; return false; } // check for static grids or grids already jumping foreach (MyCubeGrid grid in AttachedGrid.AttachedGrids(apGrid, AttachedGrid.AttachmentKind.Physics, true)) { if (grid.MarkedForClose) { Log.DebugLog("Cannot jump with closing grid: " + grid.nameWithId(), Logger.severity.WARNING); JumpComplaint = InfoString.StringId_Jump.ClosingGrid; return false; } if (grid.IsStatic) { Log.DebugLog("Cannot jump with static grid: " + grid.nameWithId(), Logger.severity.WARNING); JumpComplaint = InfoString.StringId_Jump.StaticGrid; return false; } if (grid.GridSystems.JumpSystem.GetJumpDriveDirection().HasValue) { Log.DebugLog("Cannot jump, grid already jumping: " + grid.nameWithId(), Logger.severity.WARNING); JumpComplaint = InfoString.StringId_Jump.AlreadyJumping; return false; } } Vector3D finalDest = m_pickedDestination.WorldPosition(); if (MySession.Static.Settings.WorldSizeKm > 0 && finalDest.Length() > MySession.Static.Settings.WorldSizeKm * 500) { Log.DebugLog("Cannot jump outside of world", Logger.severity.WARNING); JumpComplaint = InfoString.StringId_Jump.DestOutsideWorld; return false; } MyGridJumpDriveSystem jdSystem =apGrid.GridSystems.JumpSystem; Vector3D jumpDisp; Vector3D.Subtract(ref finalDest, ref m_currentPosition, out jumpDisp); // limit jump to maximum allowed by jump drive capacity double maxJumpDistance = jdSystem.GetMaxJumpDistance(apBlock.OwnerId); double jumpDistSq = jumpDisp.LengthSquared(); if (maxJumpDistance * maxJumpDistance < jumpDistSq) { Log.DebugLog("Jump drives do not have sufficient power to jump the desired distance", Logger.severity.DEBUG); Vector3D newJumpDisp; Vector3D.Multiply(ref jumpDisp, maxJumpDistance / Math.Sqrt(jumpDistSq), out newJumpDisp); jumpDisp = newJumpDisp; if (newJumpDisp.LengthSquared() < MyGridJumpDriveSystem.MIN_JUMP_DISTANCE * MyGridJumpDriveSystem.MIN_JUMP_DISTANCE) { Log.DebugLog("Jump drives do not have sufficient power to jump the minimum distance", Logger.severity.WARNING); JumpComplaint = InfoString.StringId_Jump.CannotJumpMin; return false; } } // limit jump based on obstruction m_lineSegment.From = m_currentPosition; m_lineSegment.To = finalDest; double apRadius = apGrid.PositionComp.LocalVolume.Radius; LineD line = m_lineSegment.Line; List<MyLineSegmentOverlapResult<MyEntity>> overlappingEntities; ResourcePool.Get(out overlappingEntities); MyGamePruningStructure.GetTopmostEntitiesOverlappingRay(ref line, overlappingEntities); MyLineSegmentOverlapResult<MyEntity> closest = new MyLineSegmentOverlapResult<MyEntity>() { Distance = double.MaxValue }; foreach (MyLineSegmentOverlapResult<MyEntity> overlap in overlappingEntities) { MyPlanet planet = overlap.Element as MyPlanet; if (planet != null) { BoundingSphereD gravSphere = new BoundingSphereD(planet.PositionComp.GetPosition(), planet.GetGravityLimit() + apRadius); double t1, t2; if (m_lineSegment.Intersects(ref gravSphere, out t1, out t2)) { if (t1 < closest.Distance) closest = new MyLineSegmentOverlapResult<MyEntity>() { Distance = t1, Element = planet }; } else { Log.DebugLog("planet gravity does not hit line: " + planet.getBestName()); continue; } } else { if (overlap.Element == apGrid) continue; if (overlap.Distance < closest.Distance) closest = overlap; } } overlappingEntities.Clear(); ResourcePool.Return(overlappingEntities); if (closest.Element != null) { Log.DebugLog("jump would hit: " + closest.Element.nameWithId() + ", shortening jump from " + m_lineSegment.Length + " to " + closest.Distance, Logger.severity.DEBUG); if (closest.Distance < MyGridJumpDriveSystem.MIN_JUMP_DISTANCE) { Log.DebugLog("Jump is obstructed", Logger.severity.DEBUG); JumpComplaint = InfoString.StringId_Jump.Obstructed; return false; } m_lineSegment.To = m_lineSegment.From + m_lineSegment.Direction * closest.Distance; } Log.DebugLog("Requesting jump to " + m_lineSegment.To, Logger.severity.DEBUG); JumpComplaint = InfoString.StringId_Jump.Jumping; // if jump fails after request, wait a long time before trying again m_nextJumpAttempt = 10000uL; Static.JumpDisplacement.SetValue(jdSystem, m_lineSegment.To - m_lineSegment.From); Static.RequestJump.Invoke(jdSystem, new object[] { m_lineSegment.To, apBlock.OwnerId }); m_jumpSystem = jdSystem; return true; } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) Under one or more * contributor license agreements. See the NOTICE file distributed with * this work for Additional information regarding copyright ownership. * The ASF licenses this file to You Under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed Under the License is distributed on an "AS Is" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations Under the License. */ /* * Created on May 8, 2005 * */ using NPOI.SS.Formula.Atp; namespace NPOI.SS.Formula.Eval { using System; using NPOI.SS.Formula.Functions; using NPOI.SS.Formula.Function; using System.Collections.Generic; using System.Collections.ObjectModel; /** * @author Amol S. Deshmukh &lt; amolweb at ya hoo dot com &gt; * */ public abstract class FunctionEval { /** * Some function IDs that require special treatment */ private class FunctionID { /** 1 */ public const int IF = FunctionMetadataRegistry.FUNCTION_INDEX_IF; public const int SUM = FunctionMetadataRegistry.FUNCTION_INDEX_SUM; /** 78 */ public const int OFFSET = 78; /** 100 */ public const int CHOOSE = FunctionMetadataRegistry.FUNCTION_INDEX_CHOOSE; /** 148 */ public const int INDIRECT = FunctionMetadataRegistry.FUNCTION_INDEX_INDIRECT; /** 255 */ public const int EXTERNAL_FUNC = FunctionMetadataRegistry.FUNCTION_INDEX_EXTERNAL; } public abstract Eval Evaluate(Eval[] evals, int srcCellRow, short srcCellCol); protected static Function[] functions = ProduceFunctions(); // fix warning CS0169 "never used": private static Hashtable freeRefFunctionsByIdMap; private static FunctionMetadataRegistry _instance; private static FunctionMetadataRegistry GetInstance() { if (_instance == null) { _instance = FunctionMetadataReader.CreateRegistry(); } return _instance; } public static Function GetBasicFunction(int functionIndex) { // check for 'free ref' functions first switch (functionIndex) { case FunctionID.INDIRECT: case FunctionID.EXTERNAL_FUNC: return null; } // else - must be plain function Function result = functions[functionIndex]; if (result == null) { throw new NotImplementedException("FuncIx=" + functionIndex); } return result; } private static Function[] ProduceFunctions() { Function[] retval = new Function[368]; retval[0] = new Count(); // COUNT retval[FunctionID.IF] = new If(); // IF retval[2] = LogicalFunction.ISNA; // IsNA retval[3] = LogicalFunction.ISERROR; // IsERROR retval[FunctionID.SUM] = AggregateFunction.SUM; // SUM retval[5] = AggregateFunction.AVERAGE; // AVERAGE retval[6] = AggregateFunction.MIN; // MIN retval[7] = AggregateFunction.MAX; // MAX retval[8] = new Row(); // ROW retval[9] = new Column(); // COLUMN retval[10] = new Na(); // NA retval[11] = new Npv(); // NPV retval[12] = AggregateFunction.STDEV; // STDEV retval[13] = NumericFunction.DOLLAR; // DOLLAR retval[14] = new NotImplementedFunction("FIXED"); // FIXED retval[15] = NumericFunction.SIN; // SIN retval[16] = NumericFunction.COS; // COS retval[17] = NumericFunction.TAN; // TAN retval[18] = NumericFunction.ATAN; // ATAN retval[19] = new Pi(); // PI retval[20] = NumericFunction.SQRT; // SQRT retval[21] = NumericFunction.EXP; // EXP retval[22] = NumericFunction.LN; // LN retval[23] = NumericFunction.LOG10; // LOG10 retval[24] = NumericFunction.ABS; // ABS retval[25] = NumericFunction.INT; // INT retval[26] = NumericFunction.SIGN; // SIGN retval[27] = NumericFunction.ROUND; // ROUND retval[28] = new Lookup(); // LOOKUP retval[29] = new Index(); // INDEX retval[30] = new NotImplementedFunction("REPT"); // REPT retval[31] = TextFunction.MID; // MID retval[32] = TextFunction.LEN; // LEN retval[33] = new Value(); // VALUE retval[34] = new True(); // TRUE retval[35] = new False(); // FALSE retval[36] = new And(); // AND retval[37] = new Or(); // OR retval[38] = new Not(); // NOT retval[39] = NumericFunction.MOD; // MOD retval[40] = new NotImplementedFunction("DCOUNT"); // DCOUNT retval[41] = new NotImplementedFunction("DSUM"); // DSUM retval[42] = new NotImplementedFunction("DAVERAGE"); // DAVERAGE retval[43] = new NotImplementedFunction("DMIN"); // DMIN retval[44] = new NotImplementedFunction("DMAX"); // DMAX retval[45] = new NotImplementedFunction("DSTDEV"); // DSTDEV retval[46] = AggregateFunction.VAR; // VAR retval[47] = new NotImplementedFunction("DVAR"); // DVAR retval[48] = TextFunction.TEXT; // TEXT retval[49] = new NotImplementedFunction("LINEST"); // LINEST retval[50] = new NotImplementedFunction("TREND"); // TREND retval[51] = new NotImplementedFunction("LOGEST"); // LOGEST retval[52] = new NotImplementedFunction("GROWTH"); // GROWTH retval[53] = new NotImplementedFunction("GOTO"); // GOTO retval[54] = new NotImplementedFunction("HALT"); // HALT retval[56] = FinanceFunction.PV; // PV retval[57] = FinanceFunction.FV; // FV retval[58] = FinanceFunction.NPER; // NPER retval[59] = FinanceFunction.PMT; // PMT retval[60] = new Rate(); // RATE retval[61] = new NotImplementedFunction("MIRR"); // MIRR retval[62] = new Irr(); // IRR retval[63] = new Rand(); // RAND retval[64] = new Match(); // MATCH retval[65] = DateFunc.instance; // DATE retval[66] = new TimeFunc(); // TIME retval[67] = CalendarFieldFunction.DAY; // DAY retval[68] = CalendarFieldFunction.MONTH; // MONTH retval[69] = CalendarFieldFunction.YEAR; // YEAR retval[70] = WeekdayFunc.instance; // WEEKDAY retval[71] = CalendarFieldFunction.HOUR; retval[72] = CalendarFieldFunction.MINUTE; retval[73] = CalendarFieldFunction.SECOND; retval[74] = new Now(); retval[75] = new NotImplementedFunction("AREAS"); // AREAS retval[76] = new Rows(); // ROWS retval[77] = new Columns(); // COLUMNS retval[FunctionID.OFFSET] = new Offset(); // Offset.Evaluate has a different signature retval[79] = new NotImplementedFunction("ABSREF"); // ABSREF retval[80] = new NotImplementedFunction("RELREF"); // RELREF retval[81] = new NotImplementedFunction("ARGUMENT"); // ARGUMENT retval[82] = TextFunction.SEARCH; retval[83] = new NotImplementedFunction("TRANSPOSE"); // TRANSPOSE retval[84] = new NotImplementedFunction("ERROR"); // ERROR retval[85] = new NotImplementedFunction("STEP"); // STEP retval[86] = new NotImplementedFunction("TYPE"); // TYPE retval[87] = new NotImplementedFunction("ECHO"); // ECHO retval[88] = new NotImplementedFunction("SetNAME"); // SetNAME retval[89] = new NotImplementedFunction("CALLER"); // CALLER retval[90] = new NotImplementedFunction("DEREF"); // DEREF retval[91] = new NotImplementedFunction("WINDOWS"); // WINDOWS retval[92] = new NotImplementedFunction("SERIES"); // SERIES retval[93] = new NotImplementedFunction("DOCUMENTS"); // DOCUMENTS retval[94] = new NotImplementedFunction("ACTIVECELL"); // ACTIVECELL retval[95] = new NotImplementedFunction("SELECTION"); // SELECTION retval[96] = new NotImplementedFunction("RESULT"); // RESULT retval[97] = NumericFunction.ATAN2; // ATAN2 retval[98] = NumericFunction.ASIN; // ASIN retval[99] = NumericFunction.ACOS; // ACOS retval[FunctionID.CHOOSE] = new Choose(); retval[101] = new Hlookup(); // HLOOKUP retval[102] = new Vlookup(); // VLOOKUP retval[103] = new NotImplementedFunction("LINKS"); // LINKS retval[104] = new NotImplementedFunction("INPUT"); // INPUT retval[105] = LogicalFunction.ISREF; // IsREF retval[106] = new NotImplementedFunction("GetFORMULA"); // GetFORMULA retval[107] = new NotImplementedFunction("GetNAME"); // GetNAME retval[108] = new NotImplementedFunction("SetVALUE"); // SetVALUE retval[109] = NumericFunction.LOG; // LOG retval[110] = new NotImplementedFunction("EXEC"); // EXEC retval[111] = TextFunction.CHAR; // CHAR retval[112] = TextFunction.LOWER; // LOWER retval[113] = TextFunction.UPPER; // UPPER retval[114] = new NotImplementedFunction("PROPER"); // PROPER retval[115] = TextFunction.LEFT; // LEFT retval[116] = TextFunction.RIGHT; // RIGHT retval[117] = TextFunction.EXACT; // EXACT retval[118] = TextFunction.TRIM; // TRIM retval[119] = new Replace(); // Replace retval[120] = new Substitute(); // SUBSTITUTE retval[121] = new NotImplementedFunction("CODE"); // CODE retval[122] = new NotImplementedFunction("NAMES"); // NAMES retval[123] = new NotImplementedFunction("DIRECTORY"); // DIRECTORY retval[124] = TextFunction.FIND; // Find retval[125] = new NotImplementedFunction("CELL"); // CELL retval[126] = LogicalFunction.ISERR; // IsERR retval[127] = LogicalFunction.ISTEXT; // IsTEXT retval[128] = LogicalFunction.ISNUMBER; // IsNUMBER retval[129] = LogicalFunction.ISBLANK; // IsBLANK retval[130] = new T(); // T retval[131] = new NotImplementedFunction("N"); // N retval[132] = new NotImplementedFunction("FOPEN"); // FOPEN retval[133] = new NotImplementedFunction("FCLOSE"); // FCLOSE retval[134] = new NotImplementedFunction("FSIZE"); // FSIZE retval[135] = new NotImplementedFunction("FReadLN"); // FReadLN retval[136] = new NotImplementedFunction("FRead"); // FRead retval[137] = new NotImplementedFunction("FWriteLN"); // FWriteLN retval[138] = new NotImplementedFunction("FWrite"); // FWrite retval[139] = new NotImplementedFunction("FPOS"); // FPOS retval[140] = new NotImplementedFunction("DATEVALUE"); // DATEVALUE retval[141] = new NotImplementedFunction("TIMEVALUE"); // TIMEVALUE retval[142] = new NotImplementedFunction("SLN"); // SLN retval[143] = new NotImplementedFunction("SYD"); // SYD retval[144] = new NotImplementedFunction("DDB"); // DDB retval[145] = new NotImplementedFunction("GetDEF"); // GetDEF retval[146] = new NotImplementedFunction("REFTEXT"); // REFTEXT retval[147] = new NotImplementedFunction("TEXTREF"); // TEXTREF retval[FunctionID.INDIRECT] = null; // Indirect.Evaluate has different signature retval[149] = new NotImplementedFunction("REGISTER"); // REGISTER retval[150] = new NotImplementedFunction("CALL"); // CALL retval[151] = new NotImplementedFunction("AddBAR"); // AddBAR retval[152] = new NotImplementedFunction("AddMENU"); // AddMENU retval[153] = new NotImplementedFunction("AddCOMMAND"); // AddCOMMAND retval[154] = new NotImplementedFunction("ENABLECOMMAND"); // ENABLECOMMAND retval[155] = new NotImplementedFunction("CHECKCOMMAND"); // CHECKCOMMAND retval[156] = new NotImplementedFunction("RenameCOMMAND"); // RenameCOMMAND retval[157] = new NotImplementedFunction("SHOWBAR"); // SHOWBAR retval[158] = new NotImplementedFunction("DELETEMENU"); // DELETEMENU retval[159] = new NotImplementedFunction("DELETECOMMAND"); // DELETECOMMAND retval[160] = new NotImplementedFunction("GetCHARTITEM"); // GetCHARTITEM retval[161] = new NotImplementedFunction("DIALOGBOX"); // DIALOGBOX retval[162] = TextFunction.CLEAN; // CLEAN retval[163] = new NotImplementedFunction("MDETERM"); // MDETERM retval[164] = new NotImplementedFunction("MINVERSE"); // MINVERSE retval[165] = new NotImplementedFunction("MMULT"); // MMULT retval[166] = new NotImplementedFunction("FILES"); // FILES retval[167] = new NotImplementedFunction("IPMT"); // IPMT retval[168] = new NotImplementedFunction("PPMT"); // PPMT retval[169] = new Counta(); // COUNTA retval[170] = new NotImplementedFunction("CANCELKEY"); // CANCELKEY retval[175] = new NotImplementedFunction("INITIATE"); // INITIATE retval[176] = new NotImplementedFunction("REQUEST"); // REQUEST retval[177] = new NotImplementedFunction("POKE"); // POKE retval[178] = new NotImplementedFunction("EXECUTE"); // EXECUTE retval[179] = new NotImplementedFunction("TERMINATE"); // TERMINATE retval[180] = new NotImplementedFunction("RESTART"); // RESTART retval[181] = new NotImplementedFunction("HELP"); // HELP retval[182] = new NotImplementedFunction("GetBAR"); // GetBAR retval[183] = AggregateFunction.PRODUCT; // PRODUCT retval[184] = NumericFunction.FACT; // FACT retval[185] = new NotImplementedFunction("GetCELL"); // GetCELL retval[186] = new NotImplementedFunction("GetWORKSPACE"); // GetWORKSPACE retval[187] = new NotImplementedFunction("GetWINDOW"); // GetWINDOW retval[188] = new NotImplementedFunction("GetDOCUMENT"); // GetDOCUMENT retval[189] = new NotImplementedFunction("DPRODUCT"); // DPRODUCT retval[190] = LogicalFunction.ISNONTEXT; // IsNONTEXT retval[191] = new NotImplementedFunction("GetNOTE"); // GetNOTE retval[192] = new NotImplementedFunction("NOTE"); // NOTE retval[193] = new NotImplementedFunction("STDEVP"); // STDEVP retval[194] = AggregateFunction.VARP; // VARP retval[195] = new NotImplementedFunction("DSTDEVP"); // DSTDEVP retval[196] = new NotImplementedFunction("DVARP"); // DVARP retval[197] = NumericFunction.TRUNC; // TRUNC retval[198] = LogicalFunction.ISLOGICAL; // IsLOGICAL retval[199] = new NotImplementedFunction("DCOUNTA"); // DCOUNTA retval[200] = new NotImplementedFunction("DELETEBAR"); // DELETEBAR retval[201] = new NotImplementedFunction("UNREGISTER"); // UNREGISTER retval[204] = new NotImplementedFunction("USDOLLAR"); // USDOLLAR retval[205] = new NotImplementedFunction("FindB"); // FindB retval[206] = new NotImplementedFunction("SEARCHB"); // SEARCHB retval[207] = new NotImplementedFunction("ReplaceB"); // ReplaceB retval[208] = new NotImplementedFunction("LEFTB"); // LEFTB retval[209] = new NotImplementedFunction("RIGHTB"); // RIGHTB retval[210] = new NotImplementedFunction("MIDB"); // MIDB retval[211] = new NotImplementedFunction("LENB"); // LENB retval[212] = NumericFunction.ROUNDUP; // ROUNDUP retval[213] = NumericFunction.ROUNDDOWN; // ROUNDDOWN retval[214] = new NotImplementedFunction("ASC"); // ASC retval[215] = new NotImplementedFunction("DBCS"); // DBCS retval[216] = new Rank(); // RANK retval[219] = new Address(); // AddRESS retval[220] = new Days360(); // DAYS360 retval[221] = new Today(); // TODAY retval[222] = new NotImplementedFunction("VDB"); // VDB retval[227] = AggregateFunction.MEDIAN; // MEDIAN retval[228] = new Sumproduct(); // SUMPRODUCT retval[229] = NumericFunction.SINH; // SINH retval[230] = NumericFunction.COSH; // COSH retval[231] = NumericFunction.TANH; // TANH retval[232] = NumericFunction.ASINH; // ASINH retval[233] = NumericFunction.ACOSH; // ACOSH retval[234] = NumericFunction.ATANH; // ATANH retval[235] = new NotImplementedFunction("DGet"); // DGet retval[236] = new NotImplementedFunction("CreateOBJECT"); // CreateOBJECT retval[237] = new NotImplementedFunction("VOLATILE"); // VOLATILE retval[238] = new NotImplementedFunction("LASTERROR"); // LASTERROR retval[239] = new NotImplementedFunction("CUSTOMUNDO"); // CUSTOMUNDO retval[240] = new NotImplementedFunction("CUSTOMREPEAT"); // CUSTOMREPEAT retval[241] = new NotImplementedFunction("FORMULAConvert"); // FORMULAConvert retval[242] = new NotImplementedFunction("GetLINKINFO"); // GetLINKINFO retval[243] = new NotImplementedFunction("TEXTBOX"); // TEXTBOX retval[244] = new NotImplementedFunction("INFO"); // INFO retval[245] = new NotImplementedFunction("GROUP"); // GROUP retval[246] = new NotImplementedFunction("GetOBJECT"); // GetOBJECT retval[247] = new NotImplementedFunction("DB"); // DB retval[248] = new NotImplementedFunction("PAUSE"); // PAUSE retval[250] = new NotImplementedFunction("RESUME"); // RESUME retval[252] = new NotImplementedFunction("FREQUENCY"); // FREQUENCY retval[253] = new NotImplementedFunction("AddTOOLBAR"); // AddTOOLBAR retval[254] = new NotImplementedFunction("DELETETOOLBAR"); // DELETETOOLBAR retval[FunctionID.EXTERNAL_FUNC] = null; // ExternalFunction is a FreeREfFunction retval[256] = new NotImplementedFunction("RESetTOOLBAR"); // RESetTOOLBAR retval[257] = new NotImplementedFunction("EVALUATE"); // EVALUATE retval[258] = new NotImplementedFunction("GetTOOLBAR"); // GetTOOLBAR retval[259] = new NotImplementedFunction("GetTOOL"); // GetTOOL retval[260] = new NotImplementedFunction("SPELLINGCHECK"); // SPELLINGCHECK retval[261] = new Errortype(); // ERRORTYPE retval[262] = new NotImplementedFunction("APPTITLE"); // APPTITLE retval[263] = new NotImplementedFunction("WINDOWTITLE"); // WINDOWTITLE retval[264] = new NotImplementedFunction("SAVETOOLBAR"); // SAVETOOLBAR retval[265] = new NotImplementedFunction("ENABLETOOL"); // ENABLETOOL retval[266] = new NotImplementedFunction("PRESSTOOL"); // PRESSTOOL retval[267] = new NotImplementedFunction("REGISTERID"); // REGISTERID retval[268] = new NotImplementedFunction("GetWORKBOOK"); // GetWORKBOOK retval[269] = AggregateFunction.AVEDEV; // AVEDEV retval[270] = new NotImplementedFunction("BETADIST"); // BETADIST retval[271] = new NotImplementedFunction("GAMMALN"); // GAMMALN retval[272] = new NotImplementedFunction("BETAINV"); // BETAINV retval[273] = new NotImplementedFunction("BINOMDIST"); // BINOMDIST retval[274] = new NotImplementedFunction("CHIDIST"); // CHIDIST retval[275] = new NotImplementedFunction("CHIINV"); // CHIINV retval[276] = NumericFunction.COMBIN; // COMBIN retval[277] = new NotImplementedFunction("CONFIDENCE"); // CONFIDENCE retval[278] = new NotImplementedFunction("CRITBINOM"); // CRITBINOM retval[279] = new Even(); // EVEN retval[280] = new NotImplementedFunction("EXPONDIST"); // EXPONDIST retval[281] = new NotImplementedFunction("FDIST"); // FDIST retval[282] = new NotImplementedFunction("FINV"); // FINV retval[283] = new NotImplementedFunction("FISHER"); // FISHER retval[284] = new NotImplementedFunction("FISHERINV"); // FISHERINV retval[285] = NumericFunction.FLOOR; // FLOOR retval[286] = new NotImplementedFunction("GAMMADIST"); // GAMMADIST retval[287] = new NotImplementedFunction("GAMMAINV"); // GAMMAINV retval[288] = NumericFunction.CEILING; // CEILING retval[289] = new NotImplementedFunction("HYPGEOMDIST"); // HYPGEOMDIST retval[290] = new NotImplementedFunction("LOGNORMDIST"); // LOGNORMDIST retval[291] = new NotImplementedFunction("LOGINV"); // LOGINV retval[292] = new NotImplementedFunction("NEGBINOMDIST"); // NEGBINOMDIST retval[293] = new NotImplementedFunction("NORMDIST"); // NORMDIST retval[294] = new NotImplementedFunction("NORMSDIST"); // NORMSDIST retval[295] = new NotImplementedFunction("NORMINV"); // NORMINV retval[296] = new NotImplementedFunction("NORMSINV"); // NORMSINV retval[297] = new NotImplementedFunction("STANDARDIZE"); // STANDARDIZE retval[298] = new Odd(); // ODD retval[299] = new NotImplementedFunction("PERMUT"); // PERMUT retval[300] = NumericFunction.POISSON; // POISSON retval[301] = new NotImplementedFunction("TDIST"); // TDIST retval[302] = new NotImplementedFunction("WEIBULL"); // WEIBULL retval[303] = new Sumxmy2(); // SUMXMY2 retval[304] = new Sumx2my2(); // SUMX2MY2 retval[305] = new Sumx2py2(); // SUMX2PY2 retval[306] = new NotImplementedFunction("CHITEST"); // CHITEST retval[307] = new NotImplementedFunction("CORREL"); // CORREL retval[308] = new NotImplementedFunction("COVAR"); // COVAR retval[309] = new NotImplementedFunction("FORECAST"); // FORECAST retval[310] = new NotImplementedFunction("FTEST"); // FTEST retval[311] = new NotImplementedFunction("INTERCEPT"); // INTERCEPT retval[312] = new NotImplementedFunction("PEARSON"); // PEARSON retval[313] = new NotImplementedFunction("RSQ"); // RSQ retval[314] = new NotImplementedFunction("STEYX"); // STEYX retval[315] = new NotImplementedFunction("SLOPE"); // SLOPE retval[316] = new NotImplementedFunction("TTEST"); // TTEST retval[317] = new NotImplementedFunction("PROB"); // PROB retval[318] = AggregateFunction.DEVSQ; // DEVSQ retval[319] = new NotImplementedFunction("GEOMEAN"); // GEOMEAN retval[320] = new NotImplementedFunction("HARMEAN"); // HARMEAN retval[321] = AggregateFunction.SUMSQ; // SUMSQ retval[322] = new NotImplementedFunction("KURT"); // KURT retval[323] = new NotImplementedFunction("SKEW"); // SKEW retval[324] = new NotImplementedFunction("ZTEST"); // ZTEST retval[325] = AggregateFunction.LARGE; // LARGE retval[326] = AggregateFunction.SMALL; // SMALL retval[327] = new NotImplementedFunction("QUARTILE"); // QUARTILE retval[328] = new NotImplementedFunction("PERCENTILE"); // PERCENTILE retval[329] = new NotImplementedFunction("PERCENTRANK"); // PERCENTRANK retval[330] = new Mode(); // MODE retval[331] = new NotImplementedFunction("TRIMMEAN"); // TRIMMEAN retval[332] = new NotImplementedFunction("TINV"); // TINV retval[334] = new NotImplementedFunction("MOVIECOMMAND"); // MOVIECOMMAND retval[335] = new NotImplementedFunction("GetMOVIE"); // GetMOVIE retval[336] = TextFunction.CONCATENATE; // CONCATENATE retval[337] = NumericFunction.POWER; // POWER retval[338] = new NotImplementedFunction("PIVOTAddDATA"); // PIVOTAddDATA retval[339] = new NotImplementedFunction("GetPIVOTTABLE"); // GetPIVOTTABLE retval[340] = new NotImplementedFunction("GetPIVOTFIELD"); // GetPIVOTFIELD retval[341] = new NotImplementedFunction("GetPIVOTITEM"); // GetPIVOTITEM retval[342] = NumericFunction.RADIANS; ; // RADIANS retval[343] = NumericFunction.DEGREES; // DEGREES retval[344] = new Subtotal(); // SUBTOTAL retval[345] = new Sumif(); // SUMIF retval[346] = new Countif(); // COUNTIF retval[347] = new Countblank(); // COUNTBLANK retval[348] = new NotImplementedFunction("SCENARIOGet"); // SCENARIOGet retval[349] = new NotImplementedFunction("OPTIONSLISTSGet"); // OPTIONSLISTSGet retval[350] = new NotImplementedFunction("IsPMT"); // IsPMT retval[351] = new NotImplementedFunction("DATEDIF"); // DATEDIF retval[352] = new NotImplementedFunction("DATESTRING"); // DATESTRING retval[353] = new NotImplementedFunction("NUMBERSTRING"); // NUMBERSTRING retval[354] = new NotImplementedFunction("ROMAN"); // ROMAN retval[355] = new NotImplementedFunction("OPENDIALOG"); // OPENDIALOG retval[356] = new NotImplementedFunction("SAVEDIALOG"); // SAVEDIALOG retval[357] = new NotImplementedFunction("VIEWGet"); // VIEWGet retval[358] = new NotImplementedFunction("GetPIVOTDATA"); // GetPIVOTDATA retval[359] = new Hyperlink(); // HYPERLINK retval[360] = new NotImplementedFunction("PHONETIC"); // PHONETIC retval[361] = new NotImplementedFunction("AVERAGEA"); // AVERAGEA retval[362] = new Maxa(); // MAXA retval[363] = new Mina(); // MINA retval[364] = new NotImplementedFunction("STDEVPA"); // STDEVPA retval[365] = new NotImplementedFunction("VARPA"); // VARPA retval[366] = new NotImplementedFunction("STDEVA"); // STDEVA retval[367] = new NotImplementedFunction("VARA"); // VARA return retval; } /** * Register a new function in runtime. * * @param name the function name * @param func the functoin to register * @throws ArgumentException if the function is unknown or already registered. * @since 3.8 beta6 */ public static void RegisterFunction(String name, Function func) { FunctionMetadata metaData = FunctionMetadataRegistry.GetFunctionByName(name); if (metaData == null) { if (AnalysisToolPak.IsATPFunction(name)) { throw new ArgumentException(name + " is a function from the Excel Analysis Toolpack. " + "Use AnalysisToolpack.RegisterFunction(String name, FreeRefFunction func) instead."); } else { throw new ArgumentException("Unknown function: " + name); } } int idx = metaData.Index; if (functions[idx] is NotImplementedFunction) { functions[idx] = func; } else { throw new ArgumentException("POI already implememts " + name + ". You cannot override POI's implementations of Excel functions"); } } /** * Returns a collection of function names implemented by POI. * * @return an array of supported functions * @since 3.8 beta6 */ public static ReadOnlyCollection<String> GetSupportedFunctionNames() { List<String> lst = new List<String>(); for (int i = 0; i < functions.Length; i++) { Function func = functions[i]; FunctionMetadata metaData = FunctionMetadataRegistry.GetFunctionByIndex(i); if (func != null && !(func is NotImplementedFunction)) { lst.Add(metaData.Name); } } lst.Add("INDIRECT"); // INDIRECT is a special case return lst.AsReadOnly(); // Collections.unmodifiableCollection(lst); } /** * Returns an array of function names NOT implemented by POI. * * @return an array of not supported functions * @since 3.8 beta6 */ public static ReadOnlyCollection<String> GetNotSupportedFunctionNames() { List<String> lst = new List<String>(); for (int i = 0; i < functions.Length; i++) { Function func = functions[i]; if (func != null && (func is NotImplementedFunction)) { FunctionMetadata metaData = FunctionMetadataRegistry.GetFunctionByIndex(i); lst.Add(metaData.Name); } } lst.Remove("INDIRECT"); // INDIRECT is a special case return lst.AsReadOnly(); // Collections.unmodifiableCollection(lst); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Automation.Peers.DateTimeAutomationPeer.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Automation.Peers { sealed public partial class DateTimeAutomationPeer : AutomationPeer, System.Windows.Automation.Provider.ISelectionItemProvider, System.Windows.Automation.Provider.ITableItemProvider, System.Windows.Automation.Provider.IGridItemProvider, System.Windows.Automation.Provider.IInvokeProvider, System.Windows.Automation.Provider.IVirtualizedItemProvider { #region Methods and constructors internal DateTimeAutomationPeer() { } protected override string GetAcceleratorKeyCore() { return default(string); } protected override string GetAccessKeyCore() { return default(string); } protected override AutomationControlType GetAutomationControlTypeCore() { return default(AutomationControlType); } protected override string GetAutomationIdCore() { return default(string); } protected override System.Windows.Rect GetBoundingRectangleCore() { return default(System.Windows.Rect); } protected override List<AutomationPeer> GetChildrenCore() { return default(List<AutomationPeer>); } protected override string GetClassNameCore() { return default(string); } protected override System.Windows.Point GetClickablePointCore() { return default(System.Windows.Point); } protected override string GetHelpTextCore() { return default(string); } protected override string GetItemStatusCore() { return default(string); } protected override string GetItemTypeCore() { return default(string); } protected override AutomationPeer GetLabeledByCore() { return default(AutomationPeer); } protected override string GetLocalizedControlTypeCore() { return default(string); } protected override string GetNameCore() { return default(string); } protected override AutomationOrientation GetOrientationCore() { return default(AutomationOrientation); } public override Object GetPattern(PatternInterface patternInterface) { return default(Object); } protected override bool HasKeyboardFocusCore() { return default(bool); } protected override bool IsContentElementCore() { return default(bool); } protected override bool IsControlElementCore() { return default(bool); } protected override bool IsEnabledCore() { return default(bool); } protected override bool IsKeyboardFocusableCore() { return default(bool); } protected override bool IsOffscreenCore() { return default(bool); } protected override bool IsPasswordCore() { return default(bool); } protected override bool IsRequiredForFormCore() { return default(bool); } protected override void SetFocusCore() { } void System.Windows.Automation.Provider.IInvokeProvider.Invoke() { } void System.Windows.Automation.Provider.ISelectionItemProvider.AddToSelection() { } void System.Windows.Automation.Provider.ISelectionItemProvider.RemoveFromSelection() { } void System.Windows.Automation.Provider.ISelectionItemProvider.Select() { } System.Windows.Automation.Provider.IRawElementProviderSimple[] System.Windows.Automation.Provider.ITableItemProvider.GetColumnHeaderItems() { return default(System.Windows.Automation.Provider.IRawElementProviderSimple[]); } System.Windows.Automation.Provider.IRawElementProviderSimple[] System.Windows.Automation.Provider.ITableItemProvider.GetRowHeaderItems() { return default(System.Windows.Automation.Provider.IRawElementProviderSimple[]); } void System.Windows.Automation.Provider.IVirtualizedItemProvider.Realize() { } #endregion #region Properties and indexers int System.Windows.Automation.Provider.IGridItemProvider.Column { get { return default(int); } } int System.Windows.Automation.Provider.IGridItemProvider.ColumnSpan { get { return default(int); } } System.Windows.Automation.Provider.IRawElementProviderSimple System.Windows.Automation.Provider.IGridItemProvider.ContainingGrid { get { return default(System.Windows.Automation.Provider.IRawElementProviderSimple); } } int System.Windows.Automation.Provider.IGridItemProvider.Row { get { return default(int); } } int System.Windows.Automation.Provider.IGridItemProvider.RowSpan { get { return default(int); } } bool System.Windows.Automation.Provider.ISelectionItemProvider.IsSelected { get { return default(bool); } } System.Windows.Automation.Provider.IRawElementProviderSimple System.Windows.Automation.Provider.ISelectionItemProvider.SelectionContainer { get { return default(System.Windows.Automation.Provider.IRawElementProviderSimple); } } #endregion } }
// // NativeDapiProtection.cs - // Protect (encrypt) data without (user involved) key management // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2005 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. // #if NET_2_0 using System; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; namespace Mono.Security.Cryptography { // DAPI is only available in Windows 2000 and later operating systems // see ManagedProtection for other platforms // notes: // * no need to assert KeyContainerPermission here as unmanaged code can // do what it wants; // * which is why we also need the [SuppressUnmanagedCodeSecurity] // attribute on each native function (so we don't require UnmanagedCode) internal class NativeDapiProtection { private const uint CRYPTPROTECT_UI_FORBIDDEN = 0x1; private const uint CRYPTPROTECT_LOCAL_MACHINE = 0x4; [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Auto)] private struct DATA_BLOB { private int cbData; private IntPtr pbData; public void Alloc (int size) { if (size > 0) { pbData = Marshal.AllocHGlobal (size); cbData = size; } } public void Alloc (byte[] managedMemory) { if (managedMemory != null) { int size = managedMemory.Length; pbData = Marshal.AllocHGlobal (size); cbData = size; Marshal.Copy (managedMemory, 0, pbData, cbData); } } public void Free () { if (pbData != IntPtr.Zero) { // clear copied memory! ZeroMemory (pbData, cbData); Marshal.FreeHGlobal (pbData); pbData = IntPtr.Zero; cbData = 0; } } public byte[] ToBytes () { if (cbData <= 0) return new byte [0]; byte[] managedMemory = new byte[cbData]; Marshal.Copy (pbData, managedMemory, 0, cbData); return managedMemory; } } [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Auto)] private struct CRYPTPROTECT_PROMPTSTRUCT { private int cbSize; private uint dwPromptFlags; private IntPtr hwndApp; private string szPrompt; public CRYPTPROTECT_PROMPTSTRUCT (uint flags) { cbSize = Marshal.SizeOf (typeof (CRYPTPROTECT_PROMPTSTRUCT)); dwPromptFlags = flags; hwndApp = IntPtr.Zero; szPrompt = null; } } // http://msdn.microsoft.com/library/en-us/seccrypto/security/cryptprotectdata.asp [SuppressUnmanagedCodeSecurity] [DllImport ("crypt32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)] private static extern bool CryptProtectData (ref DATA_BLOB pDataIn, string szDataDescr, ref DATA_BLOB pOptionalEntropy, IntPtr pvReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct, uint dwFlags, ref DATA_BLOB pDataOut); // http://msdn.microsoft.com/library/en-us/seccrypto/security/cryptunprotectdata.asp [SuppressUnmanagedCodeSecurity] [DllImport ("crypt32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)] private static extern bool CryptUnprotectData (ref DATA_BLOB pDataIn, string szDataDescr, ref DATA_BLOB pOptionalEntropy, IntPtr pvReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct, uint dwFlags, ref DATA_BLOB pDataOut); // http://msdn.microsoft.com/library/en-us/memory/base/zeromemory.asp // note: SecureZeroMemory is an inline function (and can't be used here) // anyway I don't think the CLR will optimize this call away (like a C/C++ compiler could do) [SuppressUnmanagedCodeSecurity] [DllImport ("kernel32.dll", EntryPoint = "RtlZeroMemory", SetLastError = false, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)] private static extern void ZeroMemory (IntPtr dest, int size); // managed helpers public static byte[] Protect (byte[] userData, byte[] optionalEntropy, DataProtectionScope scope) { byte[] encdata = null; int hr = 0; DATA_BLOB data = new DATA_BLOB (); DATA_BLOB entropy = new DATA_BLOB (); DATA_BLOB cipher = new DATA_BLOB (); try { CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT (0); data.Alloc (userData); entropy.Alloc (optionalEntropy); // note: the scope/flags has already been check by the public caller uint flags = CRYPTPROTECT_UI_FORBIDDEN; if (scope == DataProtectionScope.LocalMachine) flags |= CRYPTPROTECT_LOCAL_MACHINE; // note: on Windows 2000 the string parameter *cannot* be null if (CryptProtectData (ref data, String.Empty, ref entropy, IntPtr.Zero, ref prompt, flags, ref cipher)) { // copy encrypted data back to managed codde encdata = cipher.ToBytes (); } else { hr = Marshal.GetLastWin32Error (); } } catch (Exception ex) { string msg = Locale.GetText ("Error protecting data."); throw new CryptographicException (msg, ex); } finally { cipher.Free (); data.Free (); entropy.Free (); } if ((encdata == null) || (hr != 0)) { throw new CryptographicException (hr); } return encdata; } public static byte[] Unprotect (byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope) { byte[] decdata = null; int hr = 0; DATA_BLOB cipher = new DATA_BLOB (); DATA_BLOB entropy = new DATA_BLOB (); DATA_BLOB data = new DATA_BLOB (); try { CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT (0); cipher.Alloc (encryptedData); entropy.Alloc (optionalEntropy); // note: the scope/flags has already been check by the public caller uint flags = CRYPTPROTECT_UI_FORBIDDEN; if (scope == DataProtectionScope.LocalMachine) flags |= CRYPTPROTECT_LOCAL_MACHINE; if (CryptUnprotectData (ref cipher, null, ref entropy, IntPtr.Zero, ref prompt, flags, ref data)) { // copy decrypted data back to managed codde decdata = data.ToBytes (); } else { hr = Marshal.GetLastWin32Error (); } } catch (Exception ex) { string msg = Locale.GetText ("Error protecting data."); throw new CryptographicException (msg, ex); } finally { cipher.Free (); data.Free (); entropy.Free (); } if ((decdata == null) || (hr != 0)) { throw new CryptographicException (hr); } return decdata; } } } #endif
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- //------------------------------------------------------------------------------ // Shape Editor //------------------------------------------------------------------------------ function initializeShapeEditor() { echo(" % - Initializing Shape Editor"); exec("./gui/Profiles.ed.cs"); exec("./gui/shapeEdPreviewWindow.ed.gui"); exec("./gui/shapeEdAnimWindow.ed.gui"); exec("./gui/shapeEdAdvancedWindow.ed.gui"); exec("./gui/ShapeEditorToolbar.ed.gui"); exec("./gui/shapeEdSelectWindow.ed.gui"); exec("./gui/shapeEdPropWindow.ed.gui"); exec("./scripts/shapeEditor.ed.cs"); exec("./scripts/shapeEditorHints.ed.cs"); exec("./scripts/shapeEditorActions.ed.cs"); // Add windows to editor gui ShapeEdPreviewGui.setVisible(false); ShapeEdAnimWindow.setVisible(false); ShapeEditorToolbar.setVisible(false); ShapeEdSelectWindow.setVisible(false); ShapeEdPropWindow.setVisible(false); EditorGui.add(ShapeEdPreviewGui); EditorGui.add(ShapeEdAnimWindow); EditorGui.add(ShapeEdAdvancedWindow); EditorGui.add(ShapeEditorToolbar); EditorGui.add(ShapeEdSelectWindow); EditorGui.add(ShapeEdPropWindow); new ScriptObject(ShapeEditorPlugin) { superClass = "EditorPlugin"; editorGui = ShapeEdShapeView; }; %map = new ActionMap(); %map.bindCmd( keyboard, "escape", "ToolsToolbarArray->WorldEditorInspectorPalette.performClick();", "" ); %map.bindCmd( keyboard, "1", "ShapeEditorNoneModeBtn.performClick();", "" ); %map.bindCmd( keyboard, "2", "ShapeEditorMoveModeBtn.performClick();", "" ); %map.bindCmd( keyboard, "3", "ShapeEditorRotateModeBtn.performClick();", "" ); //%map.bindCmd( keyboard, "4", "ShapeEditorScaleModeBtn.performClick();", "" ); // not needed for the shape editor %map.bindCmd( keyboard, "n", "ShapeEditorToolbar->showNodes.performClick();", "" ); %map.bindCmd( keyboard, "t", "ShapeEditorToolbar->ghostMode.performClick();", "" ); %map.bindCmd( keyboard, "r", "ShapeEditorToolbar->wireframeMode.performClick();", "" ); %map.bindCmd( keyboard, "f", "ShapeEditorToolbar->fitToShapeBtn.performClick();", "" ); %map.bindCmd( keyboard, "g", "ShapeEditorToolbar->showGridBtn.performClick();", "" ); %map.bindCmd( keyboard, "h", "ShapeEdSelectWindow->tabBook.selectPage( 2 );", "" ); // Load help tab %map.bindCmd( keyboard, "l", "ShapeEdSelectWindow->tabBook.selectPage( 1 );", "" ); // load Library Tab %map.bindCmd( keyboard, "j", "ShapeEdSelectWindow->tabBook.selectPage( 0 );", "" ); // load scene object Tab %map.bindCmd( keyboard, "SPACE", "ShapeEdAnimWindow.togglePause();", "" ); %map.bindCmd( keyboard, "i", "ShapeEdSequences.onEditSeqInOut(\"in\", ShapeEdSeqSlider.getValue());", "" ); %map.bindCmd( keyboard, "o", "ShapeEdSequences.onEditSeqInOut(\"out\", ShapeEdSeqSlider.getValue());", "" ); %map.bindCmd( keyboard, "shift -", "ShapeEdSeqSlider.setValue(ShapeEdAnimWindow-->seqIn.getText());", "" ); %map.bindCmd( keyboard, "shift =", "ShapeEdSeqSlider.setValue(ShapeEdAnimWindow-->seqOut.getText());", "" ); %map.bindCmd( keyboard, "=", "ShapeEdAnimWindow-->stepFwdBtn.performClick();", "" ); %map.bindCmd( keyboard, "-", "ShapeEdAnimWindow-->stepBkwdBtn.performClick();", "" ); ShapeEditorPlugin.map = %map; ShapeEditorPlugin.initSettings(); } function destroyShapeEditor() { } function SetToggleButtonValue(%ctrl, %value) { if ( %ctrl.getValue() != %value ) %ctrl.performClick(); } // Replace the command field in an Editor PopupMenu item (returns the original value) function ShapeEditorPlugin::replaceMenuCmd(%this, %menuTitle, %id, %newCmd) { %menu = EditorGui.findMenu( %menuTitle ); %cmd = getField( %menu.item[%id], 2 ); %menu.setItemCommand( %id, %newCmd ); return %cmd; } function ShapeEditorPlugin::onWorldEditorStartup(%this) { // Add ourselves to the window menu. %accel = EditorGui.addToEditorsMenu("Shape Editor", "", ShapeEditorPlugin); // Add ourselves to the ToolsToolbar %tooltip = "Shape Editor (" @ %accel @ ")"; EditorGui.addToToolsToolbar( "ShapeEditorPlugin", "ShapeEditorPalette", expandFilename("tools/worldEditor/images/toolbar/shape-editor"), %tooltip ); // Add ourselves to the Editor Settings window exec( "./gui/ShapeEditorSettingsTab.gui" ); ESettingsWindow.addTabPage( EShapeEditorSettingsPage ); GuiWindowCtrl::attach(ShapeEdPropWindow, ShapeEdSelectWindow); ShapeEdAnimWindow.resize( -1, 526, 593, 53 ); // Initialise gui ShapeEdSeqNodeTabBook.selectPage(0); ShapeEdAdvancedWindow-->tabBook.selectPage(0); ShapeEdSelectWindow-->tabBook.selectPage(0); ShapeEdSelectWindow.navigate(""); SetToggleButtonValue( ShapeEditorToolbar-->orbitNodeBtn, 0 ); SetToggleButtonValue( ShapeEditorToolbar-->ghostMode, 0 ); // Initialise hints menu ShapeEdHintMenu.clear(); %count = ShapeHintGroup.getCount(); for (%i = 0; %i < %count; %i++) { %hint = ShapeHintGroup.getObject(%i); ShapeEdHintMenu.add(%hint.objectType, %hint); } } function ShapeEditorPlugin::openShapeAsset(%this, %assetId) { %this.selectedAssetId = %assetId; %this.selectedAssetDef = AssetDatabase.acquireAsset(%assetId); %this.open(%this.selectedAssetDef.fileName); } function ShapeEditorPlugin::open(%this, %filename) { if ( !%this.isActivated ) { // Activate the Shape Editor EditorGui.setEditor( %this, true ); // Get editor settings (note the sun angle is not configured in the settings // dialog, so apply the settings here instead of in readSettings) %this.readSettings(); ShapeEdShapeView.sunAngleX = EditorSettings.value("ShapeEditor/SunAngleX"); ShapeEdShapeView.sunAngleZ = EditorSettings.value("ShapeEditor/SunAngleZ"); EWorldEditor.forceLoadDAE = EditorSettings.value("forceLoadDAE"); $wasInWireFrameMode = $gfx::wireframe; ShapeEditorToolbar-->wireframeMode.setStateOn($gfx::wireframe); if ( GlobalGizmoProfile.getFieldValue(alignment) $= "Object" ) ShapeEdNodes-->objectTransform.setStateOn(1); else ShapeEdNodes-->worldTransform.setStateOn(1); // Initialise and show the shape editor ShapeEdShapeTreeView.open(MissionGroup); ShapeEdShapeTreeView.buildVisibleTree(true); ShapeEdPreviewGui.setVisible(true); ShapeEdSelectWindow.setVisible(true); ShapeEdPropWindow.setVisible(true); ShapeEdAnimWindow.setVisible(true); ShapeEdAdvancedWindow.setVisible(ShapeEditorToolbar-->showAdvanced.getValue()); ShapeEditorToolbar.setVisible(true); EditorGui.bringToFront(ShapeEdPreviewGui); ToolsPaletteArray->WorldEditorMove.performClick(); %this.map.push(); // Switch to the ShapeEditor UndoManager %this.oldUndoMgr = Editor.getUndoManager(); Editor.setUndoManager( ShapeEdUndoManager ); ShapeEdShapeView.setDisplayType( EditorGui.currentDisplayType ); %this.initStatusBar(); // Customise menu bar %this.oldCamFitCmd = %this.replaceMenuCmd( "Camera", 8, "ShapeEdShapeView.fitToShape();" ); %this.oldCamFitOrbitCmd = %this.replaceMenuCmd( "Camera", 9, "ShapeEdShapeView.fitToShape();" ); Parent::onActivated(%this); } // Select the new shape if (isObject(ShapeEditor.shape) && (ShapeEditor.shape.baseShape $= %filename)) { // Shape is already selected => re-highlight the selected material if necessary ShapeEdMaterials.updateSelectedMaterial(ShapeEdMaterials-->highlightMaterial.getValue()); } else if (%filename !$= "") { ShapeEditor.selectShape(%filename, ShapeEditor.isDirty()); // 'fitToShape' only works after the GUI has been rendered, so force a repaint first Canvas.repaint(); ShapeEdShapeView.fitToShape(); } } function ShapeEditorPlugin::onActivated(%this) { %this.open(""); // Try to start with the shape selected in the world editor %count = EWorldEditor.getSelectionSize(); for (%i = 0; %i < %count; %i++) { %obj = EWorldEditor.getSelectedObject(%i); %shapeFile = ShapeEditor.getObjectShapeFile(%obj); if (%shapeFile !$= "") { if (!isObject(ShapeEditor.shape) || (ShapeEditor.shape.baseShape !$= %shapeFile)) { // Call the 'onSelect' method directly if the object is not in the // MissionGroup tree (such as a Player or Projectile object). ShapeEdShapeTreeView.clearSelection(); if (!ShapeEdShapeTreeView.selectItem(%obj)) ShapeEdShapeTreeView.onSelect(%obj); // 'fitToShape' only works after the GUI has been rendered, so force a repaint first Canvas.repaint(); ShapeEdShapeView.fitToShape(); } break; } } } function ShapeEditorPlugin::initStatusBar(%this) { EditorGuiStatusBar.setInfo("Shape editor ( Shift Click ) to speed up camera."); EditorGuiStatusBar.setSelection( ShapeEditor.shape.baseShape ); } function ShapeEditorPlugin::onDeactivated(%this) { %this.writeSettings(); // Notify game objects if shape has been modified if ( ShapeEditor.isDirty() ) ShapeEditor.shape.notifyShapeChanged(); $gfx::wireframe = $wasInWireFrameMode; ShapeEdMaterials.updateSelectedMaterial(false); ShapeEditorToolbar.setVisible(false); ShapeEdPreviewGui.setVisible(false); ShapeEdSelectWindow.setVisible(false); ShapeEdPropWindow.setVisible(false); ShapeEdAnimWindow.setVisible(false); ShapeEdAdvancedWindow.setVisible(false); if( EditorGui-->MatEdPropertiesWindow.visible ) { ShapeEdMaterials.editSelectedMaterialEnd( true ); } %this.map.pop(); // Restore the original undo manager Editor.setUndoManager( %this.oldUndoMgr ); // Restore menu bar %this.replaceMenuCmd( "Camera", 8, %this.oldCamFitCmd ); %this.replaceMenuCmd( "Camera", 9, %this.oldCamFitOrbitCmd ); Parent::onDeactivated(%this); } function ShapeEditorPlugin::onExitMission( %this ) { // unselect the current shape ShapeEdShapeView.setModel( "" ); if (ShapeEditor.shape != -1) ShapeEditor.shape.delete(); ShapeEditor.shape = 0; ShapeEdUndoManager.clearAll(); ShapeEditor.setDirty( false ); ShapeEdSequenceList.clear(); ShapeEdNodeTreeView.removeItem( 0 ); ShapeEdPropWindow.update_onNodeSelectionChanged( -1 ); ShapeEdDetailTree.removeItem( 0 ); ShapeEdMaterialList.clear(); ShapeEdMountWindow-->mountList.clear(); ShapeEdThreadWindow-->seqList.clear(); ShapeEdThreadList.clear(); } function ShapeEditorPlugin::openShape( %this, %path, %discardChangesToCurrent ) { EditorGui.setEditor( ShapeEditorPlugin ); if( ShapeEditor.isDirty() && !%discardChangesToCurrent ) { MessageBoxYesNo( "Save Changes?", "Save changes to current shape?", "ShapeEditor.saveChanges(); ShapeEditorPlugin.openShape(\"" @ %path @ "\");", "ShapeEditorPlugin.openShape(\"" @ %path @ "\");" ); return; } ShapeEditor.selectShape( %path ); ShapeEdShapeView.fitToShape(); } function shapeEditorWireframeMode() { $gfx::wireframe = !$gfx::wireframe; ShapeEditorToolbar-->wireframeMode.setStateOn($gfx::wireframe); } //----------------------------------------------------------------------------- // Settings //----------------------------------------------------------------------------- function ShapeEditorPlugin::initSettings( %this ) { EditorSettings.beginGroup( "ShapeEditor", true ); // Display options EditorSettings.setDefaultValue( "BackgroundColor", "0 0 0 100" ); EditorSettings.setDefaultValue( "HighlightMaterial", 1 ); EditorSettings.setDefaultValue( "ShowNodes", 1 ); EditorSettings.setDefaultValue( "ShowBounds", 0 ); EditorSettings.setDefaultValue( "ShowObjBox", 1 ); EditorSettings.setDefaultValue( "RenderMounts", 1 ); EditorSettings.setDefaultValue( "RenderCollision", 0 ); // Grid EditorSettings.setDefaultValue( "ShowGrid", 1 ); EditorSettings.setDefaultValue( "GridSize", 0.1 ); EditorSettings.setDefaultValue( "GridDimension", "40 40" ); // Sun EditorSettings.setDefaultValue( "SunDiffuseColor", "255 255 255 255" ); EditorSettings.setDefaultValue( "SunAmbientColor", "180 180 180 255" ); EditorSettings.setDefaultValue( "SunAngleX", "45" ); EditorSettings.setDefaultValue( "SunAngleZ", "135" ); // Sub-windows EditorSettings.setDefaultValue( "AdvancedWndVisible", "1" ); EditorSettings.endGroup(); } function ShapeEditorPlugin::readSettings( %this ) { EditorSettings.beginGroup( "ShapeEditor", true ); // Display options ShapeEdPreviewGui-->previewBackground.color = ColorIntToFloat( EditorSettings.value("BackgroundColor") ); SetToggleButtonValue( ShapeEdMaterials-->highlightMaterial, EditorSettings.value( "HighlightMaterial" ) ); SetToggleButtonValue( ShapeEditorToolbar-->showNodes, EditorSettings.value( "ShowNodes" ) ); SetToggleButtonValue( ShapeEditorToolbar-->showBounds, EditorSettings.value( "ShowBounds" ) ); SetToggleButtonValue( ShapeEditorToolbar-->showObjBox, EditorSettings.value( "ShowObjBox" ) ); SetToggleButtonValue( ShapeEditorToolbar-->renderColMeshes, EditorSettings.value( "RenderCollision" ) ); SetToggleButtonValue( ShapeEdMountWindow-->renderMounts, EditorSettings.value( "RenderMounts" ) ); // Grid SetToggleButtonValue( ShapeEditorToolbar-->showGridBtn, EditorSettings.value( "ShowGrid" ) ); ShapeEdShapeView.gridSize = EditorSettings.value( "GridSize" ); ShapeEdShapeView.gridDimension = EditorSettings.value( "GridDimension" ); // Sun ShapeEdShapeView.sunDiffuse = EditorSettings.value("SunDiffuseColor"); ShapeEdShapeView.sunAmbient = EditorSettings.value("SunAmbientColor"); // Sub-windows SetToggleButtonValue( ShapeEditorToolbar-->showAdvanced, EditorSettings.value( "AdvancedWndVisible" ) ); EditorSettings.endGroup(); } function ShapeEditorPlugin::writeSettings( %this ) { EditorSettings.beginGroup( "ShapeEditor", true ); // Display options EditorSettings.setValue( "BackgroundColor", ColorFloatToInt( ShapeEdPreviewGui-->previewBackground.color ) ); EditorSettings.setValue( "HighlightMaterial", ShapeEdMaterials-->highlightMaterial.getValue() ); EditorSettings.setValue( "ShowNodes", ShapeEditorToolbar-->showNodes.getValue() ); EditorSettings.setValue( "ShowBounds", ShapeEditorToolbar-->showBounds.getValue() ); EditorSettings.setValue( "ShowObjBox", ShapeEditorToolbar-->showObjBox.getValue() ); EditorSettings.setValue( "RenderCollision", ShapeEditorToolbar-->renderColMeshes.getValue() ); EditorSettings.setValue( "RenderMounts", ShapeEdMountWindow-->renderMounts.getValue() ); // Grid EditorSettings.setValue( "ShowGrid", ShapeEditorToolbar-->showGridBtn.getValue() ); EditorSettings.setValue( "GridSize", ShapeEdShapeView.gridSize ); EditorSettings.setValue( "GridDimension", ShapeEdShapeView.gridDimension ); // Sun EditorSettings.setValue( "SunDiffuseColor", ShapeEdShapeView.sunDiffuse ); EditorSettings.setValue( "SunAmbientColor", ShapeEdShapeView.sunAmbient ); EditorSettings.setValue( "SunAngleX", ShapeEdShapeView.sunAngleX ); EditorSettings.setValue( "SunAngleZ", ShapeEdShapeView.sunAngleZ ); // Sub-windows EditorSettings.setValue( "AdvancedWndVisible", ShapeEditorToolbar-->showAdvanced.getValue() ); EditorSettings.endGroup(); }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Runtime; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Runtime.ConsistentRing; using Orleans.Runtime.Counters; using Orleans.Runtime.GrainDirectory; using Orleans.Runtime.LogConsistency; using Orleans.Runtime.Messaging; using Orleans.Runtime.MultiClusterNetwork; using Orleans.Runtime.Providers; using Orleans.Runtime.ReminderService; using Orleans.Runtime.Scheduler; using Orleans.Services; using Orleans.Streams; using Orleans.Transactions; using Orleans.Runtime.Versions; using Orleans.Versions; using Orleans.ApplicationParts; using Orleans.Configuration; using Orleans.Serialization; namespace Orleans.Runtime { /// <summary> /// Orleans silo. /// </summary> public class Silo { /// <summary> Standard name for Primary silo. </summary> public const string PrimarySiloName = "Primary"; /// <summary> Silo Types. </summary> public enum SiloType { /// <summary> No silo type specified. </summary> None = 0, /// <summary> Primary silo. </summary> Primary, /// <summary> Secondary silo. </summary> Secondary, } private readonly ILocalSiloDetails siloDetails; private readonly ClusterOptions clusterOptions; private readonly ISiloMessageCenter messageCenter; private readonly OrleansTaskScheduler scheduler; private readonly LocalGrainDirectory localGrainDirectory; private readonly ActivationDirectory activationDirectory; private readonly IncomingMessageAgent incomingAgent; private readonly IncomingMessageAgent incomingSystemAgent; private readonly IncomingMessageAgent incomingPingAgent; private readonly ILogger logger; private TypeManager typeManager; private readonly TaskCompletionSource<int> siloTerminatedTask = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); private readonly SiloStatisticsManager siloStatistics; private readonly InsideRuntimeClient runtimeClient; private IReminderService reminderService; private SystemTarget fallbackScheduler; private readonly IMembershipOracle membershipOracle; private readonly IMultiClusterOracle multiClusterOracle; private readonly ExecutorService executorService; private Watchdog platformWatchdog; private readonly TimeSpan initTimeout; private readonly TimeSpan stopTimeout = TimeSpan.FromMinutes(1); private readonly Catalog catalog; private readonly List<IHealthCheckParticipant> healthCheckParticipants = new List<IHealthCheckParticipant>(); private readonly object lockable = new object(); private readonly GrainFactory grainFactory; private readonly ISiloLifecycleSubject siloLifecycle; private List<GrainService> grainServices = new List<GrainService>(); private readonly ILoggerFactory loggerFactory; /// <summary> /// Gets the type of this /// </summary> internal string Name => this.siloDetails.Name; internal OrleansTaskScheduler LocalScheduler { get { return scheduler; } } internal ILocalGrainDirectory LocalGrainDirectory { get { return localGrainDirectory; } } internal IMultiClusterOracle LocalMultiClusterOracle { get { return multiClusterOracle; } } internal IConsistentRingProvider RingProvider { get; private set; } internal ICatalog Catalog => catalog; internal SystemStatus SystemStatus { get; set; } internal IServiceProvider Services { get; } /// <summary> SiloAddress for this silo. </summary> public SiloAddress SiloAddress => this.siloDetails.SiloAddress; /// <summary> /// Silo termination event used to signal shutdown of this silo. /// </summary> public WaitHandle SiloTerminatedEvent // one event for all types of termination (shutdown, stop and fast kill). => ((IAsyncResult)this.siloTerminatedTask.Task).AsyncWaitHandle; public Task SiloTerminated { get { return this.siloTerminatedTask.Task; } } // one event for all types of termination (shutdown, stop and fast kill). private SchedulingContext membershipOracleContext; private SchedulingContext multiClusterOracleContext; private SchedulingContext reminderServiceContext; private LifecycleSchedulingSystemTarget lifecycleSchedulingSystemTarget; /// <summary> /// Initializes a new instance of the <see cref="Silo"/> class. /// </summary> /// <param name="siloDetails">The silo initialization parameters</param> /// <param name="services">Dependency Injection container</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Should not Dispose of messageCenter in this method because it continues to run / exist after this point.")] public Silo(ILocalSiloDetails siloDetails, IServiceProvider services) { string name = siloDetails.Name; // Temporarily still require this. Hopefuly gone when 2.0 is released. this.siloDetails = siloDetails; this.SystemStatus = SystemStatus.Creating; AsynchAgent.IsStarting = true; // todo. use ISiloLifecycle instead? var startTime = DateTime.UtcNow; IOptions<ClusterMembershipOptions> clusterMembershipOptions = services.GetRequiredService<IOptions<ClusterMembershipOptions>>(); initTimeout = clusterMembershipOptions.Value.MaxJoinAttemptTime; if (Debugger.IsAttached) { initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), clusterMembershipOptions.Value.MaxJoinAttemptTime); stopTimeout = initTimeout; } var localEndpoint = this.siloDetails.SiloAddress.Endpoint; services.GetService<SerializationManager>().RegisterSerializers(services.GetService<IApplicationPartManager>()); this.Services = services; this.Services.InitializeSiloUnobservedExceptionsHandler(); //set PropagateActivityId flag from node config IOptions<SiloMessagingOptions> messagingOptions = services.GetRequiredService<IOptions<SiloMessagingOptions>>(); RequestContext.PropagateActivityId = messagingOptions.Value.PropagateActivityId; this.loggerFactory = this.Services.GetRequiredService<ILoggerFactory>(); logger = this.loggerFactory.CreateLogger<Silo>(); logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode)); if (!GCSettings.IsServerGC) { logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\">"); logger.Warn(ErrorCode.SiloGcWarning, "Note: ServerGC only kicks in on multi-core systems (settings enabling ServerGC have no effect on single-core machines)."); } logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing silo on host {0} MachineName {1} at {2}, gen {3} --------------", this.siloDetails.DnsHostName, Environment.MachineName, localEndpoint, this.siloDetails.SiloAddress.Generation); logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0}", name); var siloMessagingOptions = this.Services.GetRequiredService<IOptions<SiloMessagingOptions>>(); BufferPool.InitGlobalBufferPool(siloMessagingOptions.Value); try { grainFactory = Services.GetRequiredService<GrainFactory>(); } catch (InvalidOperationException exc) { logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start, GrainFactory was not registered in Dependency Injection container", exc); throw; } // Performance metrics siloStatistics = Services.GetRequiredService<SiloStatisticsManager>(); // The scheduler scheduler = Services.GetRequiredService<OrleansTaskScheduler>(); healthCheckParticipants.Add(scheduler); runtimeClient = Services.GetRequiredService<InsideRuntimeClient>(); // Initialize the message center messageCenter = Services.GetRequiredService<MessageCenter>(); var dispatcher = this.Services.GetRequiredService<Dispatcher>(); messageCenter.RerouteHandler = dispatcher.RerouteMessage; messageCenter.SniffIncomingMessage = runtimeClient.SniffIncomingMessage; // Now the router/directory service // This has to come after the message center //; note that it then gets injected back into the message center.; localGrainDirectory = Services.GetRequiredService<LocalGrainDirectory>(); // Now the activation directory. activationDirectory = Services.GetRequiredService<ActivationDirectory>(); // Now the consistent ring provider RingProvider = Services.GetRequiredService<IConsistentRingProvider>(); catalog = Services.GetRequiredService<Catalog>(); executorService = Services.GetRequiredService<ExecutorService>(); // Now the incoming message agents var messageFactory = this.Services.GetRequiredService<MessageFactory>(); incomingSystemAgent = new IncomingMessageAgent(Message.Categories.System, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, executorService, this.loggerFactory); incomingPingAgent = new IncomingMessageAgent(Message.Categories.Ping, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, executorService, this.loggerFactory); incomingAgent = new IncomingMessageAgent(Message.Categories.Application, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, executorService, this.loggerFactory); membershipOracle = Services.GetRequiredService<IMembershipOracle>(); this.clusterOptions = Services.GetRequiredService<IOptions<ClusterOptions>>().Value; var multiClusterOptions = Services.GetRequiredService<IOptions<MultiClusterOptions>>().Value; if (!multiClusterOptions.HasMultiClusterNetwork) { logger.Info("Skip multicluster oracle creation (no multicluster network configured)"); } else { multiClusterOracle = Services.GetRequiredService<IMultiClusterOracle>(); } this.SystemStatus = SystemStatus.Created; AsynchAgent.IsStarting = false; StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME, () => LogFormatter.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs. this.siloLifecycle = this.Services.GetRequiredService<ISiloLifecycleSubject>(); // register all lifecycle participants IEnumerable<ILifecycleParticipant<ISiloLifecycle>> lifecycleParticipants = this.Services.GetServices<ILifecycleParticipant<ISiloLifecycle>>(); foreach(ILifecycleParticipant<ISiloLifecycle> participant in lifecycleParticipants) { participant?.Participate(this.siloLifecycle); } // register all named lifecycle participants IKeyedServiceCollection<string, ILifecycleParticipant<ISiloLifecycle>> namedLifecycleParticipantCollection = this.Services.GetService<IKeyedServiceCollection<string,ILifecycleParticipant<ISiloLifecycle>>>(); foreach (ILifecycleParticipant<ISiloLifecycle> participant in namedLifecycleParticipantCollection ?.GetServices(this.Services) ?.Select(s => s.GetService(this.Services))) { participant?.Participate(this.siloLifecycle); } // add self to lifecycle this.Participate(this.siloLifecycle); logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode()); } public void Start() { StartAsync(CancellationToken.None).GetAwaiter().GetResult(); } public async Task StartAsync(CancellationToken cancellationToken) { StartTaskWithPerfAnalysis("Start Scheduler", scheduler.Start, new Stopwatch()); // SystemTarget for provider init calls this.lifecycleSchedulingSystemTarget = Services.GetRequiredService<LifecycleSchedulingSystemTarget>(); this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>(); RegisterSystemTarget(lifecycleSchedulingSystemTarget); try { await this.scheduler.QueueTask(() => this.siloLifecycle.OnStart(cancellationToken), this.lifecycleSchedulingSystemTarget.SchedulingContext); } catch (Exception exc) { logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start", exc); throw; } } private void CreateSystemTargets() { logger.Debug("Creating System Targets for this silo."); logger.Debug("Creating {0} System Target", "SiloControl"); var siloControl = ActivatorUtilities.CreateInstance<SiloControl>(Services); RegisterSystemTarget(siloControl); logger.Debug("Creating {0} System Target", "ProtocolGateway"); RegisterSystemTarget(new ProtocolGateway(this.SiloAddress, this.loggerFactory)); logger.Debug("Creating {0} System Target", "DeploymentLoadPublisher"); RegisterSystemTarget(Services.GetRequiredService<DeploymentLoadPublisher>()); logger.Debug("Creating {0} System Target", "RemoteGrainDirectory + CacheValidator"); RegisterSystemTarget(LocalGrainDirectory.RemoteGrainDirectory); RegisterSystemTarget(LocalGrainDirectory.CacheValidator); logger.Debug("Creating {0} System Target", "RemoteClusterGrainDirectory"); RegisterSystemTarget(LocalGrainDirectory.RemoteClusterGrainDirectory); logger.Debug("Creating {0} System Target", "ClientObserverRegistrar + TypeManager"); this.RegisterSystemTarget(this.Services.GetRequiredService<ClientObserverRegistrar>()); var implicitStreamSubscriberTable = Services.GetRequiredService<ImplicitStreamSubscriberTable>(); var versionDirectorManager = this.Services.GetRequiredService<CachedVersionSelectorManager>(); var grainTypeManager = this.Services.GetRequiredService<GrainTypeManager>(); IOptions<TypeManagementOptions> typeManagementOptions = this.Services.GetRequiredService<IOptions<TypeManagementOptions>>(); typeManager = new TypeManager(SiloAddress, grainTypeManager, membershipOracle, LocalScheduler, typeManagementOptions.Value.TypeMapRefreshInterval, implicitStreamSubscriberTable, this.grainFactory, versionDirectorManager, this.loggerFactory); this.RegisterSystemTarget(typeManager); logger.Debug("Creating {0} System Target", "MembershipOracle"); if (this.membershipOracle is SystemTarget) { RegisterSystemTarget((SystemTarget)membershipOracle); } if (multiClusterOracle != null && multiClusterOracle is SystemTarget) { logger.Debug("Creating {0} System Target", "MultiClusterOracle"); RegisterSystemTarget((SystemTarget)multiClusterOracle); } logger.Debug("Finished creating System Targets for this silo."); } private async Task InjectDependencies() { healthCheckParticipants.Add(membershipOracle); catalog.SiloStatusOracle = this.membershipOracle; this.membershipOracle.SubscribeToSiloStatusEvents(localGrainDirectory); messageCenter.SiloDeadOracle = this.membershipOracle.IsDeadSilo; // consistentRingProvider is not a system target per say, but it behaves like the localGrainDirectory, so it is here this.membershipOracle.SubscribeToSiloStatusEvents((ISiloStatusListener)RingProvider); this.membershipOracle.SubscribeToSiloStatusEvents(typeManager); this.membershipOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<DeploymentLoadPublisher>()); this.membershipOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<ClientObserverRegistrar>()); var reminderTable = Services.GetService<IReminderTable>(); if (reminderTable != null) { logger.Info($"Creating reminder grain service for type={reminderTable.GetType()}"); // Start the reminder service system target reminderService = new LocalReminderService(this, reminderTable, this.initTimeout, this.loggerFactory); ; RegisterSystemTarget((SystemTarget)reminderService); } RegisterSystemTarget(catalog); await scheduler.QueueAction(catalog.Start, catalog.SchedulingContext) .WithTimeout(initTimeout, $"Starting Catalog failed due to timeout {initTimeout}"); // SystemTarget for provider init calls this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>(); RegisterSystemTarget(fallbackScheduler); } private Task OnRuntimeInitializeStart(CancellationToken ct) { lock (lockable) { if (!this.SystemStatus.Equals(SystemStatus.Created)) throw new InvalidOperationException(String.Format("Calling Silo.Start() on a silo which is not in the Created state. This silo is in the {0} state.", this.SystemStatus)); this.SystemStatus = SystemStatus.Starting; } logger.Info(ErrorCode.SiloStarting, "Silo Start()"); var processExitHandlingOptions = this.Services.GetService<IOptions<ProcessExitHandlingOptions>>().Value; if(processExitHandlingOptions.FastKillOnProcessExit) AppDomain.CurrentDomain.ProcessExit += HandleProcessExit; //TODO: setup thead pool directly to lifecycle StartTaskWithPerfAnalysis("ConfigureThreadPoolAndServicePointSettings", this.ConfigureThreadPoolAndServicePointSettings, Stopwatch.StartNew()); return Task.CompletedTask; } private void StartTaskWithPerfAnalysis(string taskName, Action task, Stopwatch stopWatch) { stopWatch.Restart(); task.Invoke(); stopWatch.Stop(); this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish"); } private async Task StartAsyncTaskWithPerfAnalysis(string taskName, Func<Task> task, Stopwatch stopWatch) { stopWatch.Restart(); await task.Invoke(); stopWatch.Stop(); this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish"); } private async Task OnRuntimeServicesStart(CancellationToken ct) { //TODO: Setup all (or as many as possible) of the class started in this call to work directly with lifecyce var stopWatch = Stopwatch.StartNew(); // The order of these 4 is pretty much arbitrary. StartTaskWithPerfAnalysis("Start Message center",messageCenter.Start,stopWatch); StartTaskWithPerfAnalysis("Start Incoming message agents", IncomingMessageAgentsStart, stopWatch); void IncomingMessageAgentsStart() { incomingPingAgent.Start(); incomingSystemAgent.Start(); incomingAgent.Start(); } StartTaskWithPerfAnalysis("Start local grain directory", LocalGrainDirectory.Start,stopWatch); // Set up an execution context for this thread so that the target creation steps can use asynch values. RuntimeContext.InitializeMainThread(); StartTaskWithPerfAnalysis("Init implicit stream subscribe table", InitImplicitStreamSubscribeTable, stopWatch); void InitImplicitStreamSubscribeTable() { // Initialize the implicit stream subscribers table. var implicitStreamSubscriberTable = Services.GetRequiredService<ImplicitStreamSubscriberTable>(); var grainTypeManager = Services.GetRequiredService<GrainTypeManager>(); implicitStreamSubscriberTable.InitImplicitStreamSubscribers(grainTypeManager.GrainClassTypeData.Select(t => t.Value.Type).ToArray()); } this.runtimeClient.CurrentStreamProviderRuntime = this.Services.GetRequiredService<SiloProviderRuntime>(); // This has to follow the above steps that start the runtime components await StartAsyncTaskWithPerfAnalysis("Create system targets and inject dependencies", () => { CreateSystemTargets(); return InjectDependencies(); }, stopWatch); // Validate the configuration. // TODO - refactor validation - jbragg //GlobalConfig.Application.ValidateConfiguration(logger); } private async Task OnRuntimeGrainServicesStart(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); // Load and init grain services before silo becomes active. await StartAsyncTaskWithPerfAnalysis("Init grain services", () => CreateGrainServices(), stopWatch); this.membershipOracleContext = (this.membershipOracle as SystemTarget)?.SchedulingContext ?? this.fallbackScheduler.SchedulingContext; await StartAsyncTaskWithPerfAnalysis("Starting local silo status oracle", StartMembershipOracle, stopWatch); async Task StartMembershipOracle() { await scheduler.QueueTask(() => this.membershipOracle.Start(), this.membershipOracleContext) .WithTimeout(initTimeout, $"Starting MembershipOracle failed due to timeout {initTimeout}"); logger.Debug("Local silo status oracle created successfully."); } var versionStore = Services.GetService<IVersionStore>(); await StartAsyncTaskWithPerfAnalysis("Init type manager", () => scheduler .QueueTask(() => this.typeManager.Initialize(versionStore), this.typeManager.SchedulingContext) .WithTimeout(this.initTimeout, $"TypeManager Initializing failed due to timeout {initTimeout}"), stopWatch); //if running in multi cluster scenario, start the MultiClusterNetwork Oracle if (this.multiClusterOracle != null) { await StartAsyncTaskWithPerfAnalysis("Start multicluster oracle", StartMultiClusterOracle, stopWatch); async Task StartMultiClusterOracle() { logger.Info("Starting multicluster oracle with my ServiceId={0} and ClusterId={1}.", this.clusterOptions.ServiceId, this.clusterOptions.ClusterId); this.multiClusterOracleContext = (multiClusterOracle as SystemTarget)?.SchedulingContext ?? this.fallbackScheduler.SchedulingContext; await scheduler.QueueTask(() => multiClusterOracle.Start(), multiClusterOracleContext) .WithTimeout(initTimeout, $"Starting MultiClusterOracle failed due to timeout {initTimeout}"); logger.Debug("multicluster oracle created successfully."); } } try { StatisticsOptions statisticsOptions = Services.GetRequiredService<IOptions<StatisticsOptions>>().Value; StartTaskWithPerfAnalysis("Start silo statistics", () => this.siloStatistics.Start(statisticsOptions), stopWatch); logger.Debug("Silo statistics manager started successfully."); // Finally, initialize the deployment load collector, for grains with load-based placement await StartAsyncTaskWithPerfAnalysis("Start deployment load collector", StartDeploymentLoadCollector, stopWatch); async Task StartDeploymentLoadCollector() { var deploymentLoadPublisher = Services.GetRequiredService<DeploymentLoadPublisher>(); await this.scheduler.QueueTask(deploymentLoadPublisher.Start, deploymentLoadPublisher.SchedulingContext) .WithTimeout(this.initTimeout, $"Starting DeploymentLoadPublisher failed due to timeout {initTimeout}"); logger.Debug("Silo deployment load publisher started successfully."); } // Start background timer tick to watch for platform execution stalls, such as when GC kicks in this.platformWatchdog = new Watchdog(statisticsOptions.LogWriteInterval, this.healthCheckParticipants, this.executorService, this.loggerFactory); this.platformWatchdog.Start(); if (this.logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo platform watchdog started successfully."); } } catch (Exception exc) { this.SafeExecute(() => this.logger.Error(ErrorCode.Runtime_Error_100330, String.Format("Error starting silo {0}. Going to FastKill().", this.SiloAddress), exc)); throw; } if (logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo.Start complete: System status = {0}", this.SystemStatus); } } private async Task OnBecomeActiveStart(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); StartTaskWithPerfAnalysis("Start gateway", StartGateway, stopWatch); void StartGateway() { // Now that we're active, we can start the gateway var mc = this.messageCenter as MessageCenter; mc?.StartGateway(this.Services.GetRequiredService<ClientObserverRegistrar>()); logger.Debug("Message gateway service started successfully."); } await StartAsyncTaskWithPerfAnalysis("Starting local silo status oracle", BecomeActive, stopWatch); async Task BecomeActive() { await scheduler.QueueTask(this.membershipOracle.BecomeActive, this.membershipOracleContext) .WithTimeout(initTimeout, $"MembershipOracle activating failed due to timeout {initTimeout}"); logger.Debug("Local silo status oracle became active successfully."); } this.SystemStatus = SystemStatus.Running; } private async Task OnActiveStart(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); if (this.reminderService != null) { await StartAsyncTaskWithPerfAnalysis("Start reminder service", StartReminderService, stopWatch); async Task StartReminderService() { // so, we have the view of the membership in the consistentRingProvider. We can start the reminder service this.reminderServiceContext = (this.reminderService as SystemTarget)?.SchedulingContext ?? this.fallbackScheduler.SchedulingContext; await this.scheduler.QueueTask(this.reminderService.Start, this.reminderServiceContext) .WithTimeout(this.initTimeout, $"Starting ReminderService failed due to timeout {initTimeout}"); this.logger.Debug("Reminder service started successfully."); } } foreach (var grainService in grainServices) { await StartGrainService(grainService); } } private async Task CreateGrainServices() { var grainServices = this.Services.GetServices<IGrainService>(); foreach (var grainService in grainServices) { await RegisterGrainService(grainService); } } private async Task RegisterGrainService(IGrainService service) { var grainService = (GrainService)service; RegisterSystemTarget(grainService); grainServices.Add(grainService); await this.scheduler.QueueTask(() => grainService.Init(Services), grainService.SchedulingContext).WithTimeout(this.initTimeout, $"GrainService Initializing failed due to timeout {initTimeout}"); logger.Info($"Grain Service {service.GetType().FullName} registered successfully."); } private async Task StartGrainService(IGrainService service) { var grainService = (GrainService)service; await this.scheduler.QueueTask(grainService.Start, grainService.SchedulingContext).WithTimeout(this.initTimeout, $"Starting GrainService failed due to timeout {initTimeout}"); logger.Info($"Grain Service {service.GetType().FullName} started successfully."); } private void ConfigureThreadPoolAndServicePointSettings() { PerformanceTuningOptions performanceTuningOptions = Services.GetRequiredService<IOptions<PerformanceTuningOptions>>().Value; if (performanceTuningOptions.MinDotNetThreadPoolSize > 0) { int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); if (performanceTuningOptions.MinDotNetThreadPoolSize > workerThreads || performanceTuningOptions.MinDotNetThreadPoolSize > completionPortThreads) { // if at least one of the new values is larger, set the new min values to be the larger of the prev. and new config value. int newWorkerThreads = Math.Max(performanceTuningOptions.MinDotNetThreadPoolSize, workerThreads); int newCompletionPortThreads = Math.Max(performanceTuningOptions.MinDotNetThreadPoolSize, completionPortThreads); bool ok = ThreadPool.SetMinThreads(newWorkerThreads, newCompletionPortThreads); if (ok) { logger.Info(ErrorCode.SiloConfiguredThreadPool, "Configured ThreadPool.SetMinThreads() to values: {0},{1}. Previous values are: {2},{3}.", newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads); } else { logger.Warn(ErrorCode.SiloFailedToConfigureThreadPool, "Failed to configure ThreadPool.SetMinThreads(). Tried to set values to: {0},{1}. Previous values are: {2},{3}.", newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads); } } } // Set .NET ServicePointManager settings to optimize throughput performance when using Azure storage // http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx logger.Info(ErrorCode.SiloConfiguredServicePointManager, "Configured .NET ServicePointManager to Expect100Continue={0}, DefaultConnectionLimit={1}, UseNagleAlgorithm={2} to improve Azure storage performance.", performanceTuningOptions.Expect100Continue, performanceTuningOptions.DefaultConnectionLimit, performanceTuningOptions.UseNagleAlgorithm); ServicePointManager.Expect100Continue = performanceTuningOptions.Expect100Continue; ServicePointManager.DefaultConnectionLimit = performanceTuningOptions.DefaultConnectionLimit; ServicePointManager.UseNagleAlgorithm = performanceTuningOptions.UseNagleAlgorithm; } /// <summary> /// Gracefully stop the run time system only, but not the application. /// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible. /// Grains are not deactivated. /// </summary> public void Stop() { var cancellationSource = new CancellationTokenSource(); cancellationSource.Cancel(); StopAsync(cancellationSource.Token).GetAwaiter().GetResult(); } /// <summary> /// Gracefully stop the run time system and the application. /// All grains will be properly deactivated. /// All in-flight applications requests would be awaited and finished gracefully. /// </summary> public void Shutdown() { StopAsync(CancellationToken.None).GetAwaiter().GetResult(); } /// <summary> /// Gracefully stop the run time system only, but not the application. /// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible. /// </summary> public async Task StopAsync(CancellationToken cancellationToken) { bool gracefully = !cancellationToken.IsCancellationRequested; string operation = gracefully ? "Shutdown()" : "Stop()"; bool stopAlreadyInProgress = false; lock (lockable) { if (this.SystemStatus.Equals(SystemStatus.Stopping) || this.SystemStatus.Equals(SystemStatus.ShuttingDown) || this.SystemStatus.Equals(SystemStatus.Terminated)) { stopAlreadyInProgress = true; // Drop through to wait below } else if (!this.SystemStatus.Equals(SystemStatus.Running)) { throw new InvalidOperationException(String.Format("Calling Silo.{0} on a silo which is not in the Running state. This silo is in the {1} state.", operation, this.SystemStatus)); } else { if (gracefully) this.SystemStatus = SystemStatus.ShuttingDown; else this.SystemStatus = SystemStatus.Stopping; } } if (stopAlreadyInProgress) { logger.Info(ErrorCode.SiloStopInProgress, "Silo termination is in progress - Will wait for it to finish"); var pause = TimeSpan.FromSeconds(1); while (!this.SystemStatus.Equals(SystemStatus.Terminated)) { logger.Info(ErrorCode.WaitingForSiloStop, "Waiting {0} for termination to complete", pause); Thread.Sleep(pause); } await this.siloTerminatedTask.Task; return; } try { await this.scheduler.QueueTask(() => this.siloLifecycle.OnStop(cancellationToken), this.lifecycleSchedulingSystemTarget.SchedulingContext); } finally { SafeExecute(scheduler.Stop); SafeExecute(scheduler.PrintStatistics); } } private Task OnRuntimeServicesStop(CancellationToken cancellationToken) { // Start rejecting all silo to silo application messages SafeExecute(messageCenter.BlockApplicationMessages); // Stop scheduling/executing application turns SafeExecute(scheduler.StopApplicationTurns); // Directory: Speed up directory handoff // will be started automatically when directory receives SiloStatusChangeNotification(Stopping) SafeExecute(() => LocalGrainDirectory.StopPreparationCompletion.WaitWithThrow(stopTimeout)); return Task.CompletedTask; } private Task OnRuntimeInitializeStop(CancellationToken ct) { // 10, 11, 12: Write Dead in the table, Drain scheduler, Stop msg center, ... logger.Info(ErrorCode.SiloStopped, "Silo is Stopped()"); SafeExecute(() => scheduler.QueueTask( this.membershipOracle.KillMyself, this.membershipOracleContext) .WaitWithThrow(stopTimeout)); // incoming messages SafeExecute(incomingSystemAgent.Stop); SafeExecute(incomingPingAgent.Stop); SafeExecute(incomingAgent.Stop); // timers if (platformWatchdog != null) SafeExecute(platformWatchdog.Stop); // Silo may be dying before platformWatchdog was set up SafeExecute(activationDirectory.PrintActivationDirectory); SafeExecute(messageCenter.Stop); SafeExecute(siloStatistics.Stop); SafeExecute(() => this.SystemStatus = SystemStatus.Terminated); SafeExecute(() => (this.Services as IDisposable)?.Dispose()); // Setting the event should be the last thing we do. // Do nothing after that! this.siloTerminatedTask.SetResult(0); return Task.CompletedTask; } private async Task OnBecomeActiveStop(CancellationToken ct) { bool gracefully = !ct.IsCancellationRequested; string operation = gracefully ? "Shutdown()" : "Stop()"; try { if (gracefully) { logger.Info(ErrorCode.SiloShuttingDown, "Silo starting to Shutdown()"); // Write "ShutDown" state in the table + broadcast gossip msgs to re-read the table to everyone await scheduler.QueueTask(this.membershipOracle.ShutDown, this.membershipOracleContext) .WithTimeout(stopTimeout, $"MembershipOracle Shutting down failed due to timeout {stopTimeout}"); // Deactivate all grains SafeExecute(() => catalog.DeactivateAllActivations().WaitWithThrow(stopTimeout)); } else { logger.Info(ErrorCode.SiloStopping, "Silo starting to Stop()"); // Write "Stopping" state in the table + broadcast gossip msgs to re-read the table to everyone await scheduler.QueueTask(this.membershipOracle.Stop, this.membershipOracleContext) .WithTimeout(stopTimeout, $"Stopping MembershipOracle faield due to timeout {stopTimeout}"); } } catch (Exception exc) { logger.Error(ErrorCode.SiloFailedToStopMembership, String.Format("Failed to {0} membership oracle. About to FastKill this silo.", operation), exc); return; // will go to finally } // Stop the gateway SafeExecute(messageCenter.StopAcceptingClientMessages); } private async Task OnActiveStop(CancellationToken ct) { if (reminderService != null) { // 2: Stop reminder service await scheduler.QueueTask(reminderService.Stop, this.reminderServiceContext) .WithTimeout(stopTimeout, $"Stopping ReminderService failed due to timeout {stopTimeout}"); } foreach (var grainService in grainServices) { await this.scheduler.QueueTask(grainService.Stop, grainService.SchedulingContext).WithTimeout(this.stopTimeout, $"Stopping GrainService failed due to timeout {initTimeout}"); if (this.logger.IsEnabled(LogLevel.Debug)) { logger.Debug(String.Format("{0} Grain Service with Id {1} stopped successfully.", grainService.GetType().FullName, grainService.GetPrimaryKeyLong(out string ignored))); } } } private void SafeExecute(Action action) { Utils.SafeExecute(action, logger, "Silo.Stop"); } private void HandleProcessExit(object sender, EventArgs e) { // NOTE: We need to minimize the amount of processing occurring on this code path -- we only have under approx 2-3 seconds before process exit will occur this.logger.Warn(ErrorCode.Runtime_Error_100220, "Process is exiting"); this.Stop(); } internal void RegisterSystemTarget(SystemTarget target) { var providerRuntime = this.Services.GetRequiredService<SiloProviderRuntime>(); providerRuntime.RegisterSystemTarget(target); } /// <summary> Return dump of diagnostic data from this silo. </summary> /// <param name="all"></param> /// <returns>Debug data for this silo.</returns> public string GetDebugDump(bool all = true) { var sb = new StringBuilder(); foreach (var systemTarget in activationDirectory.AllSystemTargets()) sb.AppendFormat("System target {0}:", ((ISystemTargetBase)systemTarget).GrainId.ToString()).AppendLine(); var enumerator = activationDirectory.GetEnumerator(); while(enumerator.MoveNext()) { Utils.SafeExecute(() => { var activationData = enumerator.Current.Value; var workItemGroup = scheduler.GetWorkItemGroup(activationData.SchedulingContext); if (workItemGroup == null) { sb.AppendFormat("Activation with no work item group!! Grain {0}, activation {1}.", activationData.Grain, activationData.ActivationId); sb.AppendLine(); return; } if (all || activationData.State.Equals(ActivationState.Valid)) { sb.AppendLine(workItemGroup.DumpStatus()); sb.AppendLine(activationData.DumpStatus()); } }); } logger.Info(ErrorCode.SiloDebugDump, sb.ToString()); return sb.ToString(); } /// <summary> Object.ToString override -- summary info for this silo. </summary> public override string ToString() { return localGrainDirectory.ToString(); } private void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeInitialize, (ct) => Task.Run(() => OnRuntimeInitializeStart(ct)), (ct) => Task.Run(() => OnRuntimeInitializeStop(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeServices, (ct) => Task.Run(() => OnRuntimeServicesStart(ct)), (ct) => Task.Run(() => OnRuntimeServicesStop(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeGrainServices, (ct) => Task.Run(() => OnRuntimeGrainServicesStart(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.BecomeActive, (ct) => Task.Run(() => OnBecomeActiveStart(ct)), (ct) => Task.Run(() => OnBecomeActiveStop(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.Active, (ct) => Task.Run(() => OnActiveStart(ct)), (ct) => Task.Run(() => OnActiveStop(ct))); } } // A dummy system target for fallback scheduler internal class FallbackSystemTarget : SystemTarget { public FallbackSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory) : base(Constants.FallbackSystemTargetId, localSiloDetails.SiloAddress, loggerFactory) { } } // A dummy system target for fallback scheduler internal class LifecycleSchedulingSystemTarget : SystemTarget { public LifecycleSchedulingSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory) : base(Constants.LifecycleSchedulingSystemTargetId, localSiloDetails.SiloAddress, loggerFactory) { } } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Resources; using MindTouch.Dream; namespace MindTouch.Deki { // A custom Resource Reader which takes a plain text file with key=value pairs on each line internal class PlainTextResourceReader : IResourceReader { //--- Class Fields --- private static readonly log4net.ILog _log = LogUtils.CreateLog(); //--- Fields --- private String _filename; //--- Constructors -- public PlainTextResourceReader(String filename) { _filename = filename; } //--- Methods --- public IDictionaryEnumerator GetEnumerator() { Dictionary<String, String> resources = new Dictionary<String, String>(); if(System.IO.File.Exists(_filename)) { char[] brackets = new char[] { ']' }; char[] equals = new char[] { '=' }; string[] parts; // read the file into the hashtable using(StreamReader sr = new StreamReader(_filename, System.Text.Encoding.UTF8, true)) { int count = 0; string section = null; for(string line = sr.ReadLine(); line != null; line = sr.ReadLine()) { line = line.TrimStart(); ++count; // check if line is a comment if(line.StartsWith(";")) { continue; } // check if line is a new section if(line.StartsWith("[")) { parts = line.Substring(1).Split(brackets, 2); if(!string.IsNullOrEmpty(parts[0])) { section = parts[0].Trim(); } else { section = null; _log.WarnMethodCall("missing namespace name", _filename, count); } continue; } // parse the line as key=value parts = line.Split(equals, 2); if(parts.Length == 2) { if(!string.IsNullOrEmpty(parts[0])) { string key; // check if a section is defined if(section != null) { key = section + "." + parts[0]; } else { key = parts[0]; _log.WarnMethodCall("missing namespace prefix", _filename, count, parts[0]); } // check if key already exists if(resources.ContainsKey(key)) { _log.WarnMethodCall("duplicate key", _filename, count, key); } resources[key] = PhpUtil.ConvertToFormatString(parts[1]); } else { _log.WarnMethodCall("empty key", _filename, count, line); } } else if(line != string.Empty) { _log.WarnMethodCall("bad key/value pair", _filename, count, line); } } sr.Close(); } } return resources.GetEnumerator(); } public void Close() { } public void Dispose() { } //--- Interface --- IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } public class PlainTextResourceManager { //--- Fields --- private readonly String _resourcePath; // TODO: this really shouldn't be static, since several PlainTextResourceManager, each with different resourcePaths could // could be created, leaving the actually instantiated ResourceSet as non-deterministic. private static Dictionary<String, ResourceSet> _resourceData; private static object _resourceLock = new object(); //--- Constructors --- public PlainTextResourceManager(ResourceSet testSet) { lock(_resourceLock) { string key = GetResourceKey(null, false); ResourceData[key] = testSet; key = GetResourceKey(new CultureInfo("en"), false); ResourceData[key] = testSet; key = GetResourceKey(new CultureInfo("en-us"), false); ResourceData[key] = testSet; key = GetResourceKey(CultureInfo.InvariantCulture, false); ResourceData[key] = testSet; } } public PlainTextResourceManager(String resourcePath) { _resourcePath = resourcePath; } //--- Methods --- private String GetResourceKey(CultureInfo culture, bool custom) { if(null == culture) { return _resourcePath + "-custom"; } else if(culture.Equals(CultureInfo.InvariantCulture)) { return _resourcePath + culture.LCID; } else { return _resourcePath + "-" + culture.LCID + (custom ? "-custom" : string.Empty); } } private ResourceSet GetResourceSet(CultureInfo culture, bool custom) { ResourceSet resource; String resourceKey = GetResourceKey(culture, custom); lock(_resourceLock) { // if the resource data for this culture has not yet been loaded, load it if(!ResourceData.TryGetValue(resourceKey, out resource)) { // set the filename according to the cuture String filename; if(null == culture) { filename = "resources.custom.txt"; } else if(culture.Equals(CultureInfo.InvariantCulture)) { filename = "resources.txt"; } else { filename = "resources."; if(custom) { filename += "custom."; } filename += culture.Name.ToLowerInvariant() + ".txt"; } filename = Path.Combine(_resourcePath, filename); // load the resource set and add it into the resource table resource = new ResourceSet(new PlainTextResourceReader(filename)); // Note (arnec): We call GetString to force the lazy loading of the resource stream, thereby making // GetString(), at least theoretically, thread-safe for subsequent calls. resource.GetString("", true); ResourceData.Add(resourceKey, resource); } } return resource; } public String GetString(String name, CultureInfo culture, string def) { if(null == culture) { culture = CultureInfo.InvariantCulture; } // attempt to retrieve the string from the custom resource set ResourceSet resourceSet = GetResourceSet(null, true); string result = resourceSet.GetString(name, true); // if not found, attempt to load for the specified culture while(null == result) { // attempt to load from custom, localized resource resourceSet = GetResourceSet(culture, true); result = resourceSet.GetString(name, true); // if not found, load from non-custom, localize resource if(result == null) { resourceSet = GetResourceSet(culture, false); result = resourceSet.GetString(name, true); } // if not found, attempt to load for the parent culture if available if(null == result) { if(culture.Parent != culture) { culture = culture.Parent; } else { result = def; break; } } } return (result != null) ? StringUtil.UnescapeString(result) : null; } //--- Properties --- private Dictionary<String, ResourceSet> ResourceData { get { // NOTE (steveb): make sure this property is _only_ accessed when a lock is taken! if(null == _resourceData) { _resourceData = new Dictionary<String, ResourceSet>(); } return _resourceData; } } } public class TestResourceSet : ResourceSet { // Note (arnec): This is really a fragile implemementation of a test resource set, but'll do for now. private readonly Dictionary<string, string> _resources = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); public override string GetString(string name) { return _resources.ContainsKey(name) ? _resources[name] : null; } public override string GetString(string name, bool ignoreCase) { return GetString(name); } public void Add(string key, string value) { _resources.Add(key,value); } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Linq; using Moq; using NUnit.Framework; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Tests.Common.Builders; using Umbraco.Extensions; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Models { [TestFixture] public class ContentExtensionsTests { [Test] public void DirtyProperty_Reset_Clears_SavedPublishedState() { IContentTypeService contentTypeService = Mock.Of<IContentTypeService>(); ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); Mock.Get(contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType); Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1); content.PublishedState = PublishedState.Publishing; Assert.IsFalse(content.Published); content.ResetDirtyProperties(false); // resets Assert.AreEqual(PublishedState.Unpublished, content.PublishedState); Assert.IsFalse(content.Published); } [Test] public void DirtyProperty_OnlyIfActuallyChanged_Content() { IContentTypeService contentTypeService = Mock.Of<IContentTypeService>(); ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); Mock.Get(contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType); Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1); // if you assign a content property with its value it is not dirty // if you assign it with another value then back, it is dirty content.ResetDirtyProperties(false); Assert.IsFalse(content.IsPropertyDirty("Published")); content.Published = true; Assert.IsTrue(content.IsPropertyDirty("Published")); content.ResetDirtyProperties(false); Assert.IsFalse(content.IsPropertyDirty("Published")); content.Published = true; Assert.IsFalse(content.IsPropertyDirty("Published")); content.Published = false; content.Published = true; Assert.IsTrue(content.IsPropertyDirty("Published")); } [Test] public void DirtyProperty_OnlyIfActuallyChanged_User() { IContentTypeService contentTypeService = Mock.Of<IContentTypeService>(); ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); Mock.Get(contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType); Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1); IProperty prop = content.Properties.First(); // if you assign a user property with its value it is not dirty // if you assign it with another value then back, it is dirty prop.SetValue("A"); content.ResetDirtyProperties(false); Assert.IsFalse(prop.IsDirty()); prop.SetValue("B"); Assert.IsTrue(prop.IsDirty()); content.ResetDirtyProperties(false); Assert.IsFalse(prop.IsDirty()); prop.SetValue("B"); Assert.IsFalse(prop.IsDirty()); prop.SetValue("A"); prop.SetValue("B"); Assert.IsTrue(prop.IsDirty()); } [Test] public void DirtyProperty_UpdateDate() { IContentTypeService contentTypeService = Mock.Of<IContentTypeService>(); ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); Mock.Get(contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType); Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1); IProperty prop = content.Properties.First(); content.ResetDirtyProperties(false); DateTime d = content.UpdateDate; prop.SetValue("A"); Assert.IsTrue(content.IsAnyUserPropertyDirty()); Assert.IsFalse(content.IsEntityDirty()); Assert.AreEqual(d, content.UpdateDate); content.UpdateDate = DateTime.Now; Assert.IsTrue(content.IsEntityDirty()); Assert.AreNotEqual(d, content.UpdateDate); // so... changing UpdateDate would count as a content property being changed // however in ContentRepository.PersistUpdatedItem, we change UpdateDate AFTER // we've tested for RequiresSaving & RequiresNewVersion so it's OK } [Test] public void DirtyProperty_WasDirty_ContentProperty() { IContentTypeService contentTypeService = Mock.Of<IContentTypeService>(); ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); Mock.Get(contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType); Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1); content.ResetDirtyProperties(false); Assert.IsFalse(content.IsDirty()); Assert.IsFalse(content.WasDirty()); content.Published = false; content.Published = true; Assert.IsTrue(content.IsDirty()); Assert.IsFalse(content.WasDirty()); content.ResetDirtyProperties(false); Assert.IsFalse(content.IsDirty()); Assert.IsFalse(content.WasDirty()); content.Published = false; content.Published = true; content.ResetDirtyProperties(true); // what PersistUpdatedItem does Assert.IsFalse(content.IsDirty()); Assert.IsTrue(content.WasDirty()); content.Published = false; content.Published = true; content.ResetDirtyProperties(); // what PersistUpdatedItem does Assert.IsFalse(content.IsDirty()); Assert.IsTrue(content.WasDirty()); } [Test] public void DirtyProperty_WasDirty_ContentSortOrder() { IContentTypeService contentTypeService = Mock.Of<IContentTypeService>(); ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); Mock.Get(contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType); Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1); content.ResetDirtyProperties(false); Assert.IsFalse(content.IsDirty()); Assert.IsFalse(content.WasDirty()); content.SortOrder = 0; content.SortOrder = 1; Assert.IsTrue(content.IsDirty()); Assert.IsFalse(content.WasDirty()); content.ResetDirtyProperties(false); Assert.IsFalse(content.IsDirty()); Assert.IsFalse(content.WasDirty()); content.SortOrder = 0; content.SortOrder = 1; content.ResetDirtyProperties(true); // what PersistUpdatedItem does Assert.IsFalse(content.IsDirty()); Assert.IsTrue(content.WasDirty()); content.SortOrder = 0; content.SortOrder = 1; content.ResetDirtyProperties(); // what PersistUpdatedItem does Assert.IsFalse(content.IsDirty()); Assert.IsTrue(content.WasDirty()); } [Test] public void DirtyProperty_WasDirty_UserProperty() { IContentTypeService contentTypeService = Mock.Of<IContentTypeService>(); ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); Mock.Get(contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType); Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1); IProperty prop = content.Properties.First(); content.ResetDirtyProperties(false); Assert.IsFalse(content.IsDirty()); Assert.IsFalse(content.WasDirty()); prop.SetValue("a"); prop.SetValue("b"); Assert.IsTrue(content.IsDirty()); Assert.IsFalse(content.WasDirty()); content.ResetDirtyProperties(false); Assert.IsFalse(content.IsDirty()); Assert.IsFalse(content.WasDirty()); prop.SetValue("a"); prop.SetValue("b"); content.ResetDirtyProperties(true); // what PersistUpdatedItem does Assert.IsFalse(content.IsDirty()); //// Assert.IsFalse(content.WasDirty()); // not impacted by user properties Assert.IsTrue(content.WasDirty()); // now it is! prop.SetValue("a"); prop.SetValue("b"); content.ResetDirtyProperties(); // what PersistUpdatedItem does Assert.IsFalse(content.IsDirty()); //// Assert.IsFalse(content.WasDirty()); // not impacted by user properties Assert.IsTrue(content.WasDirty()); // now it is! } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using DevExpress.Internal.WinApi; using DevExpress.Internal.WinApi.Windows.UI.Notifications; namespace DevExpress.Internal { public class WinRTToastNotificationFactory : IPredefinedToastNotificationFactory { readonly string appId; public WinRTToastNotificationFactory(string appId) { this.appId = appId; } public IPredefinedToastNotification CreateToastNotification(IPredefinedToastNotificationContent content) { return new WinRTToastNotification(content, () => ToastNotificationManager.CreateToastNotificationAdapter(appId)); } public IPredefinedToastNotification CreateToastNotification(string bodyText) { return CreateToastNotification(DefaultFactory.CreateContent(bodyText)); } public IPredefinedToastNotification CreateToastNotificationOneLineHeaderContent(string headlineText, string bodyText) { return CreateToastNotification(DefaultFactory.CreateOneLineHeaderContent(headlineText, bodyText)); } public IPredefinedToastNotification CreateToastNotificationOneLineHeaderContent(string headlineText, string bodyText1, string bodyText2) { return CreateToastNotification(DefaultFactory.CreateOneLineHeaderContent(headlineText, bodyText1, bodyText2)); } public IPredefinedToastNotification CreateToastNotificationTwoLineHeader(string headlineText, string bodyText) { return CreateToastNotification(DefaultFactory.CreateTwoLineHeaderContent(headlineText, bodyText)); } #region IPredefinedToastNotificationContentFactory IPredefinedToastNotificationContentFactory factoryCore; IPredefinedToastNotificationContentFactory DefaultFactory { get { if(factoryCore == null) factoryCore = CreateContentFactory(); return factoryCore; } } public double ImageSize { get { return DevExpress.Utils.WindowsVersionProvider.IsWin10AnniversaryUpdateOrHigher ? 48 : 90; } } public virtual IPredefinedToastNotificationContentFactory CreateContentFactory() { return new WinRTToastNotificationContentFactory(); } class WinRTToastNotificationContentFactory : IPredefinedToastNotificationContentFactory, IPredefinedToastNotificationContentFactoryGeneric { public IPredefinedToastNotificationContent CreateContent(string bodyText) { return WinRTToastNotificationContent.Create(bodyText); } public IPredefinedToastNotificationContent CreateOneLineHeaderContent(string headlineText, string bodyText) { return WinRTToastNotificationContent.CreateOneLineHeader(headlineText, bodyText); } public IPredefinedToastNotificationContent CreateTwoLineHeaderContent(string headlineText, string bodyText) { return WinRTToastNotificationContent.CreateTwoLineHeader(headlineText, bodyText); } public IPredefinedToastNotificationContent CreateOneLineHeaderContent(string headlineText, string bodyText1, string bodyText2) { return WinRTToastNotificationContent.CreateOneLineHeader(headlineText, bodyText1, bodyText2); } public IPredefinedToastNotificationContent CreateToastGeneric(string headlineText, string bodyText1, string bodyText2) { return WinRTToastNotificationContent.CreateToastGeneric(headlineText, bodyText1, bodyText2); } } #endregion IPredefinedToastNotificationContentFactory } public class WinRTToastNotification : IPredefinedToastNotification { ToastNotificationHandlerInfo<HandlerDismissed> handlerDismissed; ToastNotificationHandlerInfo<HandlerActivated> handlerActivated; ToastNotificationHandlerInfo<HandlerFailed> handlerFailed; IPredefinedToastNotificationContent contentCore; Lazy<IToastNotificationAdapter> adapterCore; internal WinRTToastNotification(IPredefinedToastNotificationContent content, Func<IToastNotificationAdapter> adapterRoutine) { if(content == null) throw new ArgumentNullException("content"); this.adapterCore = new Lazy<IToastNotificationAdapter>(adapterRoutine); this.contentCore = content; this.handlerDismissed = new ToastNotificationHandlerInfo<HandlerDismissed>(() => new HandlerDismissed(this)); this.handlerActivated = new ToastNotificationHandlerInfo<HandlerActivated>(() => new HandlerActivated(this)); this.handlerFailed = new ToastNotificationHandlerInfo<HandlerFailed>(() => new HandlerFailed(this)); } public IPredefinedToastNotificationContent Content { get { return contentCore; } } internal IToastNotificationAdapter Adapter { get { return adapterCore.Value; } } #region Events internal delegate void TypedEventHandler<TSender, TResult>(TSender sender, TResult args); internal event TypedEventHandler<IPredefinedToastNotification, ToastDismissalReason> Dismissed { add { handlerDismissed.Handler.Subscribe(value); } remove { handlerDismissed.Handler.Unsubscribe(value); } } internal event TypedEventHandler<IPredefinedToastNotification, string> Activated { add { handlerActivated.Handler.Subscribe(value); } remove { handlerActivated.Handler.Unsubscribe(value); } } internal event TypedEventHandler<IPredefinedToastNotification, ToastNotificationFailedException> Failed { add { handlerFailed.Handler.Subscribe(value); } remove { handlerFailed.Handler.Unsubscribe(value); } } #endregion Events #region Handlers class ToastNotificationHandlerInfo<THandler> { public ToastNotificationHandlerInfo(Func<THandler> initializer) { Handler = initializer(); } public EventRegistrationToken Token; public THandler Handler { get; private set; } } class ToastNotificationHandler<THandler> { List<THandler> handlers; WinRTToastNotification toast; public ToastNotificationHandler(WinRTToastNotification toast) { this.handlers = new List<THandler>(); this.toast = toast; } public void Subscribe(THandler handler) { handlers.Add(handler); } public void Unsubscribe(THandler handler) { handlers.Remove(handler); } protected int InvokeCore<TArgs>(IToastNotification sender, TArgs args, Action<THandler, WinRTToastNotification, TArgs> action) { lock(this) { using(toast.Content) { handlers.ForEach((h) => action(h, toast, args)); handlers.Clear(); } } return 0; } } sealed class HandlerDismissed : ToastNotificationHandler<TypedEventHandler<IPredefinedToastNotification, ToastDismissalReason>>, ITypedEventHandler_IToastNotification_Dismissed { public HandlerDismissed(WinRTToastNotification sender) : base(sender) { } public int Invoke(IToastNotification sender, IToastDismissedEventArgs args) { return InvokeCore(sender, args, (h, s, a) => h(s, a.Reason)); } } sealed class HandlerActivated : ToastNotificationHandler<TypedEventHandler<IPredefinedToastNotification, string>>, ITypedEventHandler_IToastNotification_Activated { public HandlerActivated(WinRTToastNotification sender) : base(sender) { } public int Invoke(IToastNotification sender, IInspectable args) { return InvokeCore(sender, GetActivationString(args as IToastActivatedEventArgs), (h, s, a) => h(s, a)); } string GetActivationString(IToastActivatedEventArgs args) { HSTRING activationString = new HSTRING(); if(args != null) { args.GetArguments(out activationString); } return activationString.GetString(); } } sealed class HandlerFailed : ToastNotificationHandler<TypedEventHandler<IPredefinedToastNotification, ToastNotificationFailedException>>, ITypedEventHandler_IToastNotification_Failed { public HandlerFailed(WinRTToastNotification sender) : base(sender) { } public int Invoke(IToastNotification sender, IToastFailedEventArgs args) { return InvokeCore(sender, args, (h, s, a) => h(s, ToastNotificationFailedException.ToException(a.Error))); } } #endregion Handlers IToastNotification Notification; const uint WPN_E_TOAST_NOTIFICATION_DROPPED = 0x803E0207; public Task<ToastNotificationResultInternal> ShowAsync() { if(Notification == null) Notification = Adapter.Create(Content.Info); Subscribe(); var state = ToastActivationAsyncState.Create(); var source = new TaskCompletionSource<ToastNotificationResultInternal>(state); Activated += (s, args) => { Unsubscribe(); ToastActivationAsyncState.SetActivationArgs(source.Task, args); source.SetResult(ToastNotificationResultInternal.Activated); }; Dismissed += (s, reason) => { Unsubscribe(); switch(reason) { case ToastDismissalReason.ApplicationHidden: source.SetResult(ToastNotificationResultInternal.ApplicationHidden); break; case ToastDismissalReason.TimedOut: source.SetResult(ToastNotificationResultInternal.TimedOut); break; case ToastDismissalReason.UserCanceled: source.SetResult(ToastNotificationResultInternal.UserCanceled); break; } }; Failed += (s, exception) => { Unsubscribe(); if((uint)exception.ErrorCode == WPN_E_TOAST_NOTIFICATION_DROPPED) source.SetResult(ToastNotificationResultInternal.Dropped); else source.SetException(exception); }; ComFunctions.Safe(() => Adapter.Show(Notification), ce => { Unsubscribe(); source.SetException(new ToastNotificationFailedException(ce, ce.ErrorCode)); }); return source.Task; } public void Hide() { if(Notification == null) return; Adapter.Hide(Notification); } void Subscribe() { if(Notification == null) return; Notification.AddDismissed(handlerDismissed.Handler, out handlerDismissed.Token); Notification.AddActivated(handlerActivated.Handler, out handlerActivated.Token); Notification.AddFailed(handlerFailed.Handler, out handlerFailed.Token); } void Unsubscribe() { if(Notification == null) return; Notification.RemoveDismissed(handlerDismissed.Token); Notification.RemoveActivated(handlerActivated.Token); Notification.RemoveFailed(handlerFailed.Token); } } #region State public static class ToastActivationAsyncState { sealed class State { public string Arguments; } internal static object Create() { return new State(); } internal static void SetActivationArgs(Task<ToastNotificationResultInternal> task, string args) { ((State)task.AsyncState).Arguments = args; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static string ActivationArgs(this Task<ToastNotificationResultInternal> task) { return ((State)task.AsyncState).Arguments; } } #endregion State }
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls.Primitives; using System.Windows.Data; using Caliburn.Micro.Telerik; using Telerik.Windows.Controls; using WindowStartupLocation = Telerik.Windows.Controls.WindowStartupLocation; namespace Caliburn.Micro { /// <summary> /// A service that manages windows. /// Implementation for <see cref="RadWindow"/> /// </summary> public class TelerikWindowManager : IWindowManager { /// <summary> /// Shows a modal dialog for the specified model. /// /// By default RadWindow dialog is shown at the center of the screen /// </summary> /// <param name="rootModel">The root model.</param> /// <param name="context">The context.</param> /// <param name="settings">The optional RadWindow settings.</param> public virtual void ShowDialog(object rootModel, object context = null, IDictionary<string, object> settings = null) { var view = PrepareRadWindow(rootModel, context, settings); view.ShowDialog(); } /// <summary> /// Shows a normal, non-modal dialog for the specified model. /// /// By default RadWindow dialog is shown at the center of the screen /// </summary> /// <param name="rootModel">The root model.</param> /// <param name="context">The context.</param> /// <param name="settings">The optional RadWindow settings.</param> public virtual void Show(object rootModel, object context = null, IDictionary<string, object> settings = null) { var view = PrepareRadWindow(rootModel, context, settings); view.Show(); } private RadWindow PrepareRadWindow(object rootModel, object context, IDictionary<string, object> settings) { var view = EnsureWindow(rootModel, ViewLocator.LocateForModel(rootModel, null, context)); ViewModelBinder.Bind(rootModel, view, context); var haveDisplayName = rootModel as IHaveDisplayName; if (haveDisplayName != null && !ConventionManager.HasBinding(view, RadWindow.HeaderProperty)) { var binding = new Binding("DisplayName") {Mode = BindingMode.TwoWay}; view.SetBinding(RadWindow.HeaderProperty, binding); } new RadWindowConductor(rootModel, view); ApplySettings(view, settings); return view; } /// <summary> /// Shows a toast notification for the specified model. /// </summary> /// <param name="rootModel">The root model.</param> /// <param name="durationInMilliseconds">How long the notification should appear for.</param> /// <param name="context">The context.</param> /// <param name="settings">The optional RadWindow Settings</param> public void ShowNotification(object rootModel, int durationInMilliseconds, object context = null, IDictionary<string, object> settings = null) { var window = new NotificationWindow(); var view = ViewLocator.LocateForModel(rootModel, window, context); ViewModelBinder.Bind(rootModel, view, null); window.Content = (FrameworkElement)view; ApplySettings(window, settings); var activator = rootModel as IActivate; if (activator != null) activator.Activate(); var deactivator = rootModel as IDeactivate; if (deactivator != null) window.Closed += delegate { deactivator.Deactivate(true); }; window.Show(durationInMilliseconds); } /// <summary> /// Shows a popup at the current mouse position. /// </summary> /// <param name="rootModel">The root model.</param> /// <param name="context">The view context.</param> /// <param name="settings">The optional popup settings.</param> public virtual void ShowPopup(object rootModel, object context = null, IDictionary<string, object> settings = null) { var popup = CreatePopup(rootModel, settings); var view = ViewLocator.LocateForModel(rootModel, popup, context); popup.Child = view; popup.SetValue(View.IsGeneratedProperty, true); ViewModelBinder.Bind(rootModel, popup, null); var activatable = rootModel as IActivate; if (activatable != null) activatable.Activate(); var deactivator = rootModel as IDeactivate; if (deactivator != null) popup.Closed += delegate { deactivator.Deactivate(true); }; popup.IsOpen = true; popup.CaptureMouse(); } /// <summary> /// Creates a popup for hosting a popup window. /// </summary> /// <param name="rootModel">The model.</param> /// <param name="settings">The optional popup settings.</param> /// <returns>The popup.</returns> protected virtual Popup CreatePopup(object rootModel, IDictionary<string, object> settings) { var popup = new Popup { HorizontalOffset = Mouse.Position.X, VerticalOffset = Mouse.Position.Y }; if (settings != null) { var type = popup.GetType(); foreach (var pair in settings) { var propertyInfo = type.GetProperty(pair.Key); if (propertyInfo != null) propertyInfo.SetValue(popup, pair.Value, null); } } return popup; } bool ApplySettings(object target, IEnumerable<KeyValuePair<string, object>> settings) { if (settings != null) { var type = target.GetType(); foreach (var pair in settings) { var propertyInfo = type.GetProperty(pair.Key); if (propertyInfo != null) propertyInfo.SetValue(target, pair.Value, null); } return true; } return false; } private static RadWindow EnsureWindow(object model, object view) { var window = view as RadWindow; if (window == null) { window = new RadWindow { Content = view, WindowStartupLocation = WindowStartupLocation.CenterScreen }; window.SetValue(View.IsGeneratedProperty, true); } return window; } public static void Alert(string title, string message) { Alert(new DialogParameters { Header = title, Content = message }); } public static void Alert(DialogParameters dialogParameters) { RadWindow.Alert(dialogParameters); } public static void Confirm(string title, string message, System.Action onOK, System.Action onCancel = null) { var dialogParameters = new DialogParameters { Header = title, Content = message }; dialogParameters.Closed += (sender, args) => { var result = args.DialogResult; if (result.HasValue && result.Value) { onOK(); return; } if(onCancel != null) onCancel(); }; Confirm(dialogParameters); } public static void Confirm(DialogParameters dialogParameters) { RadWindow.Confirm(dialogParameters); } public static void Prompt(string title, string message, string defaultPromptResultValue, Action<string> onOK) { var dialogParameters = new DialogParameters { Header = title, Content = message, DefaultPromptResultValue = defaultPromptResultValue, }; dialogParameters.Closed += (o, args) => { if (args.DialogResult.HasValue && args.DialogResult.Value) onOK(args.PromptResult); }; Prompt(dialogParameters); } public static void Prompt(DialogParameters dialogParameters) { RadWindow.Prompt(dialogParameters); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Mappy.Areas.HelpPage.ModelDescriptions; using Mappy.Areas.HelpPage.Models; namespace Mappy.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using NUnit.Framework; using SIL.Windows.Forms.HotSpot; namespace SIL.Windows.Forms.Tests.Hotspot { [TestFixture] public class HotSpotProviderTests { private HotSpotProvider _hotSpotProvider; [SetUp] public void Setup() { _hotSpotProvider = new HotSpotProvider(); } [TearDown] public void Teardown() { _hotSpotProvider.Dispose(); } [Test] public void Construct() { using (HotSpotProvider hotSpotProvider = new HotSpotProvider()) { Assert.IsNotNull(hotSpotProvider); } } [Test] public void CanExtend_TextBox_True() { using (TextBox textBox = new TextBox()) { Assert.IsTrue(((IExtenderProvider) _hotSpotProvider).CanExtend(textBox)); } } [Test] public void CanExtend_RichTextBox_True() { using (RichTextBox textBox = new RichTextBox()) { Assert.IsTrue(((IExtenderProvider) _hotSpotProvider).CanExtend(textBox)); } } [Test] public void CanExtend_ComboBox_False() { using (ComboBox comboBox = new ComboBox()) { Assert.IsFalse(((IExtenderProvider) _hotSpotProvider).CanExtend(comboBox)); } } [Test] public void CanExtend_Null_False() { Assert.IsFalse(((IExtenderProvider) _hotSpotProvider).CanExtend(null)); } [Test] public void CanExtend_CalledAfterDisposed_Throws() { HotSpotProvider hotSpotProvider = new HotSpotProvider(); hotSpotProvider.Dispose(); using (TextBox textBox = new TextBox()) { Assert.Throws<ObjectDisposedException>(() => hotSpotProvider.CanExtend(textBox)); } } [Test] public void GetEnableHotSpots_Null_Throws() { Assert.Throws<ArgumentNullException>(() => _hotSpotProvider.GetEnableHotSpots(null)); } [Test] public void GetEnableHotSpots_ComboBox_Throws() { using (ComboBox comboBox = new ComboBox()) { Assert.Throws<ArgumentException>(() => _hotSpotProvider.GetEnableHotSpots(comboBox)); } } [Test] public void GetEnableHotSpots_NeverSet_False() { using (TextBox textBox = new TextBox()) { Assert.IsFalse(_hotSpotProvider.GetEnableHotSpots(textBox)); } } [Test] public void GetEnableHotSpots_SetTrue_True() { using (TextBox textBox = new TextBox()) { _hotSpotProvider.SetEnableHotSpots(textBox, true); Assert.IsTrue(_hotSpotProvider.GetEnableHotSpots(textBox)); } } [Test] public void GetEnableHotSpots_CalledAfterDisposed_Throws() { HotSpotProvider hotSpotProvider = new HotSpotProvider(); hotSpotProvider.Dispose(); using (TextBox textBox = new TextBox()) { Assert.Throws<ObjectDisposedException>(() => hotSpotProvider.GetEnableHotSpots(textBox)); } } [Test] public void GetEnableHotSpots_SetFalse_False() { using (TextBox textBox = new TextBox()) { _hotSpotProvider.SetEnableHotSpots(textBox, false); Assert.IsFalse(_hotSpotProvider.GetEnableHotSpots(textBox)); } } [Test] public void SetEnableHotSpots_NullControl_EmptyString() { Assert.Throws<ArgumentNullException>(() => _hotSpotProvider.SetEnableHotSpots(null, true)); } [Test] public void SetEnableHotSpots_ComboBox_Throws() { using (ComboBox comboBox = new ComboBox()) { Assert.Throws<ArgumentException>(() => _hotSpotProvider.SetEnableHotSpots(comboBox, true)); } } [Test] public void SetEnableHotSpots_SetTwice_GetSecond() { using (TextBox textBox = new TextBox()) { _hotSpotProvider.SetEnableHotSpots(textBox, true); _hotSpotProvider.SetEnableHotSpots(textBox, false); Assert.IsFalse(_hotSpotProvider.GetEnableHotSpots(textBox)); } } [Test] public void SetEnableHotSpots_CalledAfterDisposed_Throws() { HotSpotProvider hotSpotProvider = new HotSpotProvider(); hotSpotProvider.Dispose(); using (TextBox textBox = new TextBox()) { Assert.Throws<ObjectDisposedException>(() => hotSpotProvider.SetEnableHotSpots(textBox, false)); } } [Test] public void Dispose_HasDisposedEventHandler_CallsHandler() { HotSpotProvider hotSpotProvider = new HotSpotProvider(); bool disposedCalled = false; hotSpotProvider.Disposed += delegate { disposedCalled = true; }; Assert.IsFalse(disposedCalled); hotSpotProvider.Dispose(); Assert.IsTrue(disposedCalled); } [Test] public void Dispose_CalledTwice_CallsHandlerOnce() { HotSpotProvider hotSpotProvider = new HotSpotProvider(); int disposedCalledCount = 0; hotSpotProvider.Disposed += delegate { ++disposedCalledCount; }; Assert.AreEqual(0, disposedCalledCount); hotSpotProvider.Dispose(); Assert.AreEqual(1, disposedCalledCount); hotSpotProvider.Dispose(); Assert.AreEqual(1, disposedCalledCount); } [Test] public void GetSite_CalledAfterDisposed_Throws() { HotSpotProvider hotSpotProvider = new HotSpotProvider(); hotSpotProvider.Dispose(); ISite x; Assert.Throws<ObjectDisposedException>(() => x = hotSpotProvider.Site); } [Test] public void SetSite_CalledAfterDisposed_Throws() { HotSpotProvider hotSpotProvider = new HotSpotProvider(); hotSpotProvider.Dispose(); Assert.Throws<ObjectDisposedException>(() => hotSpotProvider.Site = null); } [Test] public void Refresh_HotSpotsAreNotEnabledOnControl_DoNothing() { using (TextBox textBox = new TextBox()) { bool retrieveHotSpotsCalled = false; _hotSpotProvider.RetrieveHotSpots += delegate { retrieveHotSpotsCalled = true; }; Assert.IsFalse(retrieveHotSpotsCalled); _hotSpotProvider.Refresh(textBox); Assert.IsFalse(retrieveHotSpotsCalled); } } [Test] public void Refresh_HotSpotsAreEnabled_TriggersRetrieveHotSpotEvent() { using (TextBox textBox = new TextBox()) { _hotSpotProvider.SetEnableHotSpots(textBox, true); bool retrieveHotSpotsCalled = false; _hotSpotProvider.RetrieveHotSpots += delegate { retrieveHotSpotsCalled = true; }; // reset since installing the handler causes it to fire. retrieveHotSpotsCalled = false; _hotSpotProvider.Refresh(textBox); Assert.IsTrue(retrieveHotSpotsCalled); } } [Test] public void RetrieveHotSpots_AddingAHandler_CausesHotSpotsToBeRetrieved() { bool handlerCalled = false; using (TextBox textBox = new TextBox()) { _hotSpotProvider.SetEnableHotSpots(textBox, true); _hotSpotProvider.RetrieveHotSpots += delegate { handlerCalled = true; }; } Assert.IsTrue(handlerCalled); } [Test] public void RefreshAll_TriggersRetrieveHotSpotEventForAllEnabled() { TextBox textBox1 = new TextBox(); TextBox textBox2 = new TextBox(); TextBox textBox3 = new TextBox(); TextBox textBox4 = new TextBox(); _hotSpotProvider.SetEnableHotSpots(textBox1, true); _hotSpotProvider.SetEnableHotSpots(textBox2, false); _hotSpotProvider.SetEnableHotSpots(textBox3, false); _hotSpotProvider.SetEnableHotSpots(textBox4, true); bool retrieveHotSpots1Called = false; bool retrieveHotSpots2Called = false; bool retrieveHotSpots3Called = false; bool retrieveHotSpots4Called = false; _hotSpotProvider.RetrieveHotSpots += delegate(object sender, RetrieveHotSpotsEventArgs e) { if (e.Control == textBox1) { retrieveHotSpots1Called = true; return; } if (e.Control == textBox2) { retrieveHotSpots2Called = true; return; } if (e.Control == textBox3) { retrieveHotSpots3Called = true; return; } if (e.Control == textBox4) { retrieveHotSpots4Called = true; return; } throw new InvalidOperationException(); }; // reset since installing the handler causes it to fire. retrieveHotSpots1Called = false; retrieveHotSpots2Called = false; retrieveHotSpots3Called = false; retrieveHotSpots4Called = false; // force hotSpotProvider to retrieve HotSpots _hotSpotProvider.RefreshAll(); Assert.IsTrue(retrieveHotSpots1Called); Assert.IsFalse(retrieveHotSpots2Called); Assert.IsFalse(retrieveHotSpots3Called); Assert.IsTrue(retrieveHotSpots4Called); textBox1.Dispose(); textBox2.Dispose(); textBox3.Dispose(); textBox4.Dispose(); } [Test] [NUnit.Framework.Category("KnownMonoIssue")] // review: WS-???? public void RetrieveHotSpots_GiveSomeHotspots_HotSpotsVisible() { using (TextBox textBox = new TextBox()) { textBox.Text = "Now is the time for all good men to come to the aid..."; _hotSpotProvider.SetEnableHotSpots(textBox, true); _hotSpotProvider.RetrieveHotSpots += delegate(object sender, RetrieveHotSpotsEventArgs e) { e.AddHotSpot(new HotSpot.HotSpot(e.Control, 7, 3)); e.AddHotSpot(new HotSpot.HotSpot(e.Control, 16, 3)); }; Point position = textBox.GetPositionFromCharIndex(8); List<HotSpot.HotSpot> hotSpots = new List<HotSpot.HotSpot>( _hotSpotProvider.GetHotSpotsFromPosition(textBox, position)); Assert.AreEqual(1, hotSpots.Count); Assert.AreEqual(7, hotSpots[0].Offset); Assert.AreEqual("the", hotSpots[0].Text); position = textBox.GetPositionFromCharIndex(16); hotSpots = new List<HotSpot.HotSpot>( _hotSpotProvider.GetHotSpotsFromPosition(textBox, position)); Assert.AreEqual(1, hotSpots.Count); Assert.AreEqual(16, hotSpots[0].Offset); Assert.AreEqual("for", hotSpots[0].Text); } } [Test] public void RetrieveHotSpots_NoHotspotsReturned_NoHotSpotsVisible() { using (TextBox textBox = new TextBox()) { textBox.Text = "Now is the time."; _hotSpotProvider.SetEnableHotSpots(textBox, true); _hotSpotProvider.RetrieveHotSpots += delegate { // give back no hot spots }; //if we scan the entire text for hot spots we shouldn't find any for (int i = 0;i != textBox.Text.Length;++i) { Point position = textBox.GetPositionFromCharIndex(i); List<HotSpot.HotSpot> hotSpots = new List<HotSpot.HotSpot>( _hotSpotProvider.GetHotSpotsFromPosition(textBox, position)); Assert.AreEqual(0, hotSpots.Count); } } } [Test] public void RetrieveHotSpots_CalledWhenTheTextChanges() { using (TextBox textBox = new TextBox()) { bool hotSpotsWereRetrieved; textBox.Text = "Now is the time."; _hotSpotProvider.SetEnableHotSpots(textBox, true); _hotSpotProvider.RetrieveHotSpots += delegate { hotSpotsWereRetrieved = true; }; hotSpotsWereRetrieved = false; textBox.Text = "For all Good Men..."; Assert.IsTrue(hotSpotsWereRetrieved); } } } }
using System; using System.Collections.Generic; static class Program { static void Foreach<T>(this IList<T> arr, Action<T> f) { foreach (T x in arr) f(x); } static void Foreach<T>(this IList<T> arr, Action<T, int> f) { for (int i = 0; i < arr.Count; i++) f(arr[i], i); } static List<R> Map<T, R>(this IList<T> arr, Func<T, R> f) { List<R> result = new List<R>(); foreach (T x in arr) result.Add(f(x)); return result; } static List<T> Filter<T>(this IList<T> arr, Predicate<T> f) { List<T> result = new List<T>(); foreach (T x in arr) if (f(x)) result.Add(x); return result; } static T Reduce<T>(this IList<T> arr, Func<T, T, T> f) { T current = arr[0]; for (int i = 1; i < arr.Count; i++) current = f(current, arr[i]); return current; } static T Reduce<T>(this IList<T> arr, Func<T, T, T> f, T first) { T current = first; for (int i = 0; i < arr.Count; i++) current = f(current, arr[i]); return current; } static Func<T, T> Compose1<T>(Func<T, T> result, params Func<T, T>[] arr) { if (arr.Length == 0) return result; return Compose1( new Func<T, T>(x => arr[0](result(x))), System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Skip(arr, 1)) ); } static Func<T, T> Compose2<T>(params Func<T, T>[] arr) { Func<T, T> result = arr[0]; for (int i = 1; i < arr.Length; i++) { Func<T, T> temp = result; Func<T, T> f = arr[i]; result = x => f(temp(x)); // Save closure } return result; } static Func<T, T> Compose<T>(params Func<T, T>[] arr) { return arr.Reduce((a, b) => x => b(a(x))); } static Func<T, T> Repeat<T>(Func<T, T> f, int n) { //return new Func<T, T>[n].Reduce((a, _) => Compose(a, f), x => x); // Like the count method return new Func<T, T>[n].Map(x => f).Reduce((a, b) => Compose(a, b)); // Without using first } static Func<T[]> Curry<T>(T[] arguments) { } // TODO: YCombinator, Currying static void Main() { List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 }; { //Console.WriteLine("Foreach: x"); //numbers.Foreach(x => Console.WriteLine(x)); //Console.WriteLine("Foreach: x * 2"); //numbers.Foreach(x => Console.WriteLine(x * 2)); //Console.WriteLine("Foreach: x * x"); //numbers.Foreach(x => Console.WriteLine(x * x)); } { //Console.WriteLine("Foreach: x, i"); //numbers.Foreach((x, i) => Console.WriteLine("arr[{0}] = {1}", i, x)); } { //Console.WriteLine("Print"); //Print(numbers); } { //Console.WriteLine("Map: x * 2"); //Print(numbers.Map(x => x * 2)); //Console.WriteLine("Map: x * x"); //Print(numbers.Map(x => x * x)); //Console.WriteLine("Map: 2 ^ x"); //Print(numbers.Map(x => Math.Pow(2, x))); //Console.WriteLine("Map: Binary(x) "); //Print(numbers.Map(x => Convert.ToString(x, 2))); //Console.WriteLine("Map: \"1 2 3 4 5\".Parse()"); //Print("1 2 3 4 5".Split().Map(int.Parse)); } { //Console.WriteLine("Filter: x % 2 == 0"); //Print(numbers.Filter(x => x % 2 == 0)); //Console.WriteLine("Filter: x > 2"); //Print(numbers.Filter(x => x > 2)); } { //// Sum //Console.WriteLine("Reduce: a + b"); //Print(numbers.Reduce((a, b) => a + b)); //// Product //Console.WriteLine("Reduce: a * b"); //Print(numbers.Reduce((a, b) => a * b)); //// Min //Console.WriteLine("Reduce: a < b"); //Print(numbers.Reduce((a, b) => a < b ? a : b)); //// Max //Console.WriteLine("Reduce: a > b"); //Print(numbers.Reduce((a, b) => a > b ? a : b)); //Console.WriteLine("Join"); //Print(numbers.Map(x => Convert.ToString(x)).Reduce((a, b) => a + ", " + b)); //Console.WriteLine("Count"); //Print(numbers.Reduce((a, _) => a + 1) - numbers[0] + 1); //Print(numbers.Reduce((a, _) => a + 1, 0)); //Console.WriteLine("Negative sum"); //Print(numbers.Reduce((a, b) => a - b, 0)); } { //Console.WriteLine("Compose: f0(x) = x + 1; f0(1)"); //Print(Compose<int>(x => x + 1)(1)); //Console.WriteLine("Compose: f0(x) = x + 1; f1(x) = x * 2; f1(f0(1))"); //Print(Compose<int>(x => x + 1, x => x * 2)(1)); //Console.WriteLine("Compose: f0(x) = x + 1; f1(x) = x * 2; f2(x) = x * x; f2(f1(f0(1)))"); //Print(Compose<int>(x => x + 1, x => x * 2, x => x * x)(1)); //Print(Compose(Compose(Compose<int>(x => x + 1), x => x * 2), x => x * x)(1)); } { //Console.WriteLine("Repeat: f(x) = x * x; f(f(f(2)))"); //Print(Repeat<int>(x => x * x, 4)(2)); } { //Console.WriteLine("Map: x * 5"); //Print(numbers.Map(x => x * 5)); //Console.WriteLine("Map: x * 5; Filter: x > 12"); //Print(numbers.Map(x => 5 * x).Filter(x => x > 12)); //Console.WriteLine("Map: x * 5; Filter: x > 12; Reduce: a + b"); //Print(numbers.Map(x => 5 * x).Filter(x => x > 12).Reduce((a, b) => a + b)); } { Console.WriteLine("Curry"); var f = Curry(); } } static void Print<T>(IList<T> arr) { arr.Foreach(Console.WriteLine); } static void Print(object obj) { Console.WriteLine(obj); } }
// // location.cs: Keeps track of the location of source code entity // // Author: // Miguel de Icaza // Atsushi Enomoto <atsushi@ximian.com> // Marek Safar (marek.safar@gmail.com) // // Copyright 2001 Ximian, Inc. // Copyright 2005 Novell, Inc. // using System; using System.IO; using System.Collections.Generic; using Mono.CompilerServices.SymbolWriter; using System.Diagnostics; using System.Linq; namespace Mono.CSharp { /// <summary> /// This is one single source file. /// </summary> /// <remarks> /// This is intentionally a class and not a struct since we need /// to pass this by reference. /// </remarks> public class SourceFile : ISourceFile { public readonly string Name; public readonly string Path; public readonly int Index; public bool AutoGenerated; public bool IsIncludeFile; SourceFileEntry file; byte[] guid, checksum; public SourceFile (string name, string path, int index, bool is_include) { this.Index = index; this.Name = name; this.Path = path; this.IsIncludeFile = is_include; } public SourceFileEntry SourceFileEntry { get { return file; } } SourceFileEntry ISourceFile.Entry { get { return file; } } public void SetChecksum (byte[] guid, byte[] checksum) { this.guid = guid; this.checksum = checksum; } public virtual void DefineSymbolInfo (MonoSymbolWriter symwriter) { if (guid != null) file = symwriter.DefineDocument (Path, guid, checksum); else { file = symwriter.DefineDocument (Path); if (AutoGenerated) file.SetAutoGenerated (); } } public override string ToString () { return String.Format ("SourceFile ({0}:{1}:{2}:{3})", Name, Path, Index, SourceFileEntry); } } public class CompilationUnit : SourceFile, ICompileUnit { CompileUnitEntry comp_unit; Dictionary<string, SourceFile> include_files; Dictionary<string, bool> conditionals; public CompilationUnit (string name, string path, int index) : base (name, path, index, false) { } public void AddFile (SourceFile file) { if (file == this) return; if (include_files == null) include_files = new Dictionary<string, SourceFile> (); if (!include_files.ContainsKey (file.Path)) include_files.Add (file.Path, file); } public void AddDefine (string value) { if (conditionals == null) conditionals = new Dictionary<string, bool> (2); conditionals [value] = true; } public void AddUndefine (string value) { if (conditionals == null) conditionals = new Dictionary<string, bool> (2); conditionals [value] = false; } CompileUnitEntry ICompileUnit.Entry { get { return comp_unit; } } public CompileUnitEntry CompileUnitEntry { get { return comp_unit; } } public override void DefineSymbolInfo (MonoSymbolWriter symwriter) { base.DefineSymbolInfo (symwriter); comp_unit = symwriter.DefineCompilationUnit (SourceFileEntry); if (include_files != null) { foreach (SourceFile include in include_files.Values) { include.DefineSymbolInfo (symwriter); comp_unit.AddFile (include.SourceFileEntry); } } } public bool IsConditionalDefined (string value) { if (conditionals != null) { bool res; if (conditionals.TryGetValue (value, out res)) return res; // When conditional was undefined if (conditionals.ContainsKey (value)) return false; } return RootContext.IsConditionalDefined (value); } } /// <summary> /// Keeps track of the location in the program /// </summary> /// /// <remarks> /// This uses a compact representation and a couple of auxiliary /// structures to keep track of tokens to (file,line and column) /// mappings. The usage of the bits is: /// /// - 16 bits for "checkpoint" which is a mixed concept of /// file and "line segment" /// - 8 bits for line delta (offset) from the line segment /// - 8 bits for column number. /// /// http://lists.ximian.com/pipermail/mono-devel-list/2004-December/009508.html /// </remarks> public struct Location : IEquatable<Location> { struct Checkpoint { public readonly int LineOffset; public readonly int CompilationUnit; public readonly int File; public Checkpoint (int compile_unit, int file, int line) { File = file; CompilationUnit = compile_unit; LineOffset = line - (int) (line % (1 << line_delta_bits)); } } #if FULL_AST long token; const int column_bits = 24; const int line_delta_bits = 24; #else int token; const int column_bits = 8; const int line_delta_bits = 8; #endif const int checkpoint_bits = 16; // -2 because the last one is used for hidden const int max_column = (1 << column_bits) - 2; const int column_mask = (1 << column_bits) - 1; static List<SourceFile> source_list; static List<CompilationUnit> compile_units; static Dictionary<string, int> source_files; static int source_count; static int current_source; static int current_compile_unit; static Checkpoint [] checkpoints; static int checkpoint_index; public readonly static Location Null = new Location (-1); public static bool InEmacs; static Location () { Reset (); } public static void Reset () { source_files = new Dictionary<string, int> (); source_list = new List<SourceFile> (); compile_units = new List<CompilationUnit> (); current_source = 0; current_compile_unit = 0; source_count = 0; checkpoint_index = 0; } // <summary> // This must be called before parsing/tokenizing any files. // </summary> static public void AddFile (Report r, string name) { string path = name;// Path.GetFullPath(name); int id; if (source_files.TryGetValue (path, out id)){ string other_name = source_list [id - 1].Name; if (name.Equals (other_name)) r.Warning (2002, 1, "Source file `{0}' specified multiple times", other_name); else r.Warning (2002, 1, "Source filenames `{0}' and `{1}' both refer to the same file: {2}", name, other_name, path); return; } source_files.Add (path, ++source_count); CompilationUnit unit = new CompilationUnit (name, path, source_count); source_list.Add (unit); compile_units.Add (unit); } public static string FirstFile { get { return compile_units.Count == 0 ? null : compile_units[0].Name; } } public static IList<CompilationUnit> SourceFiles { get { return compile_units; } } // <summary> // After adding all source files we want to compile with AddFile(), this method // must be called to `reserve' an appropriate number of bits in the token for the // source file. We reserve some extra space for files we encounter via #line // directives while parsing. // </summary> static public void Initialize () { checkpoints = new Checkpoint [source_list.Count * 2]; if (checkpoints.Length > 0) checkpoints [0] = new Checkpoint (0, 0, 0); } // <remarks> // This is used when we encounter a #line preprocessing directive. // </remarks> static public SourceFile LookupFile (CompilationUnit comp_unit, string name) { string path; if (!Path.IsPathRooted (name)) { string root = Path.GetDirectoryName (comp_unit.Path); path = Path.Combine (root, name); } else path = name; if (!source_files.ContainsKey (path)) { if (source_count >= (1 << checkpoint_bits)) return new SourceFile (name, path, 0, true); source_files.Add (path, ++source_count); SourceFile retval = new SourceFile (name, path, source_count, true); source_list.Add (retval); return retval; } int index = source_files [path]; return source_list [index - 1]; } static public void Push (CompilationUnit compile_unit, SourceFile file) { current_source = file != null ? file.Index : -1; current_compile_unit = compile_unit != null ? compile_unit.Index : -1; // File is always pushed before being changed. } // <remarks> // If we're compiling with debugging support, this is called between parsing // and code generation to register all the source files with the // symbol writer. // </remarks> static public void DefineSymbolDocuments (MonoSymbolWriter symwriter) { foreach (CompilationUnit unit in compile_units) unit.DefineSymbolInfo (symwriter); } public Location (int row) : this (row, 0) { } public Location (int row, int column) { if (row <= 0) token = 0; else { if (column > max_column) column = max_column; else if (column < 0) column = max_column + 1; long target = -1; long delta = 0; // FIXME: This value is certainly wrong but what was the intension int max = checkpoint_index < 10 ? checkpoint_index : 10; for (int i = 0; i < max; i++) { int offset = checkpoints [checkpoint_index - i].LineOffset; delta = row - offset; if (delta >= 0 && delta < (1 << line_delta_bits) && checkpoints [checkpoint_index - i].File == current_source) { target = checkpoint_index - i; break; } } if (target == -1) { AddCheckpoint (current_compile_unit, current_source, row); target = checkpoint_index; delta = row % (1 << line_delta_bits); } long l = column + (delta << column_bits) + (target << (line_delta_bits + column_bits)); #if FULL_AST token = l; #else token = l > 0xFFFFFFFF ? 0 : (int) l; #endif } } public static Location operator - (Location loc, int columns) { return new Location (loc.Row, loc.Column - columns); } static void AddCheckpoint (int compile_unit, int file, int row) { if (checkpoints.Length == ++checkpoint_index) { Array.Resize (ref checkpoints, checkpoint_index + 2); } checkpoints [checkpoint_index] = new Checkpoint (compile_unit, file, row); } string FormatLocation (string fileName) { if (column_bits == 0 || InEmacs) return fileName + "(" + Row.ToString () + "):"; return fileName + "(" + Row.ToString () + "," + Column.ToString () + (Column == max_column ? "+):" : "):"); } public override string ToString () { return FormatLocation (Name); } public string ToStringFullName () { return FormatLocation (NameFullPath); } /// <summary> /// Whether the Location is Null /// </summary> public bool IsNull { get { return token == 0; } } public string Name { get { int index = File; if (token == 0 || index == 0) return "Internal"; SourceFile file = source_list [index - 1]; return file.Name; } } public string NameFullPath { get { int index = File; if (token == 0 || index == 0) return "Internal"; return source_list [index - 1].Path; } } int CheckpointIndex { get { const int checkpoint_mask = (1 << checkpoint_bits) - 1; return ((int) (token >> (line_delta_bits + column_bits))) & checkpoint_mask; } } public int Row { get { if (token == 0) return 1; int offset = checkpoints[CheckpointIndex].LineOffset; const int line_delta_mask = (1 << column_bits) - 1; return offset + (((int)(token >> column_bits)) & line_delta_mask); } } public int Column { get { if (token == 0) return 1; int col = (int) (token & column_mask); return col > max_column ? 1 : col; } } public bool Hidden { get { return (int) (token & column_mask) == max_column + 1; } } public int CompilationUnitIndex { get { if (token == 0) return 0; if (checkpoints.Length <= CheckpointIndex) throw new Exception (String.Format ("Should not happen. Token is {0:X04}, checkpoints are {1}, index is {2}", token, checkpoints.Length, CheckpointIndex)); return checkpoints [CheckpointIndex].CompilationUnit; } } public int File { get { if (token == 0) return 0; if (checkpoints.Length <= CheckpointIndex) throw new Exception (String.Format ("Should not happen. Token is {0:X04}, checkpoints are {1}, index is {2}", token, checkpoints.Length, CheckpointIndex)); return checkpoints [CheckpointIndex].File; } } // The ISymbolDocumentWriter interface is used by the symbol writer to // describe a single source file - for each source file there's exactly // one corresponding ISymbolDocumentWriter instance. // // This class has an internal hash table mapping source document names // to such ISymbolDocumentWriter instances - so there's exactly one // instance per document. // // This property returns the ISymbolDocumentWriter instance which belongs // to the location's source file. // // If we don't have a symbol writer, this property is always null. public SourceFile SourceFile { get { int index = File; if (index == 0) return null; return (SourceFile) source_list [index - 1]; } } public CompilationUnit CompilationUnit { get { int index = CompilationUnitIndex; if (index == 0) return null; return (CompilationUnit) source_list [index - 1]; } } #region IEquatable<Location> Members public bool Equals (Location other) { return this.token == other.token; } #endregion } // // A bag of additional locations to support full ast tree // public class LocationsBag { public class MemberLocations { public readonly IList<Tuple<Modifiers, Location>> Modifiers; Location[] locations; public MemberLocations (IList<Tuple<Modifiers, Location>> mods, Location[] locs) { Modifiers = mods; locations = locs; } #region Properties public Location this [int index] { get { return locations [index]; } } public int Count { get { return locations.Length; } } #endregion public void AddLocations (params Location[] additional) { if (locations == null) { locations = additional; } else { int pos = locations.Length; Array.Resize (ref locations, pos + additional.Length); additional.CopyTo (locations, pos); } } } Dictionary<object, Location[]> simple_locs = new Dictionary<object, Location[]> (ReferenceEquality<object>.Default); Dictionary<MemberCore, MemberLocations> member_locs = new Dictionary<MemberCore, MemberLocations> (ReferenceEquality<MemberCore>.Default); [Conditional ("FULL_AST")] public void AddLocation (object element, params Location[] locations) { simple_locs.Add (element, locations); } [Conditional ("FULL_AST")] public void AddStatement (object element, params Location[] locations) { if (locations.Length == 0) throw new ArgumentException ("Statement is missing semicolon location"); simple_locs.Add (element, locations); } [Conditional ("FULL_AST")] public void AddMember (MemberCore member, IList<Tuple<Modifiers, Location>> modLocations, params Location[] locations) { member_locs.Add (member, new MemberLocations (modLocations, locations)); } [Conditional ("FULL_AST")] public void AppendTo (object existing, params Location[] locations) { Location[] locs; if (simple_locs.TryGetValue (existing, out locs)) { simple_locs [existing] = locs.Concat (locations).ToArray (); return; } } [Conditional ("FULL_AST")] public void AppendToMember (MemberCore existing, params Location[] locations) { MemberLocations member; if (member_locs.TryGetValue (existing, out member)) { member.AddLocations (locations); return; } } public Location[] GetLocations (object element) { Location[] found; simple_locs.TryGetValue (element, out found); return found; } public MemberLocations GetMemberLocation (MemberCore element) { MemberLocations found; member_locs.TryGetValue (element, out found); return found; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class NewLeaderEventDecoder { public const ushort BLOCK_LENGTH = 20; public const ushort TEMPLATE_ID = 6; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private NewLeaderEventDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public NewLeaderEventDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public NewLeaderEventDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int LeadershipTermIdId() { return 1; } public static int LeadershipTermIdSinceVersion() { return 0; } public static int LeadershipTermIdEncodingOffset() { return 0; } public static int LeadershipTermIdEncodingLength() { return 8; } public static string LeadershipTermIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long LeadershipTermIdNullValue() { return -9223372036854775808L; } public static long LeadershipTermIdMinValue() { return -9223372036854775807L; } public static long LeadershipTermIdMaxValue() { return 9223372036854775807L; } public long LeadershipTermId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int ClusterSessionIdId() { return 2; } public static int ClusterSessionIdSinceVersion() { return 0; } public static int ClusterSessionIdEncodingOffset() { return 8; } public static int ClusterSessionIdEncodingLength() { return 8; } public static string ClusterSessionIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long ClusterSessionIdNullValue() { return -9223372036854775808L; } public static long ClusterSessionIdMinValue() { return -9223372036854775807L; } public static long ClusterSessionIdMaxValue() { return 9223372036854775807L; } public long ClusterSessionId() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int LeaderMemberIdId() { return 3; } public static int LeaderMemberIdSinceVersion() { return 0; } public static int LeaderMemberIdEncodingOffset() { return 16; } public static int LeaderMemberIdEncodingLength() { return 4; } public static string LeaderMemberIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int LeaderMemberIdNullValue() { return -2147483648; } public static int LeaderMemberIdMinValue() { return -2147483647; } public static int LeaderMemberIdMaxValue() { return 2147483647; } public int LeaderMemberId() { return _buffer.GetInt(_offset + 16, ByteOrder.LittleEndian); } public static int IngressEndpointsId() { return 4; } public static int IngressEndpointsSinceVersion() { return 0; } public static string IngressEndpointsCharacterEncoding() { return "US-ASCII"; } public static string IngressEndpointsMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int IngressEndpointsHeaderLength() { return 4; } public int IngressEndpointsLength() { int limit = _parentMessage.Limit(); return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); } public int GetIngressEndpoints(IMutableDirectBuffer dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public int GetIngressEndpoints(byte[] dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public string IngressEndpoints() { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); _parentMessage.Limit(limit + headerLength + dataLength); byte[] tmp = new byte[dataLength]; _buffer.GetBytes(limit + headerLength, tmp, 0, dataLength); return Encoding.ASCII.GetString(tmp); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[NewLeaderEvent](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='leadershipTermId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LeadershipTermId="); builder.Append(LeadershipTermId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='clusterSessionId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ClusterSessionId="); builder.Append(ClusterSessionId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='leaderMemberId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LeaderMemberId="); builder.Append(LeaderMemberId()); builder.Append('|'); //Token{signal=BEGIN_VAR_DATA, name='ingressEndpoints', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=20, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("IngressEndpoints="); builder.Append(IngressEndpoints()); Limit(originalLimit); return builder; } } }
#region Using Statments using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Input.Touch; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Content; using HackPrototype; #endregion namespace GameStateManagement { class IntermediateScreen : SingleControlScreen { #region Fields ContentManager content; Texture2D levelWinTexture; Texture2D backgroundTexture; Texture2D taptoContinueTexture; string levelWinTexturePath; string taptoContinueTexturePath; string soundPath; Vector2 tapToContinueLocation; CursorText levelwinText; Vector2 levelWinTextDrawLocation; Vector2 originalLevelWinTextDrawLocation; int wave; UInt64 score; SoundEffect splashSound; SoundEffect raiseSound; bool startedDraw = false; float DelayToRaiseText = 3.0f; float RaiseTextTimeMax = 0.75f; float RaiseTextTime = 0.75f; Vector2 levelWinTextRaiseLocation; #endregion public IntermediateScreen(string titleTexturePath, string tapToContinueTexturePath, string splashSoundPath, int currentWave, UInt64 currentscore) { // menus generally only need Tap for menu selection EnabledGestures = GestureType.Tap; levelWinTexturePath = titleTexturePath; taptoContinueTexturePath = tapToContinueTexturePath; soundPath = splashSoundPath; wave = currentWave; score = currentscore; } public override void LoadContent() { if (content == null) content = new ContentManager(ScreenManager.Game.Services, "Content"); backgroundTexture = content.Load<Texture2D>("sprites\\Background"); levelWinTexture = content.Load<Texture2D>(levelWinTexturePath); taptoContinueTexture = content.Load<Texture2D>(taptoContinueTexturePath); levelwinText = new CursorText(levelWinTexture, 1.5f, 1.0f, content); levelWinTextDrawLocation = new Vector2(ScreenManager.GraphicsDevice.Viewport.Width / 2 - levelWinTexture.Width / 2, ScreenManager.GraphicsDevice.Viewport.Height / 2 - levelWinTexture.Height / 2); originalLevelWinTextDrawLocation = levelWinTextDrawLocation; tapToContinueLocation = new Vector2(ScreenManager.GraphicsDevice.Viewport.Width / 2 - taptoContinueTexture.Width / 2, ScreenManager.GraphicsDevice.Viewport.Height - 100); levelWinTextRaiseLocation = new Vector2(levelWinTextDrawLocation.X, 60); splashSound = content.Load<SoundEffect>(soundPath); raiseSound = content.Load<SoundEffect>("Sounds\\Thump"); AddAccountingControl(); } /// <summary> /// Unloads graphics content for this screen. /// </summary> public override void UnloadContent() { content.Unload(); } #region Update and Draw /// <summary> /// Updates the tutorial screen. /// </summary> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); if (DelayToRaiseText > 0) { DelayToRaiseText -= (float)gameTime.ElapsedGameTime.TotalSeconds; } else if (RaiseTextTime > 0) { RaiseTextTime -= (float)gameTime.ElapsedGameTime.TotalSeconds; if (RaiseTextTime <= 0) { RaiseTextTime = 0; levelWinTextDrawLocation = levelWinTextRaiseLocation; //AddAccountingControl(); if(RootControl != null) RootControl.Visible = true; raiseSound.Play(); } else { levelWinTextDrawLocation = new Vector2(MathHelper.Lerp(levelWinTextRaiseLocation.X, originalLevelWinTextDrawLocation.X, RaiseTextTime / RaiseTextTimeMax), MathHelper.Lerp(levelWinTextRaiseLocation.Y, originalLevelWinTextDrawLocation.Y, RaiseTextTime / RaiseTextTimeMax)); } } levelwinText.Update(gameTime); } private void AddAccountingControl() { WaveAccountingTable table = ((Game1)(ScreenManager.Game)).GetAccounting(); RootControl = new AccountingPanel(content, table, wave, score); RootControl.Visible = false; } public override void HandleInput(InputState input) { // look for any taps that occurred and select any entries that were tapped foreach (GestureSample gesture in input.Gestures) { if (gesture.GestureType == GestureType.Tap) { //well, we're going to the game screen! ExitSelf(); } } base.HandleInput(input); } public override void OnBackButton() { ExitSelf(); } protected virtual void ExitSelf() { ExitScreen(); } /// <summary> /// Draws the game over screen. /// </summary> public override void Draw(GameTime gameTime) { SpriteBatch spriteBatch = ScreenManager.SpriteBatch; Viewport viewport = ScreenManager.GraphicsDevice.Viewport; Rectangle fullscreen = new Rectangle(0, 0, viewport.Width, viewport.Height); if (!startedDraw) { //this is our first draw, play the sound splashSound.Play(); startedDraw = true; } spriteBatch.Begin(); spriteBatch.Draw(backgroundTexture, fullscreen, new Color(TransitionAlpha, TransitionAlpha, TransitionAlpha)); levelwinText.DrawSelf(spriteBatch, levelWinTextDrawLocation, new Color(TransitionAlpha, TransitionAlpha, TransitionAlpha)); if (RootControl.Visible == true) { spriteBatch.Draw(taptoContinueTexture, tapToContinueLocation, new Color(TransitionAlpha, TransitionAlpha, TransitionAlpha)); } spriteBatch.End(); base.Draw(gameTime); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Extensions.Logging; using Orleans.CodeGenerator.Analysis; using Orleans.CodeGenerator.Compatibility; using Orleans.CodeGenerator.Generators; using Orleans.CodeGenerator.Model; using Orleans.CodeGenerator.Utilities; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Orleans.CodeGenerator { public class CodeGenerator { public const string ToolName = "OrleansCodeGen"; public static readonly string Version = typeof(CodeGenerator).Assembly.GetName().Version.ToString(); private readonly Compilation compilation; private readonly ILogger log; private readonly WellKnownTypes wellKnownTypes; private readonly SemanticModel semanticModelForAccessibility; private readonly CompilationAnalyzer compilationAnalyzer; private readonly SerializerTypeAnalyzer serializerTypeAnalyzer; private readonly SerializerGenerator serializerGenerator; private readonly GrainMethodInvokerGenerator grainMethodInvokerGenerator; private readonly GrainReferenceGenerator grainReferenceGenerator; private readonly CodeGeneratorOptions options; public CodeGenerator(Compilation compilation, CodeGeneratorOptions options, ILogger log) { this.compilation = compilation; this.options = options; this.log = log; this.wellKnownTypes = new WellKnownTypes(compilation); this.compilationAnalyzer = new CompilationAnalyzer(log, this.wellKnownTypes, compilation); var firstSyntaxTree = compilation.SyntaxTrees.FirstOrDefault() ?? throw new InvalidOperationException("Compilation has no syntax trees."); this.semanticModelForAccessibility = compilation.GetSemanticModel(firstSyntaxTree); this.serializerTypeAnalyzer = SerializerTypeAnalyzer.Create(this.wellKnownTypes); this.serializerGenerator = new SerializerGenerator(this.options, this.wellKnownTypes); this.grainMethodInvokerGenerator = new GrainMethodInvokerGenerator(this.options, this.wellKnownTypes); this.grainReferenceGenerator = new GrainReferenceGenerator(this.options, this.wellKnownTypes); } public CompilationUnitSyntax GenerateCode(CancellationToken cancellationToken) { // Create a model of the code to generate from the collection of types. var model = this.AnalyzeCompilation(); // Perform some validation against the generated model. this.ValidateModel(model); // Finally, generate code for the model. return this.GenerateSyntax(model); } private AggregatedModel AnalyzeCompilation() { // Inspect the target assembly to discover known assemblies and known types. if (log.IsEnabled(LogLevel.Debug)) log.LogDebug($"Main assembly {this.compilation.Assembly}"); this.compilationAnalyzer.Analyze(); // Create a list of all distinct types from all known assemblies. var types = this.compilationAnalyzer .KnownAssemblies.SelectMany(a => a.GetDeclaredTypes()) .Concat(this.compilationAnalyzer.KnownTypes) .Distinct() .ToList(); var model = new AggregatedModel(); // Inspect all types foreach (var type in types) this.compilationAnalyzer.InspectType(type); // Get the types which need processing. var (grainClasses, grainInterfaces, serializationTypes) = this.compilationAnalyzer.GetTypesToProcess(); // Process each of the types into the model. foreach (var grainInterface in grainInterfaces) this.ProcessGrainInterface(model, grainInterface); foreach (var grainClass in grainClasses) { this.ProcessGrainClass(model, grainClass); this.ProcessSerializableType(model, grainClass); } foreach (var type in serializationTypes) this.ProcessSerializableType(model, type); this.AddAssemblyMetadata(model); return model; } private void AddAssemblyMetadata(AggregatedModel model) { var assembliesToScan = new List<IAssemblySymbol>(); foreach (var asm in this.compilationAnalyzer.ReferencedAssemblies) { // Known assemblies are already handled. if (this.compilationAnalyzer.KnownAssemblies.Contains(asm)) continue; if (this.compilationAnalyzer.AssembliesExcludedFromCodeGeneration.Contains(asm) || this.compilationAnalyzer.AssembliesExcludedFromMetadataGeneration.Contains(asm)) { this.log.LogDebug($"Skipping adding known types for assembly {asm.Identity.Name} since a referenced assembly already includes its types."); continue; } assembliesToScan.Add(asm); } foreach (var asm in assembliesToScan) { this.log.LogDebug($"Generating metadata for referenced assembly {asm.Identity.Name}."); foreach (var type in asm.GetDeclaredTypes()) { if (this.ValidForKnownTypes(type)) { AddKnownType(model, type); } } } } private void ValidateModel(AggregatedModel model) { // Check that all types which the developer marked as requiring code generation have had code generation. foreach (var required in this.compilationAnalyzer.CodeGenerationRequiredTypes) { if (!model.Serializers.SerializerTypes.Any(t => SymbolEqualityComparer.Default.Equals(t.Target, required))) { throw new CodeGenerationException( $"Found {this.wellKnownTypes.ConsiderForCodeGenerationAttribute} with ThrowOnFailure set for type {required}, but a serializer" + " could not be generated. Ensure that the type is accessible."); } } } private CompilationUnitSyntax GenerateSyntax(AggregatedModel model) { var namespaceGroupings = new Dictionary<INamespaceSymbol, List<MemberDeclarationSyntax>>(); // Pass the relevant elements of the model to each of the code generators. foreach (var grainInterface in model.GrainInterfaces) { var nsMembers = GetNamespace(namespaceGroupings, grainInterface.Type.ContainingNamespace); nsMembers.Add(grainMethodInvokerGenerator.GenerateClass(grainInterface)); nsMembers.Add(grainReferenceGenerator.GenerateClass(grainInterface)); } var serializersToGenerate = model.Serializers.SerializerTypes .Where(s => s.SerializerTypeSyntax == null) .Distinct(SerializerTypeDescription.TargetComparer); foreach (var serializerType in serializersToGenerate) { var nsMembers = GetNamespace(namespaceGroupings, serializerType.Target.ContainingNamespace); TypeDeclarationSyntax generated; (generated, serializerType.SerializerTypeSyntax) = this.serializerGenerator.GenerateClass(this.semanticModelForAccessibility, serializerType, this.log); nsMembers.Add(generated); } var compilationMembers = new List<MemberDeclarationSyntax>(); // Group the generated code by namespace since serialized types, such as the generated GrainReference classes must have a stable namespace. foreach (var group in namespaceGroupings) { var ns = group.Key; var members = group.Value; if (ns.IsGlobalNamespace) { compilationMembers.AddRange(members); } else { compilationMembers.Add(NamespaceDeclaration(ParseName(ns.ToDisplayString())).AddMembers(members.ToArray())); } } // Add and generate feature populators to tie everything together. var (attributes, featurePopulators) = FeaturePopulatorGenerator.GenerateSyntax(this.wellKnownTypes, model, this.compilation); compilationMembers.AddRange(featurePopulators); // Add some attributes detailing which assemblies this generated code targets. attributes.Add(AttributeList( AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), SeparatedList(GetCodeGenerationTargetAttribute().ToArray()))); return CompilationUnit() .AddUsings(UsingDirective(ParseName("global::Orleans"))) .WithAttributeLists(List(attributes)) .WithMembers(List(compilationMembers)); List<MemberDeclarationSyntax> GetNamespace(Dictionary<INamespaceSymbol, List<MemberDeclarationSyntax>> namespaces, INamespaceSymbol ns) { if (namespaces.TryGetValue(ns, out var result)) return result; return namespaces[ns] = new List<MemberDeclarationSyntax>(); } IEnumerable<AttributeSyntax> GetCodeGenerationTargetAttribute() { yield return GenerateAttribute(this.compilation.Assembly); foreach (var assembly in this.compilationAnalyzer.ReferencedAssemblies) { if (this.compilationAnalyzer.AssembliesExcludedFromCodeGeneration.Contains(assembly) || this.compilationAnalyzer.AssembliesExcludedFromMetadataGeneration.Contains(assembly)) { continue; } yield return GenerateAttribute(assembly); } AttributeSyntax GenerateAttribute(IAssemblySymbol assembly) { var assemblyName = assembly.Identity.GetDisplayName(fullKey: true); this.log.LogTrace($"Adding [assembly: OrleansCodeGenerationTarget(\"{assemblyName}\")]"); var nameSyntax = this.wellKnownTypes.OrleansCodeGenerationTargetAttribute.ToNameSyntax(); return Attribute(nameSyntax) .AddArgumentListArguments(AttributeArgument(assemblyName.ToLiteralExpression())); } } } private void ProcessGrainInterface(AggregatedModel model, INamedTypeSymbol type) { var accessible = this.semanticModelForAccessibility.IsAccessible(0, type); if (this.log.IsEnabled(LogLevel.Debug)) { this.log.LogDebug($"Found grain interface {type.ToDisplayString()}{(accessible ? string.Empty : ", but it is inaccessible")}"); } if (accessible) { var genericMethod = type.GetInstanceMembers<IMethodSymbol>().FirstOrDefault(m => m.IsGenericMethod); if (genericMethod != null && this.wellKnownTypes.GenericMethodInvoker is WellKnownTypes.None) { if (this.log.IsEnabled(LogLevel.Warning)) { var message = $"Grain interface {type} has a generic method, {genericMethod}." + " Support for generic methods requires the project to reference Microsoft.Orleans.Core, but this project does not reference it."; this.log.LogError(message); throw new CodeGenerationException(message); } } var methods = GetGrainMethodDescriptions(type); model.GrainInterfaces.Add(new GrainInterfaceDescription( type, this.wellKnownTypes.GetTypeId(type), this.wellKnownTypes.GetVersion(type), methods)); } // Returns a list of all methods in all interfaces on the provided type. IEnumerable<GrainMethodDescription> GetGrainMethodDescriptions(INamedTypeSymbol initialType) { IEnumerable<INamedTypeSymbol> GetAllInterfaces(INamedTypeSymbol s) { if (s.TypeKind == TypeKind.Interface) yield return s; foreach (var i in s.AllInterfaces) yield return i; } foreach (var iface in GetAllInterfaces(initialType)) { foreach (var method in iface.GetDeclaredInstanceMembers<IMethodSymbol>()) { yield return new GrainMethodDescription(this.wellKnownTypes.GetMethodId(method), method); } } } } private void ProcessGrainClass(AggregatedModel model, INamedTypeSymbol type) { var accessible = this.semanticModelForAccessibility.IsAccessible(0, type); if (this.log.IsEnabled(LogLevel.Debug)) { this.log.LogDebug($"Found grain class {type.ToDisplayString()}{(accessible ? string.Empty : ", but it is inaccessible")}"); } if (accessible) { model.GrainClasses.Add(new GrainClassDescription(type, this.wellKnownTypes.GetTypeId(type))); } } private void ProcessSerializableType(AggregatedModel model, INamedTypeSymbol type) { if (!ValidForKnownTypes(type)) { if (this.log.IsEnabled(LogLevel.Trace)) this.log.LogTrace($"{nameof(ProcessSerializableType)} skipping abstract type {type}"); return; } AddKnownType(model, type); var serializerModel = model.Serializers; if (type.IsAbstract) { if (this.log.IsEnabled(LogLevel.Trace)) this.log.LogTrace($"{nameof(ProcessSerializableType)} skipping abstract type {type}"); return; } // Ensure that the type is accessible from generated code. var accessible = this.semanticModelForAccessibility.IsAccessible(0, type); if (!accessible) { if (this.log.IsEnabled(LogLevel.Trace)) this.log.LogTrace($"{nameof(ProcessSerializableType)} skipping inaccessible type {type}"); return; } if (type.HasBaseType(this.wellKnownTypes.Exception)) { if (this.log.IsEnabled(LogLevel.Trace)) this.log.LogTrace($"{nameof(ProcessSerializableType)} skipping Exception type {type}"); return; } if (type.HasBaseType(this.wellKnownTypes.Delegate)) { if (this.log.IsEnabled(LogLevel.Trace)) this.log.LogTrace($"{nameof(ProcessSerializableType)} skipping Delegate type {type}"); return; } if (type.AllInterfaces.Contains(this.wellKnownTypes.IAddressable)) { if (this.log.IsEnabled(LogLevel.Trace)) this.log.LogTrace($"{nameof(ProcessSerializableType)} skipping IAddressable type {type}"); return; } // Account for types that serialize themselves and/or are serializers for other types. var selfSerializing = false; if (this.serializerTypeAnalyzer.IsSerializer(type, out var serializerTargets)) { var typeSyntax = type.ToTypeSyntax(); foreach (var target in serializerTargets) { if (this.log.IsEnabled(LogLevel.Trace)) { this.log.LogTrace($"{nameof(ProcessSerializableType)} type {type} is a serializer for {target}"); } if (SymbolEqualityComparer.Default.Equals(target, type)) { selfSerializing = true; typeSyntax = type.WithoutTypeParameters().ToTypeSyntax(); } serializerModel.SerializerTypes.Add(new SerializerTypeDescription { Target = target, SerializerTypeSyntax = typeSyntax, OverrideExistingSerializer = true }); } } if (selfSerializing) { if (this.log.IsEnabled(LogLevel.Trace)) this.log.LogTrace($"{nameof(ProcessSerializableType)} skipping serializer generation for self-serializing type {type}"); return; } if (type.HasAttribute(this.wellKnownTypes.GeneratedCodeAttribute)) { if (this.log.IsEnabled(LogLevel.Trace)) { this.log.LogTrace($"{nameof(ProcessSerializableType)} type {type} is a generated type and no serializer will be generated for it"); } return; } if (type.IsStatic) { if (this.log.IsEnabled(LogLevel.Trace)) { this.log.LogTrace($"{nameof(ProcessSerializableType)} type {type} is a static type and no serializer will be generated for it"); } return; } if (type.TypeKind == TypeKind.Enum) { if (this.log.IsEnabled(LogLevel.Trace)) { this.log.LogTrace($"{nameof(ProcessSerializableType)} type {type} is an enum type and no serializer will be generated for it"); } return; } if (type.TypeParameters.Any(p => p.ConstraintTypes.Any(c => SymbolEqualityComparer.Default.Equals(c, this.wellKnownTypes.Delegate)))) { if (this.log.IsEnabled(LogLevel.Trace)) this.log.LogTrace($"{nameof(ProcessSerializableType)} skipping type with Delegate parameter constraint, {type}"); return; } var isSerializable = this.compilationAnalyzer.IsSerializable(type); if (isSerializable && this.compilationAnalyzer.IsFromKnownAssembly(type)) { // Skip types which have fields whose types are inaccessible from generated code. foreach (var field in type.GetInstanceMembers<IFieldSymbol>()) { // Ignore fields which won't be serialized anyway. if (!this.serializerGenerator.ShouldSerializeField(field)) { if (this.log.IsEnabled(LogLevel.Trace)) { this.log.LogTrace($"{nameof(ProcessSerializableType)} skipping non-serialized field {field} in type {type}"); } continue; } // Check field type accessibility. var fieldAccessible = this.semanticModelForAccessibility.IsAccessible(0, field.Type); if (!fieldAccessible) { if (this.log.IsEnabled(LogLevel.Trace)) { this.log.LogTrace($"{nameof(ProcessSerializableType)} skipping type {type} with inaccessible field type {field.Type} (field: {field})"); } return; } } // Add the type that needs generation. // The serializer generator will fill in the missing SerializerTypeSyntax field with the // generated type. if (this.log.IsEnabled(LogLevel.Trace)) { this.log.LogTrace($"{nameof(ProcessSerializableType)} will generate a serializer for type {type}"); } serializerModel.SerializerTypes.Add(new SerializerTypeDescription { Target = type }); } else if (this.log.IsEnabled(LogLevel.Trace)) { this.log.LogTrace($"{nameof(ProcessSerializableType)} will not generate a serializer for type {type}"); } } private static void AddKnownType(AggregatedModel model, INamedTypeSymbol type) { // Many types which will never have a serializer generated are still added to known types so that they can be used to identify the type // in a serialized payload. For example, when serializing List<SomeAbstractType>, SomeAbstractType must be known. The same applies to // interfaces (which are encoded as abstract). var serializerModel = model.Serializers; var strippedType = type.WithoutTypeParameters(); serializerModel.KnownTypes.Add(new KnownTypeDescription(strippedType)); } private bool ValidForKnownTypes(INamedTypeSymbol type) { // Skip implicitly declared types like anonymous classes and closures. if (type.IsImplicitlyDeclared) { return false; } if (!type.CanBeReferencedByName) { return false; } if (type.SpecialType != SpecialType.None) { return false; } switch (type.TypeKind) { case TypeKind.Unknown: case TypeKind.Array: case TypeKind.Delegate: case TypeKind.Dynamic: case TypeKind.Error: case TypeKind.Module: case TypeKind.Pointer: case TypeKind.TypeParameter: case TypeKind.Submission: return false; } if (type.IsStatic) { return false; } if (type.HasUnsupportedMetadata) { return false; } if (this.log.IsEnabled(LogLevel.Trace)) this.log.LogTrace($"{nameof(ValidForKnownTypes)} adding type {type}"); return true; } } }
using UnityEngine; using System.Collections.Generic; using Pathfinding; /** Handles path calls for a single unit. * \ingroup relevant * This is a component which is meant to be attached to a single unit (AI, Robot, Player, whatever) to handle it's pathfinding calls. * It also handles post-processing of paths using modifiers. * \see \ref calling-pathfinding */ [AddComponentMenu("Pathfinding/Seeker")] [HelpURL("http://arongranberg.com/astar/docs/class_seeker.php")] public class Seeker : MonoBehaviour, ISerializationCallbackReceiver { //====== SETTINGS ====== /** Enables drawing of the last calculated path using Gizmos. * The path will show up in green. * * \see OnDrawGizmos */ private Animator mAnim; public void FixedUpdate() { //anim.SetFloat("Vspeed", Input.GetAxis("Vertical"));// Not sure if its placed correctly, check with init programmer regarding the structure of animation codes } public bool drawGizmos = true; /** Enables drawing of the non-postprocessed path using Gizmos. * The path will show up in orange. * * Requires that #drawGizmos is true. * * This will show the path before any post processing such as smoothing is applied. * * \see drawGizmos * \see OnDrawGizmos */ public bool detailedGizmos; /** Path modifier which tweaks the start and end points of a path */ public StartEndModifier startEndModifier = new StartEndModifier(); /** The tags which the Seeker can traverse. * * \note This field is a bitmask. * \see https://en.wikipedia.org/wiki/Mask_(computing) */ [HideInInspector] public int traversableTags = -1; /** Required for serialization backwards compatibility. * \since 3.6.8 */ [UnityEngine.Serialization.FormerlySerializedAs("traversableTags")] [SerializeField] [HideInInspector] protected TagMask traversableTagsCompatibility = new TagMask(-1, -1); /** Penalties for each tag. * Tag 0 which is the default tag, will have added a penalty of tagPenalties[0]. * These should only be positive values since the A* algorithm cannot handle negative penalties. * * \note This array should always have a length of 32 otherwise the system will ignore it. * * \see Pathfinding.Path.tagPenalties */ [HideInInspector] public int[] tagPenalties = new int[32]; //====== SETTINGS ====== /** Callback for when a path is completed. * Movement scripts should register to this delegate.\n * A temporary callback can also be set when calling StartPath, but that delegate will only be called for that path */ public OnPathDelegate pathCallback; /** Called before pathfinding is started */ public OnPathDelegate preProcessPath; /** Called after a path has been calculated, right before modifiers are executed. * Can be anything which only modifies the positions (Vector3[]). */ public OnPathDelegate postProcessPath; /** Used for drawing gizmos */ [System.NonSerialized] List<Vector3> lastCompletedVectorPath; /** Used for drawing gizmos */ [System.NonSerialized] List<GraphNode> lastCompletedNodePath; /** The current path */ [System.NonSerialized] protected Path path; /** Previous path. Used to draw gizmos */ [System.NonSerialized] private Path prevPath; /** Cached delegate to avoid allocating one every time a path is started */ private readonly OnPathDelegate onPathDelegate; /** Cached delegate to avoid allocating one every time a path is started */ private readonly OnPathDelegate onPartialPathDelegate; /** Temporary callback only called for the current path. This value is set by the StartPath functions */ private OnPathDelegate tmpPathCallback; /** The path ID of the last path queried */ protected uint lastPathID; /** Internal list of all modifiers */ readonly List<IPathModifier> modifiers = new List<IPathModifier>(); public enum ModifierPass { PreProcess, // An obsolete item occupied index 1 previously PostProcess = 2, } public Seeker () { onPathDelegate = OnPathComplete; onPartialPathDelegate = OnPartialPathComplete; } /** Initializes a few variables */ void Awake () { mAnim = GetComponent<Animator>(); startEndModifier.Awake(this); } /** Path that is currently being calculated or was last calculated. * You should rarely have to use this. Instead get the path when the path callback is called. * * \see pathCallback */ public Path GetCurrentPath () { return path; } /** Cleans up some variables. * Releases any eventually claimed paths. * Calls OnDestroy on the #startEndModifier. * * \see ReleaseClaimedPath * \see startEndModifier */ public void OnDestroy () { ReleaseClaimedPath(); startEndModifier.OnDestroy(this); } /** Releases the path used for gizmos (if any). * The seeker keeps the latest path claimed so it can draw gizmos. * In some cases this might not be desireable and you want it released. * In that case, you can call this method to release it (not that path gizmos will then not be drawn). * * If you didn't understand anything from the description above, you probably don't need to use this method. * * \see \ref pooling */ public void ReleaseClaimedPath () { if (prevPath != null) { prevPath.Release(this, true); prevPath = null; } } /** Called by modifiers to register themselves */ public void RegisterModifier (IPathModifier mod) { modifiers.Add(mod); // Sort the modifiers based on their specified order modifiers.Sort((a, b) => a.Order.CompareTo(b.Order)); } /** Called by modifiers when they are disabled or destroyed */ public void DeregisterModifier (IPathModifier mod) { modifiers.Remove(mod); } /** Post Processes the path. * This will run any modifiers attached to this GameObject on the path. * This is identical to calling RunModifiers(ModifierPass.PostProcess, path) * \see RunModifiers * \since Added in 3.2 */ public void PostProcess (Path p) { RunModifiers(ModifierPass.PostProcess, p); } /** Runs modifiers on path \a p */ public void RunModifiers (ModifierPass pass, Path p) { // Call delegates if they exist if (pass == ModifierPass.PreProcess && preProcessPath != null) { preProcessPath(p); } else if (pass == ModifierPass.PostProcess && postProcessPath != null) { postProcessPath(p); } // Loop through all modifiers and apply post processing for (int i = 0; i < modifiers.Count; i++) { // Cast to MonoModifier, i.e modifiers attached as scripts to the game object var mMod = modifiers[i] as MonoModifier; // Ignore modifiers which are not enabled if (mMod != null && !mMod.enabled) continue; if (pass == ModifierPass.PreProcess) { modifiers[i].PreProcess(p); } else if (pass == ModifierPass.PostProcess) { modifiers[i].Apply(p); } } } /** Is the current path done calculating. * Returns true if the current #path has been returned or if the #path is null. * * \note Do not confuse this with Pathfinding.Path.IsDone. They usually return the same value, but not always * since the path might be completely calculated, but it has not yet been processed by the Seeker. * * \since Added in 3.0.8 * \version Behaviour changed in 3.2 */ public bool IsDone () { return path == null || path.GetState() >= PathState.Returned; } /** Called when a path has completed. * This should have been implemented as optional parameter values, but that didn't seem to work very well with delegates (the values weren't the default ones) * \see OnPathComplete(Path,bool,bool) */ void OnPathComplete (Path p) { OnPathComplete(p, true, true); } /** Called when a path has completed. * Will post process it and return it by calling #tmpPathCallback and #pathCallback */ void OnPathComplete (Path p, bool runModifiers, bool sendCallbacks) { if (p != null && p != path && sendCallbacks) { return; } if (this == null || p == null || p != path) return; if (!path.error && runModifiers) { // This will send the path for post processing to modifiers attached to this Seeker RunModifiers(ModifierPass.PostProcess, path); } if (sendCallbacks) { p.Claim(this); lastCompletedNodePath = p.path; lastCompletedVectorPath = p.vectorPath; // This will send the path to the callback (if any) specified when calling StartPath if (tmpPathCallback != null) { tmpPathCallback(p); } // This will send the path to any script which has registered to the callback if (pathCallback != null) { pathCallback(p); } // Recycle the previous path to reduce the load on the GC if (prevPath != null) { prevPath.Release(this, true); } prevPath = p; // If not drawing gizmos, then storing prevPath is quite unecessary // So clear it and set prevPath to null if (!drawGizmos) ReleaseClaimedPath(); } } /** Called for each path in a MultiTargetPath. * Only post processes the path, does not return it. * \astarpro */ void OnPartialPathComplete (Path p) { OnPathComplete(p, true, false); } /** Called once for a MultiTargetPath. Only returns the path, does not post process. * \astarpro */ void OnMultiPathComplete (Path p) { OnPathComplete(p, false, true); } /** Returns a new path instance. * The path will be taken from the path pool if path recycling is turned on.\n * This path can be sent to #StartPath(Path,OnPathDelegate,int) with no change, but if no change is required #StartPath(Vector3,Vector3,OnPathDelegate) does just that. * \code var seeker = GetComponent<Seeker>(); * Path p = seeker.GetNewPath (transform.position, transform.position+transform.forward*100); * // Disable heuristics on just this path for example * p.heuristic = Heuristic.None; * seeker.StartPath (p, OnPathComplete); * \endcode */ public ABPath GetNewPath (Vector3 start, Vector3 end) { // Construct a path with start and end points return ABPath.Construct(start, end, null); } /** Call this function to start calculating a path. * \param start The start point of the path * \param end The end point of the path */ public Path StartPath (Vector3 start, Vector3 end) { return StartPath(start, end, null, -1); } /** Call this function to start calculating a path. * * \param start The start point of the path * \param end The end point of the path * \param callback The function to call when the path has been calculated * * \a callback will be called when the path has completed. * \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) */ public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback) { return StartPath(start, end, callback, -1); } /** Call this function to start calculating a path. * * \param start The start point of the path * \param end The end point of the path * \param callback The function to call when the path has been calculated * \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask. * * \a callback will be called when the path has completed. * \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) */ public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback, int graphMask) { return StartPath(GetNewPath(start, end), callback, graphMask); } /** Call this function to start calculating a path. * * \param p The path to start calculating * \param callback The function to call when the path has been calculated * \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask. * * \a callback will be called when the path has completed. * \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) */ public Path StartPath (Path p, OnPathDelegate callback = null, int graphMask = -1) { p.enabledTags = traversableTags; p.tagPenalties = tagPenalties; p.callback += onPathDelegate; p.nnConstraint.graphMask = graphMask; StartPathInternal(p, callback); return path; } /** Internal method to start a path and mark it as the currently active path */ void StartPathInternal (Path p, OnPathDelegate callback) { // Cancel a previously requested path is it has not been processed yet and also make sure that it has not been recycled and used somewhere else if (path != null && path.GetState() <= PathState.Processing && lastPathID == path.pathID) { path.Error(); path.LogError("Canceled path because a new one was requested.\n"+ "This happens when a new path is requested from the seeker when one was already being calculated.\n" + "For example if a unit got a new order, you might request a new path directly instead of waiting for the now" + " invalid path to be calculated. Which is probably what you want.\n" + "If you are getting this a lot, you might want to consider how you are scheduling path requests."); // No callback will be sent for the canceled path } // Set p as the active path path = p; tmpPathCallback = callback; // Save the path id so we can make sure that if we cancel a path (see above) it should not have been recycled yet. lastPathID = path.pathID; // Pre process the path RunModifiers(ModifierPass.PreProcess, path); // Send the request to the pathfinder AstarPath.StartPath(path); } /** Starts a Multi Target Path from one start point to multiple end points. * A Multi Target Path will search for all the end points in one search and will return all paths if \a pathsForAll is true, or only the shortest one if \a pathsForAll is false.\n * * \param start The start point of the path * \param endPoints The end points of the path * \param pathsForAll Indicates whether or not a path to all end points should be searched for or only to the closest one * \param callback The function to call when the path has been calculated * \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask. * * \a callback and #pathCallback will be called when the path has completed. \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) * \astarpro * \see Pathfinding.MultiTargetPath * \see \ref MultiTargetPathExample.cs "Example of how to use multi-target-paths" */ public MultiTargetPath StartMultiTargetPath (Vector3 start, Vector3[] endPoints, bool pathsForAll, OnPathDelegate callback = null, int graphMask = -1) { MultiTargetPath p = MultiTargetPath.Construct(start, endPoints, null, null); p.pathsForAll = pathsForAll; return StartMultiTargetPath(p, callback, graphMask); } /** Starts a Multi Target Path from multiple start points to a single target point. * A Multi Target Path will search from all start points to the target point in one search and will return all paths if \a pathsForAll is true, or only the shortest one if \a pathsForAll is false.\n * * \param startPoints The start points of the path * \param end The end point of the path * \param pathsForAll Indicates whether or not a path from all start points should be searched for or only to the closest one * \param callback The function to call when the path has been calculated * \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask. * * \a callback and #pathCallback will be called when the path has completed. \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) * \astarpro * \see Pathfinding.MultiTargetPath * \see \ref MultiTargetPathExample.cs "Example of how to use multi-target-paths" */ public MultiTargetPath StartMultiTargetPath (Vector3[] startPoints, Vector3 end, bool pathsForAll, OnPathDelegate callback = null, int graphMask = -1) { MultiTargetPath p = MultiTargetPath.Construct(startPoints, end, null, null); p.pathsForAll = pathsForAll; return StartMultiTargetPath(p, callback, graphMask); } /** Starts a Multi Target Path. * Takes a MultiTargetPath and wires everything up for it to send callbacks to the seeker for post-processing.\n * * \param p The path to start calculating * \param callback The function to call when the path has been calculated * \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask. * * \a callback and #pathCallback will be called when the path has completed. \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) * \astarpro * \see Pathfinding.MultiTargetPath * \see \ref MultiTargetPathExample.cs "Example of how to use multi-target-paths" */ public MultiTargetPath StartMultiTargetPath (MultiTargetPath p, OnPathDelegate callback = null, int graphMask = -1) { // TODO: Allocation, cache var callbacks = new OnPathDelegate[p.targetPoints.Length]; for (int i = 0; i < callbacks.Length; i++) { callbacks[i] = onPartialPathDelegate; } // TODO: This method does not set the enabledTags or tagPenalties // as the StartPath method does... should this be changed? // Hard to do since the API has existed for a long time... p.callbacks = callbacks; p.callback += OnMultiPathComplete; p.nnConstraint.graphMask = graphMask; StartPathInternal(p, callback); return p; } /** Draws gizmos for the Seeker */ public void OnDrawGizmos () { if (lastCompletedNodePath == null || !drawGizmos) { return; } if (detailedGizmos) { Gizmos.color = new Color(0.7F, 0.5F, 0.1F, 0.5F); if (lastCompletedNodePath != null) { for (int i = 0; i < lastCompletedNodePath.Count-1; i++) { Gizmos.DrawLine((Vector3)lastCompletedNodePath[i].position, (Vector3)lastCompletedNodePath[i+1].position); } } } Gizmos.color = new Color(0, 1F, 0, 1F); if (lastCompletedVectorPath != null) { for (int i = 0; i < lastCompletedVectorPath.Count-1; i++) { Gizmos.DrawLine(lastCompletedVectorPath[i], lastCompletedVectorPath[i+1]); } } } /** Handle serialization backwards compatibility */ void ISerializationCallbackReceiver.OnBeforeSerialize () { } /** Handle serialization backwards compatibility */ void ISerializationCallbackReceiver.OnAfterDeserialize () { if (traversableTagsCompatibility != null && traversableTagsCompatibility.tagsChange != -1) { traversableTags = traversableTagsCompatibility.tagsChange; traversableTagsCompatibility = new TagMask(-1, -1); } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using Org.BouncyCastle.Math.Raw; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecP224K1Point : AbstractFpPoint { /** * Create a point which encodes with point compression. * * @param curve * the curve to use * @param x * affine x co-ordinate * @param y * affine y co-ordinate * * @deprecated Use ECCurve.createPoint to construct points */ public SecP224K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) : this(curve, x, y, false) { } /** * Create a point that encodes with or without point compresion. * * @param curve * the curve to use * @param x * affine x co-ordinate * @param y * affine y co-ordinate * @param withCompression * if true encode with point compression * * @deprecated per-point compression property will be removed, refer * {@link #getEncoded(bool)} */ public SecP224K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) : base(curve, x, y, withCompression) { if ((x == null) != (y == null)) throw new ArgumentException("Exactly one of the field elements is null"); } internal SecP224K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) : base(curve, x, y, zs, withCompression) { } protected override ECPoint Detach() { return new SecP224K1Point(null, AffineXCoord, AffineYCoord); } public override ECPoint Add(ECPoint b) { if (this.IsInfinity) return b; if (b.IsInfinity) return this; if (this == b) return Twice(); ECCurve curve = this.Curve; SecP224K1FieldElement X1 = (SecP224K1FieldElement)this.RawXCoord, Y1 = (SecP224K1FieldElement)this.RawYCoord; SecP224K1FieldElement X2 = (SecP224K1FieldElement)b.RawXCoord, Y2 = (SecP224K1FieldElement)b.RawYCoord; SecP224K1FieldElement Z1 = (SecP224K1FieldElement)this.RawZCoords[0]; SecP224K1FieldElement Z2 = (SecP224K1FieldElement)b.RawZCoords[0]; uint c; uint[] tt1 = Nat224.CreateExt(); uint[] t2 = Nat224.Create(); uint[] t3 = Nat224.Create(); uint[] t4 = Nat224.Create(); bool Z1IsOne = Z1.IsOne; uint[] U2, S2; if (Z1IsOne) { U2 = X2.x; S2 = Y2.x; } else { S2 = t3; SecP224K1Field.Square(Z1.x, S2); U2 = t2; SecP224K1Field.Multiply(S2, X2.x, U2); SecP224K1Field.Multiply(S2, Z1.x, S2); SecP224K1Field.Multiply(S2, Y2.x, S2); } bool Z2IsOne = Z2.IsOne; uint[] U1, S1; if (Z2IsOne) { U1 = X1.x; S1 = Y1.x; } else { S1 = t4; SecP224K1Field.Square(Z2.x, S1); U1 = tt1; SecP224K1Field.Multiply(S1, X1.x, U1); SecP224K1Field.Multiply(S1, Z2.x, S1); SecP224K1Field.Multiply(S1, Y1.x, S1); } uint[] H = Nat224.Create(); SecP224K1Field.Subtract(U1, U2, H); uint[] R = t2; SecP224K1Field.Subtract(S1, S2, R); // Check if b == this or b == -this if (Nat224.IsZero(H)) { if (Nat224.IsZero(R)) { // this == b, i.e. this must be doubled return this.Twice(); } // this == -b, i.e. the result is the point at infinity return curve.Infinity; } uint[] HSquared = t3; SecP224K1Field.Square(H, HSquared); uint[] G = Nat224.Create(); SecP224K1Field.Multiply(HSquared, H, G); uint[] V = t3; SecP224K1Field.Multiply(HSquared, U1, V); SecP224K1Field.Negate(G, G); Nat224.Mul(S1, G, tt1); c = Nat224.AddBothTo(V, V, G); SecP224K1Field.Reduce32(c, G); SecP224K1FieldElement X3 = new SecP224K1FieldElement(t4); SecP224K1Field.Square(R, X3.x); SecP224K1Field.Subtract(X3.x, G, X3.x); SecP224K1FieldElement Y3 = new SecP224K1FieldElement(G); SecP224K1Field.Subtract(V, X3.x, Y3.x); SecP224K1Field.MultiplyAddToExt(Y3.x, R, tt1); SecP224K1Field.Reduce(tt1, Y3.x); SecP224K1FieldElement Z3 = new SecP224K1FieldElement(H); if (!Z1IsOne) { SecP224K1Field.Multiply(Z3.x, Z1.x, Z3.x); } if (!Z2IsOne) { SecP224K1Field.Multiply(Z3.x, Z2.x, Z3.x); } ECFieldElement[] zs = new ECFieldElement[] { Z3 }; return new SecP224K1Point(curve, X3, Y3, zs, IsCompressed); } public override ECPoint Twice() { if (this.IsInfinity) return this; ECCurve curve = this.Curve; SecP224K1FieldElement Y1 = (SecP224K1FieldElement)this.RawYCoord; if (Y1.IsZero) return curve.Infinity; SecP224K1FieldElement X1 = (SecP224K1FieldElement)this.RawXCoord, Z1 = (SecP224K1FieldElement)this.RawZCoords[0]; uint c; uint[] Y1Squared = Nat224.Create(); SecP224K1Field.Square(Y1.x, Y1Squared); uint[] T = Nat224.Create(); SecP224K1Field.Square(Y1Squared, T); uint[] M = Nat224.Create(); SecP224K1Field.Square(X1.x, M); c = Nat224.AddBothTo(M, M, M); SecP224K1Field.Reduce32(c, M); uint[] S = Y1Squared; SecP224K1Field.Multiply(Y1Squared, X1.x, S); c = Nat.ShiftUpBits(7, S, 2, 0); SecP224K1Field.Reduce32(c, S); uint[] t1 = Nat224.Create(); c = Nat.ShiftUpBits(7, T, 3, 0, t1); SecP224K1Field.Reduce32(c, t1); SecP224K1FieldElement X3 = new SecP224K1FieldElement(T); SecP224K1Field.Square(M, X3.x); SecP224K1Field.Subtract(X3.x, S, X3.x); SecP224K1Field.Subtract(X3.x, S, X3.x); SecP224K1FieldElement Y3 = new SecP224K1FieldElement(S); SecP224K1Field.Subtract(S, X3.x, Y3.x); SecP224K1Field.Multiply(Y3.x, M, Y3.x); SecP224K1Field.Subtract(Y3.x, t1, Y3.x); SecP224K1FieldElement Z3 = new SecP224K1FieldElement(M); SecP224K1Field.Twice(Y1.x, Z3.x); if (!Z1.IsOne) { SecP224K1Field.Multiply(Z3.x, Z1.x, Z3.x); } return new SecP224K1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed); } public override ECPoint TwicePlus(ECPoint b) { if (this == b) return ThreeTimes(); if (this.IsInfinity) return b; if (b.IsInfinity) return Twice(); ECFieldElement Y1 = this.RawYCoord; if (Y1.IsZero) return b; return Twice().Add(b); } public override ECPoint ThreeTimes() { if (this.IsInfinity || this.RawYCoord.IsZero) return this; // NOTE: Be careful about recursions between TwicePlus and ThreeTimes return Twice().Add(this); } public override ECPoint Negate() { if (IsInfinity) return this; return new SecP224K1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); } } } #endif
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Configuration.SectionInformation.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Configuration { sealed public partial class SectionInformation { #region Methods and constructors public void ForceDeclaration() { Contract.Ensures(!this.IsLocked); } public void ForceDeclaration(bool force) { Contract.Ensures(!this.IsLocked); } public ConfigurationSection GetParentSection() { return default(ConfigurationSection); } public string GetRawXml() { return default(string); } public void ProtectSection(string protectionProvider) { } public void RevertToParent() { } internal SectionInformation() { } public void SetRawXml(string rawXml) { } public void UnprotectSection() { } #endregion #region Properties and indexers public ConfigurationAllowDefinition AllowDefinition { get { return default(ConfigurationAllowDefinition); } set { } } public ConfigurationAllowExeDefinition AllowExeDefinition { get { return default(ConfigurationAllowExeDefinition); } set { } } public bool AllowLocation { get { return default(bool); } set { } } public bool AllowOverride { get { return default(bool); } set { } } public string ConfigSource { get { return default(string); } set { } } public bool ForceSave { get { return default(bool); } set { Contract.Ensures(!this.IsLocked); } } public bool InheritInChildApplications { get { return default(bool); } set { } } public bool IsDeclarationRequired { get { return default(bool); } } public bool IsDeclared { get { return default(bool); } } public bool IsLocked { get { return default(bool); } } public bool IsProtected { get { Contract.Ensures(Contract.Result<bool>() == true); return default(bool); } } public string Name { get { return default(string); } } public OverrideMode OverrideMode { get { return default(OverrideMode); } set { } } public OverrideMode OverrideModeDefault { get { return default(OverrideMode); } set { } } public System.Configuration.OverrideMode OverrideModeEffective { get { Contract.Ensures(((System.Configuration.OverrideMode)(1)) <= Contract.Result<System.Configuration.OverrideMode>()); Contract.Ensures(Contract.Result<System.Configuration.OverrideMode>() <= ((System.Configuration.OverrideMode)(2))); return default(System.Configuration.OverrideMode); } } public ProtectedConfigurationProvider ProtectionProvider { get { return default(ProtectedConfigurationProvider); } } public bool RequirePermission { get { return default(bool); } set { } } public bool RestartOnExternalChanges { get { return default(bool); } set { } } public string SectionName { get { return default(string); } } public string Type { get { return default(string); } set { Contract.Ensures(!string.IsNullOrEmpty(value)); Contract.Ensures(0 <= value.Length); } } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System; using System.Text; using NPOI.Util; /** * Title: Window Two Record * Description: sheet window Settings * REFERENCE: PG 422 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2) * @author Andrew C. Oliver (acoliver at apache dot org) * @author Jason Height (jheight at chariot dot net dot au) * @version 2.0-pre */ public class WindowTwoRecord : StandardRecord { public const short sid = 0x23e; // bitfields private BitField displayFormulas = BitFieldFactory.GetInstance(0x01); private BitField displayGridlines = BitFieldFactory.GetInstance(0x02); private BitField displayRowColHeadings = BitFieldFactory.GetInstance(0x04); private BitField freezePanes = BitFieldFactory.GetInstance(0x08); private BitField displayZeros = BitFieldFactory.GetInstance(0x10); // if false use color in field 4 if true use default foreground for headers private BitField defaultHeader = BitFieldFactory.GetInstance(0x20); private BitField arabic = BitFieldFactory.GetInstance(0x40); private BitField displayGuts = BitFieldFactory.GetInstance(0x80); private BitField freezePanesNoSplit = BitFieldFactory.GetInstance(0x100); private BitField selected = BitFieldFactory.GetInstance(0x200); private BitField active = BitFieldFactory.GetInstance(0x400); private BitField savedInPageBreakPreview = BitFieldFactory.GetInstance(0x800); // 4-7 reserved // end bitfields private short field_1_options; private short field_2_top_row; private short field_3_left_col; private int field_4_header_color; private short field_5_page_break_zoom; private short field_6_normal_zoom; private int field_7_reserved; public WindowTwoRecord() { } /** * Constructs a WindowTwo record and Sets its fields appropriately. * @param in the RecordInputstream to Read the record from */ public WindowTwoRecord(RecordInputStream in1) { int size = in1.Remaining; field_1_options = in1.ReadShort(); field_2_top_row = in1.ReadShort(); field_3_left_col = in1.ReadShort(); field_4_header_color = in1.ReadInt(); if (size > 10) { field_5_page_break_zoom = in1.ReadShort(); field_6_normal_zoom = in1.ReadShort(); } if (size > 14) { // there Is a special case of this record that has only 14 bytes...undocumented! field_7_reserved = in1.ReadInt(); } } /** * Get the options bitmask or just use the bit Setters. * @return options */ public short Options { get { return field_1_options; } set { field_1_options = value; } } // option bitfields /** * Get whether the window should Display formulas * @return formulas or not */ public bool DisplayFormulas { get { return displayFormulas.IsSet(field_1_options); } set { field_1_options = displayFormulas.SetShortBoolean(field_1_options, value); } } /** * Get whether the window should Display gridlines * @return gridlines or not */ public bool DisplayGridlines { get { return displayGridlines.IsSet(field_1_options); } set { field_1_options = displayGridlines.SetShortBoolean(field_1_options, value); } } /** * Get whether the window should Display row and column headings * @return headings or not */ public bool DisplayRowColHeadings { get { return displayRowColHeadings.IsSet(field_1_options); } set { field_1_options = displayRowColHeadings.SetShortBoolean(field_1_options, value); } } /** * Get whether the window should freeze panes * @return freeze panes or not */ public bool FreezePanes { get { return freezePanes.IsSet(field_1_options); } set { field_1_options = freezePanes.SetShortBoolean(field_1_options, value); } } /** * Get whether the window should Display zero values * @return zeros or not */ public bool DisplayZeros { get { return displayZeros.IsSet(field_1_options); } set { field_1_options = displayZeros.SetShortBoolean(field_1_options, value); } } /** * Get whether the window should Display a default header * @return header or not */ public bool DefaultHeader { get { return defaultHeader.IsSet(field_1_options); } set { field_1_options = defaultHeader.SetShortBoolean(field_1_options, value); } } /** * Is this arabic? * @return arabic or not */ public bool Arabic { get { return arabic.IsSet(field_1_options); } set { field_1_options = arabic.SetShortBoolean(field_1_options, value); } } /** * Get whether the outline symbols are displaed * @return symbols or not */ public bool DisplayGuts { get { return displayGuts.IsSet(field_1_options); } set { field_1_options = displayGuts.SetShortBoolean(field_1_options, value); } } /** * freeze Unsplit panes or not * @return freeze or not */ public bool FreezePanesNoSplit { get { return freezePanesNoSplit.IsSet(field_1_options); } set { field_1_options = freezePanesNoSplit.SetShortBoolean(field_1_options, value); } } /** * sheet tab Is selected * @return selected or not */ public bool IsSelected { get { return selected.IsSet(field_1_options); } set { field_1_options = selected.SetShortBoolean(field_1_options, value); } } /** * Is the sheet currently Displayed in the window * @return Displayed or not */ public bool IsActive { get { return active.IsSet(field_1_options); } set { field_1_options = active.SetShortBoolean(field_1_options, value); } } /** * was the sheet saved in page break view * @return pagebreaksaved or not */ public bool SavedInPageBreakPreview { get { return savedInPageBreakPreview.IsSet(field_1_options); } set { field_1_options = savedInPageBreakPreview.SetShortBoolean(field_1_options, value); } } // end of bitfields. /** * Get the top row visible in the window * @return toprow */ public short TopRow { get { return field_2_top_row; } set { field_2_top_row = value; } } /** * Get the leftmost column Displayed in the window * @return leftmost */ public short LeftCol { get { return field_3_left_col; } set { field_3_left_col = value; } } /** * Get the palette index for the header color * @return color */ public int HeaderColor { get { return field_4_header_color; } set { field_4_header_color = value; } } /** * zoom magification in page break view * @return zoom */ public short PageBreakZoom { get { return field_5_page_break_zoom; } set { field_5_page_break_zoom = value; } } /** * Get the zoom magnification in normal view * @return zoom */ public short NormalZoom { get { return field_6_normal_zoom; } set { field_6_normal_zoom = value; } } /** * Get the reserved bits - why would you do this? * @return reserved stuff -probably garbage */ public int Reserved { get { return field_7_reserved; } set { field_7_reserved = value; } } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[WINDOW2]\n"); buffer.Append(" .options = ") .Append(StringUtil.ToHexString(Options)).Append("\n"); buffer.Append(" .dispformulas= ").Append(DisplayFormulas) .Append("\n"); buffer.Append(" .dispgridlins= ").Append(DisplayGridlines) .Append("\n"); buffer.Append(" .disprcheadin= ") .Append(DisplayRowColHeadings).Append("\n"); buffer.Append(" .freezepanes = ").Append(FreezePanes) .Append("\n"); buffer.Append(" .Displayzeros= ").Append(DisplayZeros) .Append("\n"); buffer.Append(" .defaultheadr= ").Append(DefaultHeader) .Append("\n"); buffer.Append(" .arabic = ").Append(Arabic) .Append("\n"); buffer.Append(" .Displayguts = ").Append(DisplayGuts) .Append("\n"); buffer.Append(" .frzpnsnosplt= ") .Append(FreezePanesNoSplit).Append("\n"); buffer.Append(" .selected = ").Append(IsSelected) .Append("\n"); buffer.Append(" .active = ").Append(IsActive) .Append("\n"); buffer.Append(" .svdinpgbrkpv= ") .Append(SavedInPageBreakPreview).Append("\n"); buffer.Append(" .toprow = ") .Append(StringUtil.ToHexString(TopRow)).Append("\n"); buffer.Append(" .leftcol = ") .Append(StringUtil.ToHexString(LeftCol)).Append("\n"); buffer.Append(" .headercolor = ") .Append(StringUtil.ToHexString(HeaderColor)).Append("\n"); buffer.Append(" .pagebreakzoom = ") .Append(StringUtil.ToHexString(PageBreakZoom)).Append("\n"); buffer.Append(" .normalzoom = ") .Append(StringUtil.ToHexString(NormalZoom)).Append("\n"); buffer.Append(" .reserved = ") .Append(StringUtil.ToHexString(Reserved)).Append("\n"); buffer.Append("[/WINDOW2]\n"); return buffer.ToString(); } public override void Serialize(ILittleEndianOutput out1) { out1.WriteShort(Options); out1.WriteShort(TopRow); out1.WriteShort(LeftCol); out1.WriteInt(HeaderColor); out1.WriteShort(PageBreakZoom); out1.WriteShort(NormalZoom); out1.WriteInt(Reserved); } protected override int DataSize { get { return 18; } } public override short Sid { get { return sid; } } public override Object Clone() { WindowTwoRecord rec = new WindowTwoRecord(); rec.field_1_options = field_1_options; rec.field_2_top_row = field_2_top_row; rec.field_3_left_col = field_3_left_col; rec.field_4_header_color = field_4_header_color; rec.field_5_page_break_zoom = field_5_page_break_zoom; rec.field_6_normal_zoom = field_6_normal_zoom; rec.field_7_reserved = field_7_reserved; return rec; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Threading.Tasks { public static class __Parallel { public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource>( IObservable<IEnumerable<TSource>> source, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<Action<TSource>> body) { return Observable.Zip(source, parallelOptions, body, (sourceLambda, parallelOptionsLambda, bodyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, parallelOptionsLambda, bodyLambda)); } public static IObservable<System.Reactive.Unit> Invoke(IObservable<System.Action[]> actions) { return Observable.Do(actions, (actionsLambda) => System.Threading.Tasks.Parallel.Invoke(actionsLambda)) .ToUnit(); } public static IObservable<System.Reactive.Unit> Invoke( IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<System.Action[]> actions) { return ObservableExt.ZipExecute(parallelOptions, actions, (parallelOptionsLambda, actionsLambda) => System.Threading.Tasks.Parallel.Invoke(parallelOptionsLambda, actionsLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> For( IObservable<System.Int32> fromInclusive, IObservable<System.Int32> toExclusive, IObservable<System.Action<System.Int32>> body) { return Observable.Zip(fromInclusive, toExclusive, body, (fromInclusiveLambda, toExclusiveLambda, bodyLambda) => System.Threading.Tasks.Parallel.For(fromInclusiveLambda, toExclusiveLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> For( IObservable<System.Int64> fromInclusive, IObservable<System.Int64> toExclusive, IObservable<System.Action<System.Int64>> body) { return Observable.Zip(fromInclusive, toExclusive, body, (fromInclusiveLambda, toExclusiveLambda, bodyLambda) => System.Threading.Tasks.Parallel.For(fromInclusiveLambda, toExclusiveLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> For( IObservable<System.Int32> fromInclusive, IObservable<System.Int32> toExclusive, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<System.Action<System.Int32>> body) { return Observable.Zip(fromInclusive, toExclusive, parallelOptions, body, (fromInclusiveLambda, toExclusiveLambda, parallelOptionsLambda, bodyLambda) => System.Threading.Tasks.Parallel.For(fromInclusiveLambda, toExclusiveLambda, parallelOptionsLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> For( IObservable<System.Int64> fromInclusive, IObservable<System.Int64> toExclusive, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<System.Action<System.Int64>> body) { return Observable.Zip(fromInclusive, toExclusive, parallelOptions, body, (fromInclusiveLambda, toExclusiveLambda, parallelOptionsLambda, bodyLambda) => System.Threading.Tasks.Parallel.For(fromInclusiveLambda, toExclusiveLambda, parallelOptionsLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> For( IObservable<System.Int32> fromInclusive, IObservable<System.Int32> toExclusive, IObservable<System.Action<System.Int32, System.Threading.Tasks.ParallelLoopState>> body) { return Observable.Zip(fromInclusive, toExclusive, body, (fromInclusiveLambda, toExclusiveLambda, bodyLambda) => System.Threading.Tasks.Parallel.For(fromInclusiveLambda, toExclusiveLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> For( IObservable<System.Int64> fromInclusive, IObservable<System.Int64> toExclusive, IObservable<System.Action<System.Int64, System.Threading.Tasks.ParallelLoopState>> body) { return Observable.Zip(fromInclusive, toExclusive, body, (fromInclusiveLambda, toExclusiveLambda, bodyLambda) => System.Threading.Tasks.Parallel.For(fromInclusiveLambda, toExclusiveLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> For( IObservable<System.Int32> fromInclusive, IObservable<System.Int32> toExclusive, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<System.Action<System.Int32, System.Threading.Tasks.ParallelLoopState>> body) { return Observable.Zip(fromInclusive, toExclusive, parallelOptions, body, (fromInclusiveLambda, toExclusiveLambda, parallelOptionsLambda, bodyLambda) => System.Threading.Tasks.Parallel.For(fromInclusiveLambda, toExclusiveLambda, parallelOptionsLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> For( IObservable<System.Int64> fromInclusive, IObservable<System.Int64> toExclusive, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<System.Action<System.Int64, System.Threading.Tasks.ParallelLoopState>> body) { return Observable.Zip(fromInclusive, toExclusive, parallelOptions, body, (fromInclusiveLambda, toExclusiveLambda, parallelOptionsLambda, bodyLambda) => System.Threading.Tasks.Parallel.For(fromInclusiveLambda, toExclusiveLambda, parallelOptionsLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> For<TLocal>( IObservable<System.Int32> fromInclusive, IObservable<System.Int32> toExclusive, IObservable<Func<TLocal>> localInit, IObservable<Func<System.Int32, System.Threading.Tasks.ParallelLoopState, TLocal, TLocal>> body, IObservable<Action<TLocal>> localFinally) { return Observable.Zip(fromInclusive, toExclusive, localInit, body, localFinally, (fromInclusiveLambda, toExclusiveLambda, localInitLambda, bodyLambda, localFinallyLambda) => System.Threading.Tasks.Parallel.For(fromInclusiveLambda, toExclusiveLambda, localInitLambda, bodyLambda, localFinallyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> For<TLocal>( IObservable<System.Int64> fromInclusive, IObservable<System.Int64> toExclusive, IObservable<Func<TLocal>> localInit, IObservable<Func<System.Int64, System.Threading.Tasks.ParallelLoopState, TLocal, TLocal>> body, IObservable<Action<TLocal>> localFinally) { return Observable.Zip(fromInclusive, toExclusive, localInit, body, localFinally, (fromInclusiveLambda, toExclusiveLambda, localInitLambda, bodyLambda, localFinallyLambda) => System.Threading.Tasks.Parallel.For(fromInclusiveLambda, toExclusiveLambda, localInitLambda, bodyLambda, localFinallyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> For<TLocal>( IObservable<System.Int32> fromInclusive, IObservable<System.Int32> toExclusive, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<Func<TLocal>> localInit, IObservable<Func<System.Int32, System.Threading.Tasks.ParallelLoopState, TLocal, TLocal>> body, IObservable<Action<TLocal>> localFinally) { return Observable.Zip(fromInclusive, toExclusive, parallelOptions, localInit, body, localFinally, (fromInclusiveLambda, toExclusiveLambda, parallelOptionsLambda, localInitLambda, bodyLambda, localFinallyLambda) => System.Threading.Tasks.Parallel.For(fromInclusiveLambda, toExclusiveLambda, parallelOptionsLambda, localInitLambda, bodyLambda, localFinallyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> For<TLocal>( IObservable<System.Int64> fromInclusive, IObservable<System.Int64> toExclusive, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<Func<TLocal>> localInit, IObservable<Func<System.Int64, System.Threading.Tasks.ParallelLoopState, TLocal, TLocal>> body, IObservable<Action<TLocal>> localFinally) { return Observable.Zip(fromInclusive, toExclusive, parallelOptions, localInit, body, localFinally, (fromInclusiveLambda, toExclusiveLambda, parallelOptionsLambda, localInitLambda, bodyLambda, localFinallyLambda) => System.Threading.Tasks.Parallel.For(fromInclusiveLambda, toExclusiveLambda, parallelOptionsLambda, localInitLambda, bodyLambda, localFinallyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource>( IObservable<IEnumerable<TSource>> source, IObservable<Action<TSource>> body) { return Observable.Zip(source, body, (sourceLambda, bodyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource>( IObservable<IEnumerable<TSource>> source, IObservable<Action<TSource, System.Threading.Tasks.ParallelLoopState>> body) { return Observable.Zip(source, body, (sourceLambda, bodyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource>( IObservable<IEnumerable<TSource>> source, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<Action<TSource, System.Threading.Tasks.ParallelLoopState>> body) { return Observable.Zip(source, parallelOptions, body, (sourceLambda, parallelOptionsLambda, bodyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, parallelOptionsLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource>( IObservable<IEnumerable<TSource>> source, IObservable<Action<TSource, System.Threading.Tasks.ParallelLoopState, System.Int64>> body) { return Observable.Zip(source, body, (sourceLambda, bodyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource>( IObservable<IEnumerable<TSource>> source, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<Action<TSource, System.Threading.Tasks.ParallelLoopState, System.Int64>> body) { return Observable.Zip(source, parallelOptions, body, (sourceLambda, parallelOptionsLambda, bodyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, parallelOptionsLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource, TLocal>( IObservable<IEnumerable<TSource>> source, IObservable<Func<TLocal>> localInit, IObservable<Func<TSource, System.Threading.Tasks.ParallelLoopState, TLocal, TLocal>> body, IObservable<Action<TLocal>> localFinally) { return Observable.Zip(source, localInit, body, localFinally, (sourceLambda, localInitLambda, bodyLambda, localFinallyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, localInitLambda, bodyLambda, localFinallyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource, TLocal>( IObservable<IEnumerable<TSource>> source, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<Func<TLocal>> localInit, IObservable<Func<TSource, System.Threading.Tasks.ParallelLoopState, TLocal, TLocal>> body, IObservable<Action<TLocal>> localFinally) { return Observable.Zip(source, parallelOptions, localInit, body, localFinally, (sourceLambda, parallelOptionsLambda, localInitLambda, bodyLambda, localFinallyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, parallelOptionsLambda, localInitLambda, bodyLambda, localFinallyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource, TLocal>( IObservable<IEnumerable<TSource>> source, IObservable<Func<TLocal>> localInit, IObservable<Func<TSource, System.Threading.Tasks.ParallelLoopState, System.Int64, TLocal, TLocal>> body, IObservable<Action<TLocal>> localFinally) { return Observable.Zip(source, localInit, body, localFinally, (sourceLambda, localInitLambda, bodyLambda, localFinallyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, localInitLambda, bodyLambda, localFinallyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource, TLocal>( IObservable<IEnumerable<TSource>> source, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<Func<TLocal>> localInit, IObservable<Func<TSource, System.Threading.Tasks.ParallelLoopState, System.Int64, TLocal, TLocal>> body, IObservable<Action<TLocal>> localFinally) { return Observable.Zip(source, parallelOptions, localInit, body, localFinally, (sourceLambda, parallelOptionsLambda, localInitLambda, bodyLambda, localFinallyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, parallelOptionsLambda, localInitLambda, bodyLambda, localFinallyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource>( IObservable<Partitioner<TSource>> source, IObservable<Action<TSource>> body) { return Observable.Zip(source, body, (sourceLambda, bodyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource>( IObservable<Partitioner<TSource>> source, IObservable<Action<TSource, System.Threading.Tasks.ParallelLoopState>> body) { return Observable.Zip(source, body, (sourceLambda, bodyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource>( IObservable<OrderablePartitioner<TSource>> source, IObservable<Action<TSource, System.Threading.Tasks.ParallelLoopState, System.Int64>> body) { return Observable.Zip(source, body, (sourceLambda, bodyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource, TLocal>( IObservable<Partitioner<TSource>> source, IObservable<Func<TLocal>> localInit, IObservable<Func<TSource, System.Threading.Tasks.ParallelLoopState, TLocal, TLocal>> body, IObservable<Action<TLocal>> localFinally) { return Observable.Zip(source, localInit, body, localFinally, (sourceLambda, localInitLambda, bodyLambda, localFinallyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, localInitLambda, bodyLambda, localFinallyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource, TLocal>( IObservable<OrderablePartitioner<TSource>> source, IObservable<Func<TLocal>> localInit, IObservable<Func<TSource, System.Threading.Tasks.ParallelLoopState, System.Int64, TLocal, TLocal>> body, IObservable<Action<TLocal>> localFinally) { return Observable.Zip(source, localInit, body, localFinally, (sourceLambda, localInitLambda, bodyLambda, localFinallyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, localInitLambda, bodyLambda, localFinallyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource>( IObservable<Partitioner<TSource>> source, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<Action<TSource>> body) { return Observable.Zip(source, parallelOptions, body, (sourceLambda, parallelOptionsLambda, bodyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, parallelOptionsLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource>( IObservable<Partitioner<TSource>> source, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<Action<TSource, System.Threading.Tasks.ParallelLoopState>> body) { return Observable.Zip(source, parallelOptions, body, (sourceLambda, parallelOptionsLambda, bodyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, parallelOptionsLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource>( IObservable<OrderablePartitioner<TSource>> source, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<Action<TSource, System.Threading.Tasks.ParallelLoopState, System.Int64>> body) { return Observable.Zip(source, parallelOptions, body, (sourceLambda, parallelOptionsLambda, bodyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, parallelOptionsLambda, bodyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource, TLocal>( IObservable<Partitioner<TSource>> source, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<Func<TLocal>> localInit, IObservable<Func<TSource, System.Threading.Tasks.ParallelLoopState, TLocal, TLocal>> body, IObservable<Action<TLocal>> localFinally) { return Observable.Zip(source, parallelOptions, localInit, body, localFinally, (sourceLambda, parallelOptionsLambda, localInitLambda, bodyLambda, localFinallyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, parallelOptionsLambda, localInitLambda, bodyLambda, localFinallyLambda)); } public static IObservable<System.Threading.Tasks.ParallelLoopResult> ForEach<TSource, TLocal>( IObservable<OrderablePartitioner<TSource>> source, IObservable<System.Threading.Tasks.ParallelOptions> parallelOptions, IObservable<Func<TLocal>> localInit, IObservable<Func<TSource, System.Threading.Tasks.ParallelLoopState, System.Int64, TLocal, TLocal>> body, IObservable<Action<TLocal>> localFinally) { return Observable.Zip(source, parallelOptions, localInit, body, localFinally, (sourceLambda, parallelOptionsLambda, localInitLambda, bodyLambda, localFinallyLambda) => System.Threading.Tasks.Parallel.ForEach(sourceLambda, parallelOptionsLambda, localInitLambda, bodyLambda, localFinallyLambda)); } } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using Flunity.Utils; namespace Flunity { /// <summary> /// DisplayObject to render multiline text /// </summary> public class TextField : TextBase { private const char SPACE_CHAR = ' '; public float rowSpacing = 0; private readonly float _rowHeight; private readonly List<TextRow> _rows = new List<TextRow>(4); private bool _textDirty = true; public TextField(DisplayContainer parent, string fontName, int fontSize = 0) : this(fontName, fontSize) { this.parent = parent; } public TextField(string fontName, int fontSize = 0) : base(fontName, fontSize) { _rowHeight = resource.rowHeight * fontScale; } public TextField(DisplayContainer parent, int fontSize = 0) : this(fontSize) { this.parent = parent; } public TextField(int fontSize = 0) : base(null, fontSize) { _rowHeight = resource.rowHeight * fontScale; } internal protected override void UpdateTransform() { base.UpdateTransform(); ValidateText(); ClearQuads(); var textTopLeft = GetTextTopLeft(); var rowPos = textTopLeft; foreach (var row in _rows) { rowPos.x = GetRowOffsetX(row.textWidth); AddWordQuads(row.text, rowPos); rowPos.y += ((_rowHeight + rowSpacing)); } } private float GetRowOffsetX(float rowWidth) { if (hAlignment == HAlign.LEFT) return 0; if (hAlignment == HAlign.CENTER) return (0.5f * (width - rowWidth)).RoundToInt(); return width - rowWidth; } protected override Vector2 GetTextSize() { ValidateText(); var w = _rows.Max(r => r.textWidth); var h = _rows.Count * _rowHeight + (_rows.Count - 1) * rowSpacing; return new Vector2( (float) Math.Ceiling(w), (float) Math.Ceiling(h)); } internal void ValidateText() { if (_textDirty) { CreateRows(); _textDirty = false; } } private void CreateRows() { var spaceCharInfo = resource.GetCharInfo(SPACE_CHAR); var spaceWidth = spaceCharInfo.symbolWidth * fontScale; _rows.Clear(); var textString = text ?? ""; var words = string.Join("\n ", textString.Split('\n')).Split(SPACE_CHAR); var currentRow = TextRow.empty; var wordIndex = 0; // don't use size/width properties to avoid stack overflow when autoSize == true; var maxWidth = _size.x; while (wordIndex < words.Length) { var word = words[wordIndex]; if (word == null) continue; var explicitLineBrake = (word.Length > 0 && word[word.Length - 1] == '\n'); if (explicitLineBrake) word = word.Replace("\n", ""); if (word.Length <= 0) { if (wordIndex == words.Length - 1 || explicitLineBrake) { _rows.Add(currentRow); currentRow = TextRow.empty; } wordIndex++; continue; } var wordWidth = CalculateTextSize(word).x; var spacing = currentRow.text.Length == 0 ? 0 : spaceWidth; var doesFit = currentRow.textWidth + spacing + wordWidth <= maxWidth; var needNewLine = !doesFit || wordIndex == words.Length - 1 || explicitLineBrake; if (currentRow.text.Length == 0) { currentRow.text += word; currentRow.textWidth += wordWidth; wordIndex++; } else if (doesFit) { currentRow.text += SPACE_CHAR + word; currentRow.textWidth += spaceWidth + wordWidth; wordIndex++; } if (needNewLine) { _rows.Add(currentRow); currentRow = TextRow.empty; } } } /// <summary> /// Rows count /// </summary> public int rowsCount { get { return _rows.Count; } } public override string text { get { return base.text; } set { base.text = value; _textDirty = true; } } public override Vector2 size { get { return autoSize ? new Vector2(_size.x, textSize.y) : _size; } set { _size = value; _textDirty = true; } } } internal struct TextRow { public static TextRow empty { get { return new TextRow {text = "", textWidth = 0}; } } public String text; public float textWidth; } }
/* * Copyright (c) 2007-2008, Second Life Reverse Engineering Team * 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. * - Neither the name of the Second Life Reverse Engineering Team nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using libsecondlife.Packets; namespace libsecondlife { /// <summary> /// /// </summary> [Flags] public enum FriendRights : int { /// <summary>The avatar has no rights</summary> None = 0, /// <summary>The avatar can see the online status of the target avatar</summary> CanSeeOnline = 1, /// <summary>The avatar can see the location of the target avatar on the map</summary> CanSeeOnMap = 2, /// <summary>The avatar can modify the ojects of the target avatar </summary> CanModifyObjects = 4 } /// <summary> /// This class holds information about an avatar in the friends list. There are two ways /// to interface to this class. The first is through the set of boolean properties. This is the typical /// way clients of this class will use it. The second interface is through two bitmap properties. While /// the bitmap interface is public, it is intended for use the libsecondlife framework. /// </summary> public class FriendInfo { private LLUUID m_id; private string m_name; private bool m_isOnline; private bool m_canSeeMeOnline; private bool m_canSeeMeOnMap; private bool m_canModifyMyObjects; private bool m_canSeeThemOnline; private bool m_canSeeThemOnMap; private bool m_canModifyTheirObjects; /// <summary> /// Used by the libsecondlife framework when building the initial list of friends /// at login time. This constructor should not be called by consummer of this class. /// </summary> /// <param name="id">System ID of the avatar being prepesented</param> /// <param name="theirRights">Rights the friend has to see you online and to modify your objects</param> /// <param name="myRights">Rights you have to see your friend online and to modify their objects</param> public FriendInfo(LLUUID id, FriendRights theirRights, FriendRights myRights) { m_id = id; m_canSeeMeOnline = (theirRights & FriendRights.CanSeeOnline) != 0; m_canSeeMeOnMap = (theirRights & FriendRights.CanSeeOnMap) != 0; m_canModifyMyObjects = (theirRights & FriendRights.CanModifyObjects) != 0; m_canSeeThemOnline = (myRights & FriendRights.CanSeeOnline) != 0; m_canSeeThemOnMap = (myRights & FriendRights.CanSeeOnMap) != 0; m_canModifyTheirObjects = (myRights & FriendRights.CanModifyObjects) != 0; } /// <summary> /// System ID of the avatar /// </summary> public LLUUID UUID { get { return m_id; } } /// <summary> /// full name of the avatar /// </summary> public string Name { get { return m_name; } set { m_name = value; } } /// <summary> /// True if the avatar is online /// </summary> public bool IsOnline { get { return m_isOnline; } set { m_isOnline = value; } } /// <summary> /// True if the friend can see if I am online /// </summary> public bool CanSeeMeOnline { get { return m_canSeeMeOnline; } set { m_canSeeMeOnline = value; // if I can't see them online, then I can't see them on the map if (!m_canSeeMeOnline) m_canSeeMeOnMap = false; } } /// <summary> /// True if the friend can see me on the map /// </summary> public bool CanSeeMeOnMap { get { return m_canSeeMeOnMap; } set { // if I can't see them online, then I can't see them on the map if (m_canSeeMeOnline) m_canSeeMeOnMap = value; } } /// <summary> /// True if the freind can modify my objects /// </summary> public bool CanModifyMyObjects { get { return m_canModifyMyObjects; } set { m_canModifyMyObjects = value; } } /// <summary> /// True if I can see if my friend is online /// </summary> public bool CanSeeThemOnline { get { return m_canSeeThemOnline; } } /// <summary> /// True if I can see if my friend is on the map /// </summary> public bool CanSeeThemOnMap { get { return m_canSeeThemOnMap; } } /// <summary> /// True if I can modify my friend's objects /// </summary> public bool CanModifyTheirObjects { get { return m_canModifyTheirObjects; } } /// <summary> /// My friend's rights represented as bitmapped flags /// </summary> public FriendRights TheirFriendRights { get { FriendRights results = FriendRights.None; if (m_canSeeMeOnline) results |= FriendRights.CanSeeOnline; if (m_canSeeMeOnMap) results |= FriendRights.CanSeeOnMap; if (m_canModifyMyObjects) results |= FriendRights.CanModifyObjects; return results; } set { m_canSeeMeOnline = (value & FriendRights.CanSeeOnline) != 0; m_canSeeMeOnMap = (value & FriendRights.CanSeeOnMap) != 0; m_canModifyMyObjects = (value & FriendRights.CanModifyObjects) != 0; } } /// <summary> /// My rights represented as bitmapped flags /// </summary> public FriendRights MyFriendRights { get { FriendRights results = FriendRights.None; if (m_canSeeThemOnline) results |= FriendRights.CanSeeOnline; if (m_canSeeThemOnMap) results |= FriendRights.CanSeeOnMap; if (m_canModifyTheirObjects) results |= FriendRights.CanModifyObjects; return results; } set { m_canSeeThemOnline = (value & FriendRights.CanSeeOnline) != 0; m_canSeeThemOnMap = (value & FriendRights.CanSeeOnMap) != 0; m_canModifyTheirObjects = (value & FriendRights.CanModifyObjects) != 0; } } /// <summary> /// FriendInfo represented as a string /// </summary> /// <returns>A string reprentation of both my rights and my friends rights</returns> public override string ToString() { if (!String.IsNullOrEmpty(m_name)) return String.Format("{0} (Their Rights: {1}, My Rights: {2})", m_name, TheirFriendRights, MyFriendRights); else return String.Format("{0} (Their Rights: {1}, My Rights: {2})", m_id, TheirFriendRights, MyFriendRights); } } /// <summary> /// This class is used to add and remove avatars from your friends list and to manage their permission. /// </summary> public class FriendsManager { #region Delegates /// <summary> /// Triggered when an avatar in your friends list comes online /// </summary> /// <param name="friend"> System ID of the avatar</param> public delegate void FriendOnlineEvent(FriendInfo friend); /// <summary> /// Triggered when an avatar in your friends list goes offline /// </summary> /// <param name="friend"> System ID of the avatar</param> public delegate void FriendOfflineEvent(FriendInfo friend); /// <summary> /// Triggered in response to a call to the FriendRights() method, or when a friend changes your rights /// </summary> /// <param name="friend"> System ID of the avatar you changed the right of</param> public delegate void FriendRightsEvent(FriendInfo friend); /// <summary> /// Triggered when someone offers you friendship /// </summary> /// <param name="agentID">System ID of the agent offering friendship</param> /// <param name="agentName">full name of the agent offereing friendship</param> /// <param name="IMSessionID">session ID need when accepting/declining the offer</param> /// <returns>Return true to accept the friendship, false to deny it</returns> public delegate void FriendshipOfferedEvent(LLUUID agentID, string agentName, LLUUID imSessionID); /// <summary> /// Trigger when your friendship offer has been accepted or declined /// </summary> /// <param name="agentID">System ID of the avatar who accepted your friendship offer</param> /// <param name="agentName">Full name of the avatar who accepted your friendship offer</param> /// <param name="accepted">Whether the friendship request was accepted or declined</param> public delegate void FriendshipResponseEvent(LLUUID agentID, string agentName, bool accepted); /// <summary> /// Trigger when someone terminates your friendship. /// </summary> /// <param name="agentID">System ID of the avatar who terminated your friendship</param> /// <param name="agentName">Full name of the avatar who terminated your friendship</param> public delegate void FriendshipTerminatedEvent(LLUUID agentID, string agentName); /// <summary> /// Triggered in response to a FindFriend request /// </summary> /// <param name="agentID">Friends Key</param> /// <param name="regionHandle">region handle friend is in</param> /// <param name="location">X/Y location of friend</param> public delegate void FriendFoundEvent(LLUUID agentID, ulong regionHandle, LLVector3 location); #endregion Delegates #region Events public event FriendOnlineEvent OnFriendOnline; public event FriendOfflineEvent OnFriendOffline; public event FriendRightsEvent OnFriendRights; public event FriendshipOfferedEvent OnFriendshipOffered; public event FriendshipResponseEvent OnFriendshipResponse; public event FriendshipTerminatedEvent OnFriendshipTerminated; public event FriendFoundEvent OnFriendFound; #endregion Events private SecondLife Client; /// <summary> /// A dictionary of key/value pairs containing known friends of this avatar. /// /// The Key is the <seealso cref="LLUUID"/> of the friend, the value is a <seealso cref="FriendInfo"/> /// object that contains detailed information including permissions you have and have given to the friend /// </summary> public InternalDictionary<LLUUID, FriendInfo> FriendList = new InternalDictionary<LLUUID, FriendInfo>(); /// <summary> /// A Dictionary of key/value pairs containing current pending frienship offers. /// /// The key is the <seealso cref="LLUUID"/> of the avatar making the request, /// the value is the <seealso cref="LLUUID"/> of the request which is used to accept /// or decline the friendship offer /// </summary> public InternalDictionary<LLUUID, LLUUID> FriendRequests = new InternalDictionary<LLUUID, LLUUID>(); /// <summary> /// This constructor is intened to only be used by the libsecondlife framework /// </summary> /// <param name="client">A reference to the SecondLife Object</param> public FriendsManager(SecondLife client) { Client = client; Client.Network.OnConnected += new NetworkManager.ConnectedCallback(Network_OnConnect); Client.Avatars.OnAvatarNames += new AvatarManager.AvatarNamesCallback(Avatars_OnAvatarNames); Client.Self.OnInstantMessage += new AgentManager.InstantMessageCallback(MainAvatar_InstantMessage); Client.Network.RegisterCallback(PacketType.OnlineNotification, OnlineNotificationHandler); Client.Network.RegisterCallback(PacketType.OfflineNotification, OfflineNotificationHandler); Client.Network.RegisterCallback(PacketType.ChangeUserRights, ChangeUserRightsHandler); Client.Network.RegisterCallback(PacketType.TerminateFriendship, TerminateFriendshipHandler); Client.Network.RegisterCallback(PacketType.FindAgent, OnFindAgentReplyHandler); Client.Network.RegisterLoginResponseCallback(new NetworkManager.LoginResponseCallback(Network_OnLoginResponse), new string[] { "buddy-list" }); } #region Public Methods /// <summary> /// Accept a friendship request /// </summary> /// <param name="fromAgentID">agentID of avatatar to form friendship with</param> /// <param name="imSessionID">imSessionID of the friendship request message</param> public void AcceptFriendship(LLUUID fromAgentID, LLUUID imSessionID) { LLUUID callingCardFolder = Client.Inventory.FindFolderForType(AssetType.CallingCard); AcceptFriendshipPacket request = new AcceptFriendshipPacket(); request.AgentData.AgentID = Client.Self.AgentID; request.AgentData.SessionID = Client.Self.SessionID; request.TransactionBlock.TransactionID = imSessionID; request.FolderData = new AcceptFriendshipPacket.FolderDataBlock[1]; request.FolderData[0] = new AcceptFriendshipPacket.FolderDataBlock(); request.FolderData[0].FolderID = callingCardFolder; Client.Network.SendPacket(request); FriendInfo friend = new FriendInfo(fromAgentID, FriendRights.CanSeeOnline, FriendRights.CanSeeOnline); lock (FriendList) { if(!FriendList.ContainsKey(fromAgentID)) FriendList.Add(friend.UUID, friend); } lock (FriendRequests) { if (FriendRequests.ContainsKey(fromAgentID)) FriendRequests.Remove(fromAgentID); } Client.Avatars.RequestAvatarName(fromAgentID); } /// <summary> /// Decline a friendship request /// </summary> /// <param name="imSessionID">imSessionID of the friendship request message</param> public void DeclineFriendship(LLUUID fromAgentID, LLUUID imSessionID) { DeclineFriendshipPacket request = new DeclineFriendshipPacket(); request.AgentData.AgentID = Client.Self.AgentID; request.AgentData.SessionID = Client.Self.SessionID; request.TransactionBlock.TransactionID = imSessionID; Client.Network.SendPacket(request); lock (FriendRequests) { if (FriendRequests.ContainsKey(fromAgentID)) FriendRequests.Remove(fromAgentID); } } /// <summary> /// Offer friendship to an avatar. /// </summary> /// <param name="agentID">System ID of the avatar you are offering friendship to</param> public void OfferFriendship(LLUUID agentID) { // HACK: folder id stored as "message" LLUUID callingCardFolder = Client.Inventory.FindFolderForType(AssetType.CallingCard); Client.Self.InstantMessage(Client.Self.Name, agentID, callingCardFolder.ToString(), LLUUID.Random(), InstantMessageDialog.FriendshipOffered, InstantMessageOnline.Online, Client.Self.SimPosition, Client.Network.CurrentSim.ID, new byte[0]); } /// <summary> /// Terminate a friendship with an avatar /// </summary> /// <param name="agentID">System ID of the avatar you are terminating the friendship with</param> public void TerminateFriendship(LLUUID agentID) { if (FriendList.ContainsKey(agentID)) { TerminateFriendshipPacket request = new TerminateFriendshipPacket(); request.AgentData.AgentID = Client.Self.AgentID; request.AgentData.SessionID = Client.Self.SessionID; request.ExBlock.OtherID = agentID; Client.Network.SendPacket(request); lock (FriendList) { if (FriendList.ContainsKey(agentID)) FriendList.Remove(agentID); } } } /// <summary> /// Fired when another friend terminates friendship. We need to remove them from /// our cached list. /// </summary> /// <param name="packet"></param> /// <param name="simulator"></param> private void TerminateFriendshipHandler(Packet packet, Simulator simulator) { TerminateFriendshipPacket itsOver = (TerminateFriendshipPacket)packet; string name = String.Empty; lock (FriendList) { if (FriendList.ContainsKey(itsOver.ExBlock.OtherID)) { name = FriendList[itsOver.ExBlock.OtherID].Name; FriendList.Remove(itsOver.ExBlock.OtherID); } } if (OnFriendshipTerminated != null) { OnFriendshipTerminated(itsOver.ExBlock.OtherID, name); } } /// <summary> /// Change the rights of a friend avatar. /// </summary> /// <param name="friendID">the <seealso cref="LLUUID"/> of the friend</param> /// <param name="rights">the new rights to give the friend</param> /// <remarks>This method will implicitly set the rights to those passed in the rights parameter.</remarks> public void GrantRights(LLUUID friendID, FriendRights rights) { GrantUserRightsPacket request = new GrantUserRightsPacket(); request.AgentData.AgentID = Client.Self.AgentID; request.AgentData.SessionID = Client.Self.SessionID; request.Rights = new GrantUserRightsPacket.RightsBlock[1]; request.Rights[0] = new GrantUserRightsPacket.RightsBlock(); request.Rights[0].AgentRelated = friendID; request.Rights[0].RelatedRights = (int)rights; Client.Network.SendPacket(request); } /// <summary> /// Use to map a friends location on the grid. /// </summary> /// <param name="friendID">Friends UUID to find</param> /// <remarks><seealso cref="E:OnFriendFound"/></remarks> public void MapFriend(LLUUID friendID) { FindAgentPacket stalk = new FindAgentPacket(); stalk.AgentBlock.Hunter = Client.Self.AgentID; stalk.AgentBlock.Prey = friendID; Client.Network.SendPacket(stalk); } /// <summary> /// Use to track a friends movement on the grid /// </summary> /// <param name="friendID">Friends Key</param> public void TrackFriend(LLUUID friendID) { TrackAgentPacket stalk = new TrackAgentPacket(); stalk.AgentData.AgentID = Client.Self.AgentID; stalk.AgentData.SessionID = Client.Self.SessionID; stalk.TargetData.PreyID = friendID; Client.Network.SendPacket(stalk); } #endregion #region Internal events /// <summary> /// Called when a connection to the SL server is established. The list of friend avatars /// is populated from XML returned by the login server. That list contains the avatar's id /// and right, but no names. Here is where those names are requested. /// </summary> /// <param name="sender"></param> private void Network_OnConnect(object sender) { List<LLUUID> names = new List<LLUUID>(); if ( FriendList.Count > 0 ) { lock (FriendList) { foreach (KeyValuePair<LLUUID, FriendInfo> kvp in FriendList.Dictionary) { if (String.IsNullOrEmpty(kvp.Value.Name)) names.Add(kvp.Key); } } Client.Avatars.RequestAvatarNames(names); } } /// <summary> /// This handles the asynchronous response of a RequestAvatarNames call. /// </summary> /// <param name="names">names cooresponding to the the list of IDs sent the the RequestAvatarNames call.</param> private void Avatars_OnAvatarNames(Dictionary<LLUUID, string> names) { lock (FriendList) { foreach (KeyValuePair<LLUUID, string> kvp in names) { if (FriendList.ContainsKey(kvp.Key)) FriendList[kvp.Key].Name = names[kvp.Key]; } } } #endregion #region Packet Handlers /// <summary> /// Handle notifications sent when a friends has come online. /// </summary> /// <param name="packet"></param> /// <param name="simulator"></param> private void OnlineNotificationHandler(Packet packet, Simulator simulator) { if (packet.Type == PacketType.OnlineNotification) { OnlineNotificationPacket notification = ((OnlineNotificationPacket)packet); foreach (OnlineNotificationPacket.AgentBlockBlock block in notification.AgentBlock) { FriendInfo friend; lock (FriendList) { if (!FriendList.ContainsKey(block.AgentID)) { friend = new FriendInfo(block.AgentID, FriendRights.CanSeeOnline, FriendRights.CanSeeOnline); FriendList.Add(block.AgentID, friend); } else { friend = FriendList[block.AgentID]; } } bool doNotify = !friend.IsOnline; friend.IsOnline = true; if (OnFriendOnline != null && doNotify) { try { OnFriendOnline(friend); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } } } /// <summary> /// Handle notifications sent when a friends has gone offline. /// </summary> /// <param name="packet"></param> /// <param name="simulator"></param> private void OfflineNotificationHandler(Packet packet, Simulator simulator) { if (packet.Type == PacketType.OfflineNotification) { OfflineNotificationPacket notification = ((OfflineNotificationPacket)packet); foreach (OfflineNotificationPacket.AgentBlockBlock block in notification.AgentBlock) { FriendInfo friend; lock (FriendList) { if (!FriendList.ContainsKey(block.AgentID)) FriendList.Add(block.AgentID, new FriendInfo(block.AgentID, FriendRights.CanSeeOnline, FriendRights.CanSeeOnline)); friend = FriendList[block.AgentID]; friend.IsOnline = false; } if (OnFriendOffline != null) { try { OnFriendOffline(friend); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } } } /// <summary> /// Handle notifications sent when a friend rights change. This notification is also received /// when my own rights change. /// </summary> /// <param name="packet"></param> /// <param name="simulator"></param> private void ChangeUserRightsHandler(Packet packet, Simulator simulator) { if (packet.Type == PacketType.ChangeUserRights) { FriendInfo friend; ChangeUserRightsPacket rights = (ChangeUserRightsPacket)packet; foreach (ChangeUserRightsPacket.RightsBlock block in rights.Rights) { FriendRights newRights = (FriendRights)block.RelatedRights; if (FriendList.TryGetValue(block.AgentRelated, out friend)) { friend.TheirFriendRights = newRights; if (OnFriendRights != null) { try { OnFriendRights(friend); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } else if (block.AgentRelated == Client.Self.AgentID) { if (FriendList.TryGetValue(rights.AgentData.AgentID, out friend)) { friend.MyFriendRights = newRights; if (OnFriendRights != null) { try { OnFriendRights(friend); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } } } } } /// <summary> /// Handle friend location updates /// </summary> /// <param name="packet">The Packet</param> /// <param name="simulator">The Simulator</param> public void OnFindAgentReplyHandler(Packet packet, Simulator simulator) { if(OnFriendFound != null) { FindAgentPacket reply = (FindAgentPacket)packet; float x,y; LLUUID prey = reply.AgentBlock.Prey; ulong regionHandle = Helpers.GlobalPosToRegionHandle((float)reply.LocationBlock[0].GlobalX, (float)reply.LocationBlock[0].GlobalY, out x, out y); LLVector3 xyz = new LLVector3(x, y, 0f); try { OnFriendFound(prey, regionHandle, xyz); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } #endregion /// <summary> /// Handles relevant messages from the server encapsulated in instant messages. /// </summary> /// <param name="im">InstantMessage object containing encapsalated instant message</param> /// <param name="simulator">Originating Simulator</param> private void MainAvatar_InstantMessage(InstantMessage im, Simulator simulator) { if (im.Dialog == InstantMessageDialog.FriendshipOffered) { if (OnFriendshipOffered != null) { lock (FriendRequests) { if (FriendRequests.ContainsKey(im.FromAgentID)) FriendRequests[im.FromAgentID] = im.IMSessionID; else FriendRequests.Add(im.FromAgentID, im.IMSessionID); } try { OnFriendshipOffered(im.FromAgentID, im.FromAgentName, im.IMSessionID); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } else if (im.Dialog == InstantMessageDialog.FriendshipAccepted) { FriendInfo friend = new FriendInfo(im.FromAgentID, FriendRights.CanSeeOnline, FriendRights.CanSeeOnline); friend.Name = im.FromAgentName; lock (FriendList) FriendList[friend.UUID] = friend; if (OnFriendshipResponse != null) { try { OnFriendshipResponse(im.FromAgentID, im.FromAgentName, true); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } else if (im.Dialog == InstantMessageDialog.FriendshipDeclined) { if (OnFriendshipResponse != null) { try { OnFriendshipResponse(im.FromAgentID, im.FromAgentName, false); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } } private void Network_OnLoginResponse(bool loginSuccess, bool redirect, string message, string reason, LoginResponseData replyData) { if (loginSuccess && replyData.BuddyList != null) { lock (FriendList) { for (int i = 0; i < replyData.BuddyList.Length; i++) { FriendInfo friend = replyData.BuddyList[i]; FriendList[friend.UUID] = friend; } } } } } }
// 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.Xml; using System.Xml.Schema; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Diagnostics; namespace System.Runtime.Serialization { public class XsdDataContractExporter { private ExportOptions _options; private XmlSchemaSet _schemas; private DataContractSet _dataContractSet; public XsdDataContractExporter() { } public XsdDataContractExporter(XmlSchemaSet schemas) { this._schemas = schemas; } public ExportOptions Options { get { return _options; } set { _options = value; } } public XmlSchemaSet Schemas { get { throw new PlatformNotSupportedException(SR.PlatformNotSupported_SchemaImporter); } } private XmlSchemaSet GetSchemaSet() { if (_schemas == null) { _schemas = new XmlSchemaSet(); _schemas.XmlResolver = null; } return _schemas; } private DataContractSet DataContractSet { get { // On full framework , we set _dataContractSet = Options.GetSurrogate()); // But Options.GetSurrogate() is not available on NetCore because IDataContractSurrogate // is not in NetStandard. throw new PlatformNotSupportedException(SR.PlatformNotSupported_IDataContractSurrogate); } } private void TraceExportBegin() { } private void TraceExportEnd() { } private void TraceExportError(Exception exception) { } public void Export(ICollection<Assembly> assemblies) { if (assemblies == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(assemblies))); TraceExportBegin(); DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { foreach (Assembly assembly in assemblies) { if (assembly == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullAssembly, nameof(assemblies)))); Type[] types = assembly.GetTypes(); for (int j = 0; j < types.Length; j++) CheckAndAddType(types[j]); } Export(); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } _dataContractSet = oldValue; TraceExportError(ex); throw; } TraceExportEnd(); } public void Export(ICollection<Type> types) { if (types == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(types))); TraceExportBegin(); DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { foreach (Type type in types) { if (type == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullType, nameof(types)))); AddType(type); } Export(); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } _dataContractSet = oldValue; TraceExportError(ex); throw; } TraceExportEnd(); } public void Export(Type type) { if (type == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); TraceExportBegin(); DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { AddType(type); Export(); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } _dataContractSet = oldValue; TraceExportError(ex); throw; } TraceExportEnd(); } public XmlQualifiedName GetSchemaTypeName(Type type) { if (type == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); type = GetSurrogatedType(type); DataContract dataContract = DataContract.GetDataContract(type); DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType); XmlDataContract xmlDataContract = dataContract as XmlDataContract; if (xmlDataContract != null && xmlDataContract.IsAnonymous) return XmlQualifiedName.Empty; return dataContract.StableName; } public XmlSchemaType GetSchemaType(Type type) { if (type == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); type = GetSurrogatedType(type); DataContract dataContract = DataContract.GetDataContract(type); DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType); XmlDataContract xmlDataContract = dataContract as XmlDataContract; if (xmlDataContract != null && xmlDataContract.IsAnonymous) return xmlDataContract.XsdType; return null; } public XmlQualifiedName GetRootElementName(Type type) { if (type == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); type = GetSurrogatedType(type); DataContract dataContract = DataContract.GetDataContract(type); DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType); if (dataContract.HasRoot) { return new XmlQualifiedName(dataContract.TopLevelElementName.Value, dataContract.TopLevelElementNamespace.Value); } else { return null; } } private Type GetSurrogatedType(Type type) { #if SUPPORT_SURROGATE IDataContractSurrogate dataContractSurrogate; if (options != null && (dataContractSurrogate = Options.GetSurrogate()) != null) type = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, type); #endif return type; } private void CheckAndAddType(Type type) { type = GetSurrogatedType(type); if (!type.ContainsGenericParameters && DataContract.IsTypeSerializable(type)) AddType(type); } private void AddType(Type type) { DataContractSet.Add(type); } private void Export() { AddKnownTypes(); SchemaExporter schemaExporter = new SchemaExporter(GetSchemaSet(), DataContractSet); schemaExporter.Export(); } private void AddKnownTypes() { if (Options != null) { Collection<Type> knownTypes = Options.KnownTypes; if (knownTypes != null) { for (int i = 0; i < knownTypes.Count; i++) { Type type = knownTypes[i]; if (type == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.CannotExportNullKnownType)); AddType(type); } } } } public bool CanExport(ICollection<Assembly> assemblies) { if (assemblies == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(assemblies))); DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { foreach (Assembly assembly in assemblies) { if (assembly == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullAssembly, nameof(assemblies)))); Type[] types = assembly.GetTypes(); for (int j = 0; j < types.Length; j++) CheckAndAddType(types[j]); } AddKnownTypes(); return true; } catch (InvalidDataContractException) { _dataContractSet = oldValue; return false; } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } _dataContractSet = oldValue; TraceExportError(ex); throw; } } public bool CanExport(ICollection<Type> types) { if (types == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(types))); DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { foreach (Type type in types) { if (type == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullType, nameof(types)))); AddType(type); } AddKnownTypes(); return true; } catch (InvalidDataContractException) { _dataContractSet = oldValue; return false; } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } _dataContractSet = oldValue; TraceExportError(ex); throw; } } public bool CanExport(Type type) { if (type == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { AddType(type); AddKnownTypes(); return true; } catch (InvalidDataContractException) { _dataContractSet = oldValue; return false; } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } _dataContractSet = oldValue; TraceExportError(ex); throw; } } #if USE_REFEMIT //Returns warnings public IList<string> GenerateCode(IList<Assembly> assemblies) { if (assemblies == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(assemblies))); List<string> warnings = new List<string>(); DataContractSet oldValue = (dataContractSet == null) ? null : new DataContractSet(dataContractSet); try { for (int i=0; i < assemblies.Count; i++) { Assembly assembly = assemblies[i]; if (assembly == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullAssembly, "assemblies"))); Type[] types = assembly.GetTypes(); for (int j=0; j < types.Length; j++) { try { CheckAndAddType(types[j]); } catch (Exception ex) { warnings.Add("Error on exporting Type " + DataContract.GetClrTypeFullName(types[j]) + ". " + ex.Message); } } } foreach (KeyValuePair<XmlQualifiedName, DataContract> pair in dataContractSet) { DataContract dataContract = pair.Value; if (dataContract is ClassDataContract) { try { XmlFormatClassWriterDelegate writerMethod = ((ClassDataContract)dataContract).XmlFormatWriterDelegate; XmlFormatClassReaderDelegate readerMethod = ((ClassDataContract)dataContract).XmlFormatReaderDelegate; } catch (Exception ex) { warnings.Add("Error on exporting Type " + dataContract.UnderlyingType + ". " + ex.Message); } } else if (dataContract is CollectionDataContract) { try { XmlFormatCollectionWriterDelegate writerMethod = ((CollectionDataContract)dataContract).XmlFormatWriterDelegate; XmlFormatCollectionReaderDelegate readerMethod = ((CollectionDataContract)dataContract).XmlFormatReaderDelegate; } catch (Exception ex) { warnings.Add("Error on exporting Type " + dataContract.UnderlyingType + ". " + ex.Message); } } } return warnings; } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } dataContractSet = oldValue; TraceExportError(ex); throw; } } #endif } }
using JenkinsConsoleUtility.Util; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace JenkinsConsoleUtility.jcuSrc.Commands { class GetAdoBuilds : ICommand { private const string expectedFolderPrefix = "\\PlayFabSdk"; private const string pipelinesUrl = "https://dev.azure.com/PlayFabInternal/Main/_apis/pipelines"; private const string buildsUrl = "https://dev.azure.com/PlayFabInternal/Main/_apis/build/builds?definitions={definitionId}"; // public static readonly List<string> filterIds = new List<string> { "refs/heads/master", "refs/heads/develop" }; private static readonly string[] MyCommandKeys = { "getbuilds", "builds", "adobuilds" }; public string[] CommandKeys { get { return MyCommandKeys; } } private static readonly string[] MyMandatoryArgKeys = { "kustoConfig", "pat" }; public string[] MandatoryArgKeys { get { return MyMandatoryArgKeys; } } private int days; private string pat; private KustoWriter kustoWriter; public int Execute(Dictionary<string, string> argsLc, Dictionary<string, string> argsCased) { Task<int> execTask = Task.Run(async () => { return await ExecuteAsync(argsLc, argsCased); }); return execTask.Result; } private async Task<int> ExecuteAsync(Dictionary<string, string> argsLc, Dictionary<string, string> argsCased) { List<AdoBuildResultRow> rows = new List<AdoBuildResultRow>(); string daysStr; if (!JenkinsConsoleUtility.TryGetArgVar(out daysStr, argsLc, "days") || !int.TryParse(daysStr, out days)) days = 3; pat = JenkinsConsoleUtility.GetArgVar(argsLc, "pat"); string kustoConfigFile = JenkinsConsoleUtility.GetArgVar(argsLc, "kustoConfig"); if (!File.Exists(kustoConfigFile)) throw new ArgumentException("kustoConfig file does not exist."); string kustoConfigJson = File.ReadAllText(kustoConfigFile); KustoConfig kustoConfig = JsonConvert.DeserializeObject<KustoConfig>(kustoConfigJson); kustoWriter = new KustoWriter(kustoConfig); GetPipelinesResult pipelines = await MakeAdoApiCall<GetPipelinesResult>(pipelinesUrl, "pipelines.json"); if (!FilterPipelines(pipelines.value)) { JcuUtil.FancyWriteToConsole(ConsoleColor.Red, "No pipelines found in expected folder: " + expectedFolderPrefix); return 1; } int buildsWritten = 0; foreach (var eachPipeline in pipelines.value) { GetBuildsResult builds = await MakeAdoApiCall<GetBuildsResult>(buildsUrl.Replace("{definitionId}", eachPipeline.id.ToString()), "builds" + eachPipeline.id +".json"); var buildReports = ProcessBuildList(builds.value); foreach (var eachReportPair in buildReports) { JcuUtil.FancyWriteToConsole(ConsoleColor.DarkCyan, eachReportPair.Value.name); foreach (var eachDailyResultPair in eachReportPair.Value.dailyResults) { if (eachDailyResultPair.Key > days) continue; // Skip the old tests DateTime date; int passed, failed, others, total; BuildReport.Count(eachDailyResultPair.Value, out date, out passed, out failed, out others, out total); JcuUtil.FancyWriteToConsole( ConsoleColor.White, eachDailyResultPair.Key, " days ago(", date, "): (", ConsoleColor.Green, "P: ", passed, ConsoleColor.White, "/", ConsoleColor.Red, "F:", failed, ConsoleColor.White, "/", ConsoleColor.DarkYellow, "O:", others, ConsoleColor.White, "/", ConsoleColor.Cyan, "T:", total, ConsoleColor.White, ")"); rows.Add(new AdoBuildResultRow(eachReportPair.Value.name, passed, failed, others, total, date)); } } buildsWritten += builds.value.Count; } bool success = kustoWriter.WriteDataForTable(false, rows); return success && buildsWritten > 0 ? 0 : 1; } private async Task<T> MakeAdoApiCall<T>(string adoUrl, string cacheFileName) where T : class { string jsonResult = null; try { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var b64pat = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", pat))); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", b64pat); using (HttpResponseMessage response = client.GetAsync(adoUrl).Result) { response.EnsureSuccessStatusCode(); jsonResult = await response.Content.ReadAsStringAsync(); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); return null; } var deserializedObj = JsonConvert.DeserializeObject<T>(jsonResult); if (!string.IsNullOrEmpty(cacheFileName)) { var tabbedJson = JsonConvert.SerializeObject(deserializedObj, Formatting.Indented); File.WriteAllText(cacheFileName, tabbedJson); } return deserializedObj; } // Filters in-place, modifying the list that is provided public bool FilterPipelines(List<Pipeline> pipelines) { // Remove any pipelines that don't start with the expected prefix for (int i = pipelines.Count - 1; i >= 0; i--) if (!pipelines[i].folder.StartsWith(expectedFolderPrefix)) pipelines.RemoveAt(i); return pipelines.Count > 0; } public Dictionary<int, BuildReport> ProcessBuildList(List<BuildResult> allBuilds) { Dictionary<int, BuildReport> reports = new Dictionary<int, BuildReport>(); var now = DateTime.UtcNow; var today = new DateTime(now.Year, now.Month, now.Day); foreach (var eachBuild in allBuilds) { BuildReport eachReport; if (!reports.TryGetValue(eachBuild.definition.id, out eachReport)) reports[eachBuild.definition.id] = eachReport = new BuildReport(eachBuild.definition.id, eachBuild.definition.name); int daysOld = (today - new DateTime(eachBuild.finishTime.Year, eachBuild.finishTime.Month, eachBuild.finishTime.Day)).Days; eachReport.Add(daysOld, eachBuild); } return reports; } } class BuildReport { public readonly int id; public readonly string name; public Dictionary<int, List<BuildResult>> dailyResults = new Dictionary<int, List<BuildResult>>(); public BuildReport(int id, string name) { this.id = id; this.name = name; } public void Add(int daysOld, BuildResult result) { List<BuildResult> bucket; if (!dailyResults.TryGetValue(daysOld, out bucket)) dailyResults[daysOld] = bucket = new List<BuildResult>(); bucket.Add(result); } public static void Count(List<BuildResult> results, out DateTime date, out int passed, out int failed, out int others, out int total) { passed = failed = others = total = 0; date = DateTime.MinValue; foreach (var eachResult in results) { date = new DateTime(eachResult.finishTime.Year, eachResult.finishTime.Month, eachResult.finishTime.Day); switch (eachResult.result) { case "succeeded": passed++; total++; break; case "failed": failed++; total++; break; case "canceled": others++; total++; break; default: others++; total++; Console.WriteLine(" --- Unexpected Build Result: " + eachResult.result); break; } } } } #pragma warning disable 0649 // All these are json-assigned class GetPipelinesResult { public int count; public List<Pipeline> value; } class Pipeline { public int id; public string name; public string folder; } class GetBuildsResult { public int count; public List<BuildResult> value; } class BuildResult { public int id; public string buildNumber; public string status; public string result; public DateTime finishTime; public string sourceBranch; public BuildDefn definition; public BuildRepository repository; public override string ToString() { return $"({id}): {result} at {finishTime}: {repository.name} from {sourceBranch} ({definition.id})"; } } class BuildDefn { public int id; public string name; } class BuildRepository { public string type; public string name; public string url; } #pragma warning restore 0649 }
// 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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBIteratorTests : CSharpPDBTestBase { [WorkItem(543376, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543376")] [Fact] public void SimpleIterator1() { var text = @" class Program { System.Collections.Generic.IEnumerable<int> Foo() { yield break; } } "; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <methods> <method containingType=""Program"" name=""Foo""> <customDebugInfo> <forwardIterator name=""&lt;Foo&gt;d__0"" /> </customDebugInfo> </method> <method containingType=""Program+&lt;Foo&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x17"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" /> <entry offset=""0x18"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(543376, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543376")] [Fact] public void SimpleIterator2() { var text = @" class Program { System.Collections.Generic.IEnumerable<int> Foo() { yield break; } } "; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <methods> <method containingType=""Program"" name=""Foo""> <customDebugInfo> <forwardIterator name=""&lt;Foo&gt;d__0"" /> </customDebugInfo> </method> <method containingType=""Program+&lt;Foo&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x17"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" /> <entry offset=""0x18"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(543490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543490")] [Fact] public void SimpleIterator3() { var text = @" class Program { System.Collections.Generic.IEnumerable<int> Foo() { yield return 1; //hidden sequence point after this. } } "; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <methods> <method containingType=""Program"" name=""Foo""> <customDebugInfo> <forwardIterator name=""&lt;Foo&gt;d__0"" /> </customDebugInfo> </method> <method containingType=""Program+&lt;Foo&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x1f"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" /> <entry offset=""0x20"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""24"" /> <entry offset=""0x30"" hidden=""true"" /> <entry offset=""0x37"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void IteratorWithLocals_ReleasePdb() { var text = @" class Program { System.Collections.Generic.IEnumerable<int> IEI<T>(int i0, int i1) { int x = i0; yield return x; yield return x; { int y = i1; yield return y; yield return y; } yield break; } } "; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.ReleaseDll); c.VerifyPdb(@" <symbols> <methods> <method containingType=""Program"" name=""IEI"" parameterNames=""i0, i1""> <customDebugInfo> <forwardIterator name=""&lt;IEI&gt;d__0"" /> </customDebugInfo> </method> <method containingType=""Program+&lt;IEI&gt;d__0`1"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x2a"" endOffset=""0xb3"" /> <slot startOffset=""0x6e"" endOffset=""0xb1"" /> </hoistedLocalScopes> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x2a"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""20"" /> <entry offset=""0x36"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" /> <entry offset=""0x4b"" hidden=""true"" /> <entry offset=""0x52"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" /> <entry offset=""0x67"" hidden=""true"" /> <entry offset=""0x6e"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""24"" /> <entry offset=""0x7a"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" /> <entry offset=""0x8f"" hidden=""true"" /> <entry offset=""0x96"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""28"" /> <entry offset=""0xab"" hidden=""true"" /> <entry offset=""0xb2"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""21"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void IteratorWithLocals_DebugPdb() { var text = @" class Program { System.Collections.Generic.IEnumerable<int> IEI<T>(int i0, int i1) { int x = i0; yield return x; yield return x; { int y = i1; yield return y; yield return y; } yield break; } } "; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <methods> <method containingType=""Program"" name=""IEI"" parameterNames=""i0, i1""> <customDebugInfo> <forwardIterator name=""&lt;IEI&gt;d__0"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""101"" /> </encLocalSlotMap> </customDebugInfo> </method> <method containingType=""Program+&lt;IEI&gt;d__0`1"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x39"" endOffset=""0xc5"" /> <slot startOffset=""0x7e"" endOffset=""0xc3"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x39"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" /> <entry offset=""0x3a"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""20"" /> <entry offset=""0x46"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" /> <entry offset=""0x5b"" hidden=""true"" /> <entry offset=""0x62"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" /> <entry offset=""0x77"" hidden=""true"" /> <entry offset=""0x7e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" /> <entry offset=""0x7f"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""24"" /> <entry offset=""0x8b"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" /> <entry offset=""0xa0"" hidden=""true"" /> <entry offset=""0xa7"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""28"" /> <entry offset=""0xbc"" hidden=""true"" /> <entry offset=""0xc3"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" /> <entry offset=""0xc4"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""21"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void IteratorWithCapturedSyntheticVariables() { // this iterator captures the synthetic variable generated from the expansion of the foreach loop var text = @"// Based on LegacyTest csharp\Source\Conformance\iterators\blocks\using001.cs using System; using System.Collections.Generic; class Test<T> { public static IEnumerator<T> M(IEnumerable<T> items) { T val = default(T); foreach (T item in items) { val = item; yield return val; } yield return val; } }"; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <methods> <method containingType=""Test`1"" name=""M"" parameterNames=""items""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""5"" offset=""42"" /> <slot kind=""0"" offset=""42"" /> </encLocalSlotMap> </customDebugInfo> </method> <method containingType=""Test`1+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x32"" endOffset=""0xe1"" /> <slot startOffset=""0x0"" endOffset=""0x0"" /> <slot startOffset=""0x5b"" endOffset=""0xa4"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""temp"" /> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x32"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" /> <entry offset=""0x33"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""28"" /> <entry offset=""0x3f"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""16"" /> <entry offset=""0x40"" startLine=""11"" startColumn=""28"" endLine=""11"" endColumn=""33"" /> <entry offset=""0x59"" hidden=""true"" /> <entry offset=""0x5b"" startLine=""11"" startColumn=""18"" endLine=""11"" endColumn=""24"" /> <entry offset=""0x6c"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" /> <entry offset=""0x6d"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""24"" /> <entry offset=""0x79"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""30"" /> <entry offset=""0x90"" hidden=""true"" /> <entry offset=""0x98"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" /> <entry offset=""0xa5"" startLine=""11"" startColumn=""25"" endLine=""11"" endColumn=""27"" /> <entry offset=""0xc0"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""26"" /> <entry offset=""0xd7"" hidden=""true"" /> <entry offset=""0xde"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" /> <entry offset=""0xe2"" hidden=""true"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xec""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(542705, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542705"), WorkItem(528790, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528790"), WorkItem(543490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543490")] [Fact()] public void IteratorBackToNextStatementAfterYieldReturn() { var text = @" using System.Collections.Generic; class C { IEnumerable<decimal> M() { const decimal d1 = 0.1M; yield return d1; const decimal dx = 1.23m; yield return dx; { const decimal d2 = 0.2M; yield return d2; } yield break; } static void Main() { foreach (var i in new C().M()) { System.Console.WriteLine(i); } } } "; using (new CultureContext("en-US")) { var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.ReleaseExe); c.VerifyPdb(@" <symbols> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> </customDebugInfo> </method> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""21"" startColumn=""27"" endLine=""21"" endColumn=""38"" /> <entry offset=""0x10"" hidden=""true"" /> <entry offset=""0x12"" startLine=""21"" startColumn=""18"" endLine=""21"" endColumn=""23"" /> <entry offset=""0x18"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""41"" /> <entry offset=""0x1d"" startLine=""21"" startColumn=""24"" endLine=""21"" endColumn=""26"" /> <entry offset=""0x27"" hidden=""true"" /> <entry offset=""0x31"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x32""> <namespace name=""System.Collections.Generic"" /> </scope> </method> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x26"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" /> <entry offset=""0x3f"" hidden=""true"" /> <entry offset=""0x46"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""25"" /> <entry offset=""0x60"" hidden=""true"" /> <entry offset=""0x67"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""29"" /> <entry offset=""0x80"" hidden=""true"" /> <entry offset=""0x87"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""21"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x89""> <scope startOffset=""0x26"" endOffset=""0x89""> <constant name=""d1"" value=""0.1"" type=""Decimal"" /> <constant name=""dx"" value=""1.23"" type=""Decimal"" /> <scope startOffset=""0x67"" endOffset=""0x87""> <constant name=""d2"" value=""0.2"" type=""Decimal"" /> </scope> </scope> </scope> </method> </methods> </symbols>"); } } [WorkItem(543490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543490")] [Fact()] public void IteratorMultipleEnumerables() { var text = @" using System; using System.Collections; using System.Collections.Generic; public class Test<T> : IEnumerable<T> where T : class { System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<T> GetEnumerator() { foreach (var v in this.IterProp) { yield return v; } foreach (var v in IterMethod()) { yield return v; } } public IEnumerable<T> IterProp { get { yield return null; yield return null; } } public IEnumerable<T> IterMethod() { yield return default(T); yield return null; yield break; } } public class Test { public static void Main() { foreach (var v in new Test<string>()) { } } } "; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugExe); c.VerifyPdb(@" <symbols> <entryPoint declaringType=""Test"" methodName=""Main"" /> <methods> <method containingType=""Test`1"" name=""System.Collections.IEnumerable.GetEnumerator""> <customDebugInfo> <using> <namespace usingCount=""3"" /> </using> <encLocalSlotMap> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""32"" /> <entry offset=""0xa"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xc""> <namespace name=""System"" /> <namespace name=""System.Collections"" /> <namespace name=""System.Collections.Generic"" /> </scope> </method> <method containingType=""Test`1"" name=""GetEnumerator""> <customDebugInfo> <forwardIterator name=""&lt;GetEnumerator&gt;d__1"" /> <encLocalSlotMap> <slot kind=""5"" offset=""11"" /> <slot kind=""0"" offset=""11"" /> <slot kind=""5"" offset=""104"" /> <slot kind=""0"" offset=""104"" /> </encLocalSlotMap> </customDebugInfo> </method> <method containingType=""Test`1"" name=""get_IterProp""> <customDebugInfo> <forwardIterator name=""&lt;get_IterProp&gt;d__3"" /> </customDebugInfo> </method> <method containingType=""Test`1"" name=""IterMethod""> <customDebugInfo> <forwardIterator name=""&lt;IterMethod&gt;d__4"" /> </customDebugInfo> </method> <method containingType=""Test"" name=""Main""> <customDebugInfo> <forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" /> <encLocalSlotMap> <slot kind=""5"" offset=""11"" /> <slot kind=""0"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""45"" startColumn=""5"" endLine=""45"" endColumn=""6"" /> <entry offset=""0x1"" startLine=""46"" startColumn=""9"" endLine=""46"" endColumn=""16"" /> <entry offset=""0x2"" startLine=""46"" startColumn=""27"" endLine=""46"" endColumn=""45"" /> <entry offset=""0xd"" hidden=""true"" /> <entry offset=""0xf"" startLine=""46"" startColumn=""18"" endLine=""46"" endColumn=""23"" /> <entry offset=""0x16"" startLine=""46"" startColumn=""47"" endLine=""46"" endColumn=""48"" /> <entry offset=""0x17"" startLine=""46"" startColumn=""49"" endLine=""46"" endColumn=""50"" /> <entry offset=""0x18"" startLine=""46"" startColumn=""24"" endLine=""46"" endColumn=""26"" /> <entry offset=""0x22"" hidden=""true"" /> <entry offset=""0x2d"" startLine=""47"" startColumn=""5"" endLine=""47"" endColumn=""6"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2e""> <scope startOffset=""0xf"" endOffset=""0x18""> <local name=""v"" il_index=""1"" il_start=""0xf"" il_end=""0x18"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""Test`1+&lt;GetEnumerator&gt;d__1"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" /> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x0"" /> <slot startOffset=""0x54"" endOffset=""0x94"" /> <slot startOffset=""0x0"" endOffset=""0x0"" /> <slot startOffset=""0xd1"" endOffset=""0x10e"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""temp"" /> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x32"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" /> <entry offset=""0x33"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""16"" /> <entry offset=""0x34"" startLine=""15"" startColumn=""27"" endLine=""15"" endColumn=""40"" /> <entry offset=""0x52"" hidden=""true"" /> <entry offset=""0x54"" startLine=""15"" startColumn=""18"" endLine=""15"" endColumn=""23"" /> <entry offset=""0x65"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" /> <entry offset=""0x66"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""28"" /> <entry offset=""0x80"" hidden=""true"" /> <entry offset=""0x88"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" /> <entry offset=""0x95"" startLine=""15"" startColumn=""24"" endLine=""15"" endColumn=""26"" /> <entry offset=""0xb0"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""16"" /> <entry offset=""0xb1"" startLine=""19"" startColumn=""27"" endLine=""19"" endColumn=""39"" /> <entry offset=""0xcf"" hidden=""true"" /> <entry offset=""0xd1"" startLine=""19"" startColumn=""18"" endLine=""19"" endColumn=""23"" /> <entry offset=""0xe2"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""10"" /> <entry offset=""0xe3"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""28"" /> <entry offset=""0xfa"" hidden=""true"" /> <entry offset=""0x102"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" /> <entry offset=""0x10f"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""26"" /> <entry offset=""0x12a"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" /> <entry offset=""0x12e"" hidden=""true"" /> </sequencePoints> </method> <method containingType=""Test`1+&lt;get_IterProp&gt;d__3"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" /> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x2a"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" /> <entry offset=""0x2b"" startLine=""29"" startColumn=""13"" endLine=""29"" endColumn=""31"" /> <entry offset=""0x40"" hidden=""true"" /> <entry offset=""0x47"" startLine=""30"" startColumn=""13"" endLine=""30"" endColumn=""31"" /> <entry offset=""0x5c"" hidden=""true"" /> <entry offset=""0x63"" startLine=""31"" startColumn=""9"" endLine=""31"" endColumn=""10"" /> </sequencePoints> </method> <method containingType=""Test`1+&lt;IterMethod&gt;d__4"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" /> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x2a"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" /> <entry offset=""0x2b"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""33"" /> <entry offset=""0x40"" hidden=""true"" /> <entry offset=""0x47"" startLine=""37"" startColumn=""9"" endLine=""37"" endColumn=""27"" /> <entry offset=""0x5c"" hidden=""true"" /> <entry offset=""0x63"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""21"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void VariablesWithSubstitutedType1() { var text = @" using System.Collections.Generic; class C { static IEnumerable<T> F<T>(T[] o) { int i = 0; T t = default(T); yield return t; yield return o[i]; } } "; var v = CompileAndVerify(text, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "o", "<>3__o", "<i>5__1", "<t>5__2" }, module.GetFieldNames("C.<F>d__0")); }); v.VerifyPdb("C+<F>d__0`1.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;F&gt;d__0`1"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x2a"" endOffset=""0x82"" /> <slot startOffset=""0x2a"" endOffset=""0x82"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x2a"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" /> <entry offset=""0x2b"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" /> <entry offset=""0x32"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" /> <entry offset=""0x3e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" /> <entry offset=""0x53"" hidden=""true"" /> <entry offset=""0x5a"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""27"" /> <entry offset=""0x7a"" hidden=""true"" /> <entry offset=""0x81"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x83""> <namespace name=""System.Collections.Generic"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void IteratorWithConditionalBranchDiscriminator1() { var text = @" using System.Collections.Generic; class C { static bool B() => false; static IEnumerable<int> F() { if (B()) { yield return 1; } } } "; // Note that conditional branch discriminator is not hoisted. var v = CompileAndVerify(text, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", }, module.GetFieldNames("C.<F>d__1")); }); v.VerifyIL("C.<F>d__1.System.Collections.IEnumerator.MoveNext", @" { // Code size 68 (0x44) .maxstack 2 .locals init (int V_0, bool V_1) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__1.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003a IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__1.<>1__state"" IL_001f: nop IL_0020: call ""bool C.B()"" IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: brfalse.s IL_0042 IL_0029: nop IL_002a: ldarg.0 IL_002b: ldc.i4.1 IL_002c: stfld ""int C.<F>d__1.<>2__current"" IL_0031: ldarg.0 IL_0032: ldc.i4.1 IL_0033: stfld ""int C.<F>d__1.<>1__state"" IL_0038: ldc.i4.1 IL_0039: ret IL_003a: ldarg.0 IL_003b: ldc.i4.m1 IL_003c: stfld ""int C.<F>d__1.<>1__state"" IL_0041: nop IL_0042: ldc.i4.0 IL_0043: ret } "); v.VerifyPdb("C+<F>d__1.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;F&gt;d__1"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C"" methodName=""B"" /> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x1f"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" /> <entry offset=""0x20"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""17"" /> <entry offset=""0x26"" hidden=""true"" /> <entry offset=""0x29"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" /> <entry offset=""0x2a"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" /> <entry offset=""0x3a"" hidden=""true"" /> <entry offset=""0x41"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" /> <entry offset=""0x42"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void SynthesizedVariables1() { var source = @" using System; using System.Collections.Generic; class C { public IEnumerable<int> M(IDisposable disposable) { foreach (var item in new[] { 1, 2, 3 }) { lock (this) { yield return 1; } } foreach (var item in new[] { 1, 2, 3 }) { } lock (this) { yield return 2; } if (disposable != null) { using (disposable) { yield return 3; } } lock (this) { yield return 4; } if (disposable != null) { using (disposable) { } } lock (this) { } } }"; CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { AssertEx.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "<>4__this", "disposable", "<>3__disposable", "<>7__wrap1", "<>7__wrap2", "<>7__wrap3", "<>7__wrap4", "<>7__wrap5", }, module.GetFieldNames("C.<M>d__0")); }); var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { AssertEx.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "disposable", "<>3__disposable", "<>4__this", "<>s__1", "<>s__2", "<item>5__3", "<>s__4", "<>s__5", "<>s__6", "<>s__7", "<item>5__8", "<>s__9", "<>s__10", "<>s__11", "<>s__12", "<>s__13", "<>s__14", "<>s__15", "<>s__16" }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M"" parameterNames=""disposable""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLocalSlotMap> <slot kind=""6"" offset=""11"" /> <slot kind=""8"" offset=""11"" /> <slot kind=""0"" offset=""11"" /> <slot kind=""3"" offset=""53"" /> <slot kind=""2"" offset=""53"" /> <slot kind=""6"" offset=""96"" /> <slot kind=""8"" offset=""96"" /> <slot kind=""0"" offset=""96"" /> <slot kind=""3"" offset=""149"" /> <slot kind=""2"" offset=""149"" /> <slot kind=""4"" offset=""216"" /> <slot kind=""3"" offset=""266"" /> <slot kind=""2"" offset=""266"" /> <slot kind=""4"" offset=""333"" /> <slot kind=""3"" offset=""367"" /> <slot kind=""2"" offset=""367"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols>"); } [WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")] [WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")] [Fact] public void DisplayClass_AcrossSuspensionPoints_Debug() { string source = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> M() { byte x1 = 1; byte x2 = 1; byte x3 = 1; ((Action)(() => { x1 = x2 = x3; }))(); yield return x1 + x2 + x3; yield return x1 + x2 + x3; } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "<>8__1", // hoisted display class }, module.GetFieldNames("C.<M>d__0")); }); // One iterator local entry for the lambda local. v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C+&lt;&gt;c__DisplayClass0_0"" methodName=""&lt;M&gt;b__0"" /> <hoistedLocalScopes> <slot startOffset=""0x30"" endOffset=""0xea"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x30"" hidden=""true"" /> <entry offset=""0x3b"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" /> <entry offset=""0x3c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" /> <entry offset=""0x48"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" /> <entry offset=""0x54"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" /> <entry offset=""0x60"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" /> <entry offset=""0x77"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""35"" /> <entry offset=""0xa9"" hidden=""true"" /> <entry offset=""0xb0"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""35"" /> <entry offset=""0xe2"" hidden=""true"" /> <entry offset=""0xe9"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")] [WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")] [Fact] public void DisplayClass_InBetweenSuspensionPoints_Release() { string source = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> M() { byte x1 = 1; byte x2 = 1; byte x3 = 1; ((Action)(() => { x1 = x2 = x3; }))(); yield return 1; } } "; // TODO: Currently we don't have means necessary to pass information about the display // class being pushed on evaluation stack, so that EE could find the locals. // Thus the locals are not available in EE. var v = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyIL("C.<M>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 90 (0x5a) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<M>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0010 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq.s IL_0051 IL_000e: ldc.i4.0 IL_000f: ret IL_0010: ldarg.0 IL_0011: ldc.i4.m1 IL_0012: stfld ""int C.<M>d__0.<>1__state"" IL_0017: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_001c: dup IL_001d: ldc.i4.1 IL_001e: stfld ""byte C.<>c__DisplayClass0_0.x1"" IL_0023: dup IL_0024: ldc.i4.1 IL_0025: stfld ""byte C.<>c__DisplayClass0_0.x2"" IL_002a: dup IL_002b: ldc.i4.1 IL_002c: stfld ""byte C.<>c__DisplayClass0_0.x3"" IL_0031: ldftn ""void C.<>c__DisplayClass0_0.<M>b__0()"" IL_0037: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_003c: callvirt ""void System.Action.Invoke()"" IL_0041: ldarg.0 IL_0042: ldc.i4.1 IL_0043: stfld ""int C.<M>d__0.<>2__current"" IL_0048: ldarg.0 IL_0049: ldc.i4.1 IL_004a: stfld ""int C.<M>d__0.<>1__state"" IL_004f: ldc.i4.1 IL_0050: ret IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: stfld ""int C.<M>d__0.<>1__state"" IL_0058: ldc.i4.0 IL_0059: ret } "); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C+&lt;&gt;c__DisplayClass0_0"" methodName=""&lt;M&gt;b__0"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x17"" hidden=""true"" /> <entry offset=""0x1c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" /> <entry offset=""0x23"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" /> <entry offset=""0x2a"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" /> <entry offset=""0x31"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" /> <entry offset=""0x41"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""24"" /> <entry offset=""0x51"" hidden=""true"" /> <entry offset=""0x58"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" /> </sequencePoints> </method> </methods> </symbols>"); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> </customDebugInfo> </method> </methods> </symbols>"); } [Fact] public void DisplayClass_InBetweenSuspensionPoints_Debug() { string source = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> M() { byte x1 = 1; byte x2 = 1; byte x3 = 1; ((Action)(() => { x1 = x2 = x3; }))(); yield return 1; // Possible EnC edit - add lambda: // () => { x1 } } } "; // We need to hoist display class variable to allow adding a new lambda after yield return // that shares closure with the existing lambda. var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "<>8__1", // hoisted display class }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyIL("C.<M>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 127 (0x7f) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<M>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_0076 IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<M>d__0.<>1__state"" IL_001f: ldarg.0 IL_0020: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0025: stfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1"" IL_002a: nop IL_002b: ldarg.0 IL_002c: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1"" IL_0031: ldc.i4.1 IL_0032: stfld ""byte C.<>c__DisplayClass0_0.x1"" IL_0037: ldarg.0 IL_0038: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1"" IL_003d: ldc.i4.1 IL_003e: stfld ""byte C.<>c__DisplayClass0_0.x2"" IL_0043: ldarg.0 IL_0044: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1"" IL_0049: ldc.i4.1 IL_004a: stfld ""byte C.<>c__DisplayClass0_0.x3"" IL_004f: ldarg.0 IL_0050: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1"" IL_0055: ldftn ""void C.<>c__DisplayClass0_0.<M>b__0()"" IL_005b: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0060: callvirt ""void System.Action.Invoke()"" IL_0065: nop IL_0066: ldarg.0 IL_0067: ldc.i4.1 IL_0068: stfld ""int C.<M>d__0.<>2__current"" IL_006d: ldarg.0 IL_006e: ldc.i4.1 IL_006f: stfld ""int C.<M>d__0.<>1__state"" IL_0074: ldc.i4.1 IL_0075: ret IL_0076: ldarg.0 IL_0077: ldc.i4.m1 IL_0078: stfld ""int C.<M>d__0.<>1__state"" IL_007d: ldc.i4.0 IL_007e: ret } "); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C+&lt;&gt;c__DisplayClass0_0"" methodName=""&lt;M&gt;b__0"" /> <hoistedLocalScopes> <slot startOffset=""0x1f"" endOffset=""0x7e"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x1f"" hidden=""true"" /> <entry offset=""0x2a"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" /> <entry offset=""0x2b"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" /> <entry offset=""0x37"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" /> <entry offset=""0x43"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" /> <entry offset=""0x4f"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" /> <entry offset=""0x66"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""24"" /> <entry offset=""0x76"" hidden=""true"" /> <entry offset=""0x7d"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" /> </sequencePoints> </method> </methods> </symbols>"); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""95"" closure=""0"" /> </encLambdaMap> </customDebugInfo> </method> </methods> </symbols>"); } [WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")] [WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")] [Fact] public void DynamicLocal_AcrossSuspensionPoints_Debug() { string source = @" using System.Collections.Generic; class C { static IEnumerable<int> M() { dynamic d = 1; yield return d; d.ToString(); } } "; var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "<d>5__1" }, module.GetFieldNames("C.<M>d__0")); }); // CHANGE: Dev12 emits a <dynamiclocal> entry for "d", but gives it slot "-1", preventing it from matching // any locals when consumed by the EE (i.e. it has no effect). See FUNCBRECEE::IsLocalDynamic. v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x1f"" endOffset=""0xe2"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x1f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" /> <entry offset=""0x20"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" /> <entry offset=""0x2c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" /> <entry offset=""0x82"" hidden=""true"" /> <entry offset=""0x89"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""22"" /> <entry offset=""0xe1"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe3""> <namespace name=""System.Collections.Generic"" /> </scope> </method> </methods> </symbols>"); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols> "); } [WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")] [WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")] [WorkItem(1070519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070519")] [Fact] public void DynamicLocal_InBetweenSuspensionPoints_Release() { string source = @" using System.Collections.Generic; class C { static IEnumerable<int> M() { dynamic d = 1; yield return d; } } "; var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flagCount=""1"" flags=""1"" slotId=""1"" localName=""d"" /> </dynamicLocals> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x17"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" /> <entry offset=""0x1e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" /> <entry offset=""0x6d"" hidden=""true"" /> <entry offset=""0x74"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x76""> <namespace name=""System.Collections.Generic"" /> <scope startOffset=""0x17"" endOffset=""0x76""> <local name=""d"" il_index=""1"" il_start=""0x17"" il_end=""0x76"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(1070519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070519")] [Fact] public void DynamicLocal_InBetweenSuspensionPoints_Debug() { string source = @" using System.Collections.Generic; class C { static IEnumerable<int> M() { dynamic d = 1; yield return d; // Possible EnC edit: // System.Console.WriteLine(d); } } "; var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "<d>5__1", }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x1f"" endOffset=""0x8a"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x1f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" /> <entry offset=""0x20"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" /> <entry offset=""0x2c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" /> <entry offset=""0x82"" hidden=""true"" /> <entry offset=""0x89"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8b""> <namespace name=""System.Collections.Generic"" /> </scope> </method> </methods> </symbols>"); } [Fact, WorkItem(667579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667579")] public void DebuggerHiddenIterator() { var text = @" using System; using System.Collections.Generic; using System.Diagnostics; class C { static void Main(string[] args) { foreach (var x in F()) ; } [DebuggerHidden] static IEnumerable<int> F() { throw new Exception(); yield break; } }"; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll); c.VerifyPdb("C+<F>d__1.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;F&gt;d__1"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x17"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" /> <entry offset=""0x18"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""31"" /> </sequencePoints> </method> </methods> </symbols>"); } } }
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace System.ServiceModel.Configuration { using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Reflection; using System.Runtime; using System.Runtime.Diagnostics; using System.Security; using System.Security.Permissions; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Diagnostics; static class ConfigurationHelpers { /// Be sure to update UnsafeGetAssociatedBindingCollectionElement if you modify this method internal static BindingCollectionElement GetAssociatedBindingCollectionElement(ContextInformation evaluationContext, string bindingCollectionName) { BindingCollectionElement retVal = null; BindingsSection bindingsSection = (BindingsSection)ConfigurationHelpers.GetAssociatedSection(evaluationContext, ConfigurationStrings.BindingsSectionGroupPath); if (null != bindingsSection) { bindingsSection.UpdateBindingSections(evaluationContext); try { retVal = bindingsSection[bindingCollectionName]; } catch (KeyNotFoundException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ConfigurationErrorsException(SR.GetString(SR.ConfigBindingExtensionNotFound, ConfigurationHelpers.GetBindingsSectionPath(bindingCollectionName)))); } catch (NullReferenceException) // System.Configuration.ConfigurationElement bug { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ConfigurationErrorsException(SR.GetString(SR.ConfigBindingExtensionNotFound, ConfigurationHelpers.GetBindingsSectionPath(bindingCollectionName)))); } } return retVal; } // Be sure to update GetAssociatedBindingCollectionElement if you modify this method [Fx.Tag.SecurityNote(Critical = "Uses SecurityCritical method UnsafeGetAssociatedSection which elevates.")] [SecurityCritical] internal static BindingCollectionElement UnsafeGetAssociatedBindingCollectionElement(ContextInformation evaluationContext, string bindingCollectionName) { BindingCollectionElement retVal = null; BindingsSection bindingsSection = (BindingsSection)ConfigurationHelpers.UnsafeGetAssociatedSection(evaluationContext, ConfigurationStrings.BindingsSectionGroupPath); if (null != bindingsSection) { bindingsSection.UpdateBindingSections(evaluationContext); try { retVal = bindingsSection[bindingCollectionName]; } catch (KeyNotFoundException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ConfigurationErrorsException(SR.GetString(SR.ConfigBindingExtensionNotFound, ConfigurationHelpers.GetBindingsSectionPath(bindingCollectionName)))); } catch (NullReferenceException) // System.Configuration.ConfigurationElement bug { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ConfigurationErrorsException(SR.GetString(SR.ConfigBindingExtensionNotFound, ConfigurationHelpers.GetBindingsSectionPath(bindingCollectionName)))); } } return retVal; } /// Be sure to update UnsafeGetAssociatedEndpointCollectionElement if you modify this method internal static EndpointCollectionElement GetAssociatedEndpointCollectionElement(ContextInformation evaluationContext, string endpointCollectionName) { EndpointCollectionElement retVal = null; StandardEndpointsSection endpointsSection = (StandardEndpointsSection)ConfigurationHelpers.GetAssociatedSection(evaluationContext, ConfigurationStrings.StandardEndpointsSectionPath); if (null != endpointsSection) { endpointsSection.UpdateEndpointSections(evaluationContext); try { retVal = (EndpointCollectionElement)endpointsSection[endpointCollectionName]; } catch (KeyNotFoundException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ConfigurationErrorsException(SR.GetString(SR.ConfigEndpointExtensionNotFound, ConfigurationHelpers.GetEndpointsSectionPath(endpointCollectionName)))); } catch (NullReferenceException) // System.Configuration.ConfigurationElement bug { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ConfigurationErrorsException(SR.GetString(SR.ConfigEndpointExtensionNotFound, ConfigurationHelpers.GetEndpointsSectionPath(endpointCollectionName)))); } } return retVal; } // Be sure to update GetAssociatedEndpointCollectionElement if you modify this method [Fx.Tag.SecurityNote(Critical = "Uses SecurityCritical method UnsafeGetAssociatedSection which elevates.")] [SecurityCritical] internal static EndpointCollectionElement UnsafeGetAssociatedEndpointCollectionElement(ContextInformation evaluationContext, string endpointCollectionName) { EndpointCollectionElement retVal = null; StandardEndpointsSection endpointsSection = (StandardEndpointsSection)ConfigurationHelpers.UnsafeGetAssociatedSection(evaluationContext, ConfigurationStrings.StandardEndpointsSectionPath); if (null != endpointsSection) { endpointsSection.UpdateEndpointSections(evaluationContext); try { retVal = (EndpointCollectionElement)endpointsSection[endpointCollectionName]; } catch (KeyNotFoundException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ConfigurationErrorsException(SR.GetString(SR.ConfigEndpointExtensionNotFound, ConfigurationHelpers.GetEndpointsSectionPath(endpointCollectionName)))); } catch (NullReferenceException) // System.Configuration.ConfigurationElement bug { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ConfigurationErrorsException(SR.GetString(SR.ConfigEndpointExtensionNotFound, ConfigurationHelpers.GetEndpointsSectionPath(endpointCollectionName)))); } } return retVal; } /// Be sure to update UnsafeGetAssociatedSection if you modify this method internal static object GetAssociatedSection(ContextInformation evalContext, string sectionPath) { object retval = null; if (evalContext != null) { retval = evalContext.GetSection(sectionPath); } else { retval = AspNetEnvironment.Current.GetConfigurationSection(sectionPath); // Trace after call to underlying configuration system to // insure that configuration system is initialized if (DiagnosticUtility.ShouldTraceVerbose) { TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.GetConfigurationSection, SR.GetString(SR.TraceCodeGetConfigurationSection), new StringTraceRecord("ConfigurationSection", sectionPath), null, null); } } if (retval == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ConfigurationErrorsException(SR.GetString(SR.ConfigSectionNotFound, sectionPath))); } return retval; } // Be sure to update GetAssociatedSection if you modify this method [Fx.Tag.SecurityNote(Critical = "Uses SecurityCritical methods which elevate.")] [SecurityCritical] internal static object UnsafeGetAssociatedSection(ContextInformation evalContext, string sectionPath) { object retval = null; if (evalContext != null) { retval = UnsafeGetSectionFromContext(evalContext, sectionPath); } else { retval = AspNetEnvironment.Current.UnsafeGetConfigurationSection(sectionPath); // Trace after call to underlying configuration system to // insure that configuration system is initialized if (DiagnosticUtility.ShouldTraceVerbose) { TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.GetConfigurationSection, SR.GetString(SR.TraceCodeGetConfigurationSection), new StringTraceRecord("ConfigurationSection", sectionPath), null, null); } } if (retval == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ConfigurationErrorsException(SR.GetString(SR.ConfigSectionNotFound, sectionPath))); } return retval; } /// Be sure to update UnsafeGetBindingCollectionElement if you modify this method internal static BindingCollectionElement GetBindingCollectionElement(string bindingCollectionName) { return GetAssociatedBindingCollectionElement(null, bindingCollectionName); } // Be sure to update GetBindingCollectionElement if you modify this method [Fx.Tag.SecurityNote(Critical = "Uses SecurityCritical method UnsafeGetAssociatedBindingCollectionElement which elevates.")] [SecurityCritical] internal static BindingCollectionElement UnsafeGetBindingCollectionElement(string bindingCollectionName) { return UnsafeGetAssociatedBindingCollectionElement(null, bindingCollectionName); } internal static string GetBindingsSectionPath(string sectionName) { return string.Concat(ConfigurationStrings.BindingsSectionGroupPath, "/", sectionName); } internal static string GetEndpointsSectionPath(string sectionName) { return string.Concat(ConfigurationStrings.StandardEndpointsSectionName, "/", sectionName); } /// Be sure to update UnsafeGetEndpointCollectionElement if you modify this method internal static EndpointCollectionElement GetEndpointCollectionElement(string endpointCollectionName) { return GetAssociatedEndpointCollectionElement(null, endpointCollectionName); } // Be sure to update GetEndpointCollectionElement if you modify this method [Fx.Tag.SecurityNote(Critical = "Uses SecurityCritical method UnsafeGetAssociatedEndpointCollectionElement which elevates.")] [SecurityCritical] internal static EndpointCollectionElement UnsafeGetEndpointCollectionElement(string endpointCollectionName) { return UnsafeGetAssociatedEndpointCollectionElement(null, endpointCollectionName); } /// Be sure to update UnsafeGetSection if you modify this method internal static object GetSection(string sectionPath) { return GetAssociatedSection(null, sectionPath); } // Be sure to update GetSection if you modify this method [Fx.Tag.SecurityNote(Critical = "Uses SecurityCritical method UnsafeGetAssociatedSection which elevates.")] [SecurityCritical] internal static object UnsafeGetSection(string sectionPath) { return UnsafeGetAssociatedSection(null, sectionPath); } // Be sure to update UnsafeGetSection if you modify this method [Fx.Tag.SecurityNote(Critical = "Uses SecurityCritical method UnsafeGetAssociatedSection which elevates.")] [SecurityCritical] internal static object UnsafeGetSectionNoTrace(string sectionPath) { object retval = AspNetEnvironment.Current.UnsafeGetConfigurationSection(sectionPath); if (retval == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ConfigurationErrorsException(SR.GetString(SR.ConfigSectionNotFound, sectionPath))); } return retval; } [Fx.Tag.SecurityNote(Critical = "Asserts ConfigurationPermission in order to fetch config from ContextInformation," + "caller must guard return value.")] [SecurityCritical] [ConfigurationPermission(SecurityAction.Assert, Unrestricted = true)] internal static object UnsafeGetSectionFromContext(ContextInformation evalContext, string sectionPath) { return evalContext.GetSection(sectionPath); } internal static string GetSectionPath(string sectionName) { return string.Concat(ConfigurationStrings.SectionGroupName, "/", sectionName); } [Fx.Tag.SecurityNote(Critical = "Calls SetIsPresentWithAssert which elevates in order to set a property." + "Caller must guard ConfigurationElement parameter, ie only pass 'this'.")] [SecurityCritical] internal static void SetIsPresent(ConfigurationElement element) { // Work around for VSW 578830: ConfigurationElements that override DeserializeElement cannot set ElementInformation.IsPresent PropertyInfo elementPresent = element.GetType().GetProperty("ElementPresent", BindingFlags.Instance | BindingFlags.NonPublic); SetIsPresentWithAssert(elementPresent, element, true); } [Fx.Tag.SecurityNote(Critical = "Asserts full trust in order to set a private member in the ConfigurationElement." + "Caller must guard parameters.")] [SecurityCritical] [PermissionSet(SecurityAction.Assert, Unrestricted = true)] static void SetIsPresentWithAssert(PropertyInfo elementPresent, ConfigurationElement element, bool value) { elementPresent.SetValue(element, value, null); } internal static ContextInformation GetEvaluationContext(IConfigurationContextProviderInternal provider) { if (provider != null) { try { return provider.GetEvaluationContext(); } catch (ConfigurationErrorsException) { } } return null; } [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - The return value will be used for a security decision. if in doubt about the return value, " + "it is safe to return null (caller will assume the worst case from a security perspective).")] internal static ContextInformation GetOriginalEvaluationContext(IConfigurationContextProviderInternal provider) { if (provider != null) { // provider may not need this try/catch, but it doesn't hurt to do it try { return provider.GetOriginalEvaluationContext(); } catch (ConfigurationErrorsException) { } } return null; } internal static void TraceExtensionTypeNotFound(ExtensionElement extensionElement) { if (DiagnosticUtility.ShouldTraceWarning) { Dictionary<string, string> values = new Dictionary<string, string>(2); values.Add("ExtensionName", extensionElement.Name); values.Add("ExtensionType", extensionElement.Type); DictionaryTraceRecord traceRecord = new DictionaryTraceRecord(values); TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.ExtensionTypeNotFound, SR.GetString(SR.TraceCodeExtensionTypeNotFound), traceRecord, null, (Exception)null); } } } interface IConfigurationContextProviderInternal { /// <summary> /// return the current ContextInformation (the protected property ConfigurationElement.EvaluationContext) /// this may throw ConfigurationErrorsException, caller should guard (see ConfigurationHelpers.GetEvaluationContext) /// </summary> /// <returns>result of ConfigurationElement.EvaluationContext</returns> ContextInformation GetEvaluationContext(); /// <summary> /// return the ContextInformation that was present when the ConfigurationElement was first deserialized. /// if Reset was called, this will be the value of parent.GetOriginalEvaluationContext() /// if Reset was not called, this will be the value of this.GetEvaluationContext() /// </summary> /// <returns>result of parent's ConfigurationElement.EvaluationContext</returns> [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - the return value will be used for a security decision. if in doubt about the return value, it " + "is safe (from a security perspective) to return null (caller will assume the worst case).")] ContextInformation GetOriginalEvaluationContext(); } [Fx.Tag.SecurityNote(Critical = "Stores information used in a security decision.")] #pragma warning disable 618 // have not moved to the v4 security model yet [SecurityCritical(SecurityCriticalScope.Everything)] #pragma warning restore 618 struct EvaluationContextHelper { bool reset; ContextInformation inheritedContext; internal void OnReset(ConfigurationElement parent) { this.reset = true; this.inheritedContext = ConfigurationHelpers.GetOriginalEvaluationContext(parent as IConfigurationContextProviderInternal); } internal ContextInformation GetOriginalContext(IConfigurationContextProviderInternal owner) { if (this.reset) { // if reset, inherited context is authoritative, even if null return this.inheritedContext; } else { // otherwise use current return ConfigurationHelpers.GetEvaluationContext(owner); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Tests { /// <summary> /// Contains tests that ensure the correctness of the Dictionary class. /// </summary> public abstract class SortedList_Generic_Tests<TKey, TValue> : IDictionary_Generic_Tests<TKey, TValue> { #region IDictionary<TKey, TValue> Helper Methods protected override IDictionary<TKey, TValue> GenericIDictionaryFactory() { return new SortedList<TKey, TValue>(); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public override void Enumerator_MoveNext_AfterDisposal(int count) { // Disposal of the enumerator is treated the same as a Reset call IEnumerator<KeyValuePair<TKey, TValue>> enumerator = GenericIEnumerableFactory(count).GetEnumerator(); for (int i = 0; i < count; i++) enumerator.MoveNext(); enumerator.Dispose(); if (count > 0) Assert.True(enumerator.MoveNext()); } protected override Type ICollection_Generic_CopyTo_IndexLargerThanArrayCount_ThrowType => typeof(ArgumentOutOfRangeException); #endregion #region Constructor_IComparer [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_Constructor_IComparer(int count) { IComparer<TKey> comparer = GetKeyIComparer(); IDictionary<TKey, TValue> source = GenericIDictionaryFactory(count); SortedList<TKey, TValue> copied = new SortedList<TKey, TValue>(source, comparer); Assert.Equal(source, copied); Assert.Equal(comparer, copied.Comparer); } #endregion #region Constructor_IDictionary [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_Constructor_IDictionary(int count) { IDictionary<TKey, TValue> source = GenericIDictionaryFactory(count); IDictionary<TKey, TValue> copied = new SortedList<TKey, TValue>(source); Assert.Equal(source, copied); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_Constructor_NullIDictionary_ThrowsArgumentNullException(int count) { Assert.Throws<ArgumentNullException>(() => new SortedList<TKey, TValue>((IDictionary<TKey, TValue>)null)); } #endregion #region Constructor_IDictionary_IComparer [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_Constructor_IDictionary_IComparer(int count) { IComparer<TKey> comparer = GetKeyIComparer(); IDictionary<TKey, TValue> source = GenericIDictionaryFactory(count); SortedList<TKey, TValue> copied = new SortedList<TKey, TValue>(source, comparer); Assert.Equal(source, copied); Assert.Equal(comparer, copied.Comparer); } #endregion #region Constructor_int [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_Constructor_int(int count) { SortedList<TKey, TValue> dictionary = new SortedList<TKey, TValue>(count); Assert.Equal(0, dictionary.Count); Assert.Equal(count, dictionary.Capacity); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_Constructor_NegativeCapacity_ThrowsArgumentOutOfRangeException(int count) { Assert.Throws<ArgumentOutOfRangeException>(() => new SortedList<TKey, TValue>(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => new SortedList<TKey, TValue>(int.MinValue)); } #endregion #region Constructor_int_IComparer [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_Constructor_int_IComparer(int count) { IComparer<TKey> comparer = GetKeyIComparer(); SortedList<TKey, TValue> dictionary = new SortedList<TKey, TValue>(count, comparer); Assert.Equal(0, dictionary.Count); Assert.Equal(comparer, dictionary.Comparer); Assert.Equal(count, dictionary.Capacity); } #endregion #region Capacity [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_Capacity_setRoundTrips(int count) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); dictionary.Capacity = count * 2; Assert.Equal(count * 2, dictionary.Capacity); dictionary.Capacity = count * 2 + 16000; Assert.Equal(count * 2 + 16000, dictionary.Capacity); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_Capacity_NegativeValue_ThrowsArgumentOutOfRangeException(int count) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); int capacityBefore = dictionary.Capacity; AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => dictionary.Capacity = -1); Assert.Equal(capacityBefore, dictionary.Capacity); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_Capacity_LessThanCount_ThrowsArgumentOutOfRangeException(int count) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(); for (int i = 0; i < count; i++) { AddToCollection(dictionary, 1); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => dictionary.Capacity = i); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_Capacity_GrowsDuringAdds(int count) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(); int capacity = 4; for (int i = 0; i < count; i++) { AddToCollection(dictionary, 1); //if the array needs to grow, it doubles the size if (i == capacity) capacity *= 2; if (i <= capacity + 1) Assert.Equal(capacity, dictionary.Capacity); else Assert.Equal(i, dictionary.Capacity); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_Capacity_ClearDoesntTrim(int count) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(); int capacity = 4; for (int i = 0; i < count; i++) { AddToCollection(dictionary, 1); //if the array needs to grow, it doubles the size if (i == capacity) capacity *= 2; } dictionary.Clear(); if (count == 0) Assert.Equal(0, dictionary.Capacity); else Assert.Equal(capacity, dictionary.Capacity); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_Capacity_ClearTrimsToInitialCapacity(int count) { SortedList<TKey, TValue> dictionary = new SortedList<TKey, TValue>(count); AddToCollection(dictionary, count); dictionary.Clear(); Assert.Equal(count, dictionary.Capacity); } #endregion #region ContainsValue [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_ContainsValue_NotPresent(int count) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); int seed = 4315; TValue notPresent = CreateTValue(seed++); while (dictionary.Values.Contains(notPresent)) notPresent = CreateTValue(seed++); Assert.False(dictionary.ContainsValue(notPresent)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_ContainsValue_Present(int count) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); int seed = 4315; KeyValuePair<TKey, TValue> notPresent = CreateT(seed++); while (dictionary.Contains(notPresent)) notPresent = CreateT(seed++); dictionary.Add(notPresent.Key, notPresent.Value); Assert.True(dictionary.ContainsValue(notPresent.Value)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_ContainsValue_DefaultValueNotPresent(int count) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); Assert.False(dictionary.ContainsValue(default(TValue))); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_ContainsValue_DefaultValuePresent(int count) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); int seed = 4315; TKey notPresent = CreateTKey(seed++); while (dictionary.ContainsKey(notPresent)) notPresent = CreateTKey(seed++); dictionary.Add(notPresent, default(TValue)); Assert.True(dictionary.ContainsValue(default(TValue))); } #endregion #region IndexOfKey [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_IndexOf_DefaultKeyNotContainedInSortedList(int count) { if (DefaultValueAllowed) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); TKey key = default(TKey); if (dictionary.ContainsKey(key)) { if (IsReadOnly) return; dictionary.Remove(key); } Assert.Equal(-1, dictionary.IndexOfKey(key)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_IndexOfKey_EachKey(int count) { // Assumes no duplicate elements contained in the dictionary returned by GenericIListFactory SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); IList<TKey> keys = dictionary.Keys; Assert.All(Enumerable.Range(0, count), index => { Assert.Equal(index, dictionary.IndexOfKey(keys[index])); }); } #endregion #region IndexOfValue [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_IndexOfValue_DefaultValueNotContainedInList(int count) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); TValue value = default(TValue); while (dictionary.ContainsValue(value)) { if (IsReadOnly) return; dictionary.RemoveAt(dictionary.IndexOfValue(value)); } Assert.Equal(-1, dictionary.IndexOfValue(value)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_IndexOfValue_DefaultValueContainedInList(int count) { if (!IsReadOnly) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); TKey key = GetNewKey(dictionary); TValue value = default(TValue); while (dictionary.ContainsValue(value)) dictionary.RemoveAt(dictionary.IndexOfValue(value)); List<TKey> keys = dictionary.Keys.ToList(); keys.Add(key); keys.Sort(); int expectedIndex = keys.IndexOf(key); dictionary.Add(key, value); Assert.Equal(expectedIndex, dictionary.IndexOfValue(value)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_IndexOfValue_ValueInCollectionMultipleTimes(int count) { if (!IsReadOnly) { int seed = 53214; SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); TKey key1 = CreateTKey(seed++); TKey key2 = CreateTKey(seed++); TValue value = CreateTValue(seed++); while (dictionary.ContainsKey(key1)) key1 = CreateTKey(seed++); while (key1.Equals(key2) || dictionary.ContainsKey(key2)) key2 = CreateTKey(seed++); while (dictionary.ContainsValue(value)) dictionary.RemoveAt(dictionary.IndexOfValue(value)); List<TKey> keys = dictionary.Keys.ToList(); keys.Add(key1); keys.Add(key2); keys.Sort(); int expectedIndex = Math.Min(keys.IndexOf(key1), keys.IndexOf(key2)); dictionary.Add(key1, value); dictionary.Add(key2, value); Assert.Equal(expectedIndex, dictionary.IndexOfValue(value)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_IndexOfValue_EachValue(int count) { // Assumes no duplicate elements contained in the dictionary returned by GenericIListFactory SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); IList<TKey> keys = dictionary.Keys; Assert.All(Enumerable.Range(0, count), index => { Assert.Equal(index, dictionary.IndexOfValue(dictionary[keys[index]])); }); } #endregion #region RemoveAt private void RemoveAt(SortedList<TKey, TValue> dictionary, KeyValuePair<TKey, TValue> element) { dictionary.RemoveAt(dictionary.IndexOfKey(element.Key)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_RemoveAt_OnReadOnlySortedList_ThrowsNotSupportedException(int count) { if (IsReadOnly) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); Assert.Throws<NotSupportedException>(() => RemoveAt(dictionary, CreateT(34543))); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_RemoveAt_NonDefaultValueContainedInCollection(int count) { if (!IsReadOnly) { int seed = count * 251; SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); KeyValuePair<TKey, TValue> pair = CreateT(seed++); if (!dictionary.ContainsKey(pair.Key)) { dictionary.Add(pair.Key, pair.Value); count++; } RemoveAt(dictionary, pair); Assert.Equal(count - 1, dictionary.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_RemoveAt_EveryValue(int count) { if (!IsReadOnly) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); Assert.All(dictionary.ToList(), value => { RemoveAt(dictionary, value); }); Assert.Empty(dictionary); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_RemoveAt_OutOfRangeValues(int count) { if (!IsReadOnly) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(count); Assert.Throws<ArgumentOutOfRangeException>(() => dictionary.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => dictionary.RemoveAt(int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => dictionary.RemoveAt(count)); Assert.Throws<ArgumentOutOfRangeException>(() => dictionary.RemoveAt(count + 1)); } } #endregion #region TrimExcess [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_TrimExcess_OnValidSortedListThatHasntBeenRemovedFrom(int dictionaryLength) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(dictionaryLength); dictionary.TrimExcess(); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_TrimExcess_Repeatedly(int dictionaryLength) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(dictionaryLength); List<KeyValuePair<TKey, TValue>> expected = dictionary.ToList(); dictionary.TrimExcess(); dictionary.TrimExcess(); dictionary.TrimExcess(); Assert.True(dictionary.SequenceEqual(expected, GetIEqualityComparer())); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_TrimExcess_AfterRemovingOneElement(int dictionaryLength) { if (dictionaryLength > 0) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(dictionaryLength); List<KeyValuePair<TKey, TValue>> expected = dictionary.ToList(); KeyValuePair<TKey, TValue> elementToRemove = dictionary.ElementAt(0); dictionary.TrimExcess(); Assert.True(dictionary.Remove(elementToRemove.Key)); expected.Remove(elementToRemove); dictionary.TrimExcess(); Assert.True(dictionary.SequenceEqual(expected, GetIEqualityComparer())); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_TrimExcess_AfterClearingAndAddingSomeElementsBack(int dictionaryLength) { if (dictionaryLength > 0) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(dictionaryLength); dictionary.TrimExcess(); dictionary.Clear(); dictionary.TrimExcess(); Assert.Equal(0, dictionary.Count); AddToCollection(dictionary, dictionaryLength / 10); dictionary.TrimExcess(); Assert.Equal(dictionaryLength / 10, dictionary.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_TrimExcess_AfterClearingAndAddingAllElementsBack(int dictionaryLength) { if (dictionaryLength > 0) { SortedList<TKey, TValue> dictionary = (SortedList<TKey, TValue>)GenericIDictionaryFactory(dictionaryLength); dictionary.TrimExcess(); dictionary.Clear(); dictionary.TrimExcess(); Assert.Equal(0, dictionary.Count); AddToCollection(dictionary, dictionaryLength); dictionary.TrimExcess(); Assert.Equal(dictionaryLength, dictionary.Count); } } #endregion #region Ordering [Theory] [MemberData(nameof(ValidCollectionSizes))] public void SortedList_Generic_DictionaryIsProperlySortedAccordingToComparer(int setLength) { SortedList<TKey, TValue> set = (SortedList<TKey, TValue>)GenericIDictionaryFactory(setLength); List<KeyValuePair<TKey, TValue>> expected = set.ToList(); expected.Sort(GetIComparer()); int expectedIndex = 0; foreach (KeyValuePair<TKey, TValue> value in set) Assert.Equal(expected[expectedIndex++], value); } #endregion #region IReadOnlyDictionary<TKey, TValue>.Keys [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IReadOnlyDictionary_Generic_Keys_ContainsAllCorrectKeys(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); IEnumerable<TKey> expected = dictionary.Select((pair) => pair.Key); IEnumerable<TKey> keys = ((IReadOnlyDictionary<TKey, TValue>)dictionary).Keys; Assert.True(expected.SequenceEqual(keys)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IReadOnlyDictionary_Generic_Values_ContainsAllCorrectValues(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); IEnumerable<TValue> expected = dictionary.Select((pair) => pair.Value); IEnumerable<TValue> values = ((IReadOnlyDictionary<TKey, TValue>)dictionary).Values; Assert.True(expected.SequenceEqual(values)); } #endregion } }
using System; using Eto.Forms; using Eto.Drawing; namespace Eto.Test.Sections.Controls { [Section("Controls", typeof(TextArea))] public class TextAreaSection : Scrollable { public TextAreaSection() { Content = Default(); } Control Default() { var text = new TextArea { Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." }; LogEvents(text); return new TableLayout { Padding = new Padding(10), Spacing = new Size(5, 5), Rows = { TextAreaOptions(text), TextAreaOptions2(text), TextAreaOptions3(text), text } }; } public static Control TextAreaOptions(TextArea text) { return new StackLayout { Orientation = Orientation.Horizontal, Spacing = 5, Items = { null, ShowSelectedText(text), SetSelectedText(text), ReplaceSelected(text), SelectAll(text), null } }; } public static Control TextAreaOptions2(TextArea text) { return new StackLayout { Orientation = Orientation.Horizontal, Spacing = 5, Items = { null, SetAlignment(text), SetCaretButton(text), ChangeColorButton(text), null } }; } public static Control TextAreaOptions3(TextArea text) { return new StackLayout { Orientation = Orientation.Horizontal, Spacing = 5, Items = { null, EnabledCheckBox(text), ReadOnlyCheckBox(text), AcceptsTabCheckBox(text), AcceptsReturnCheckBox(text), WrapCheckBox(text), SpellCheckCheckBox(text), null } }; } static Control WrapCheckBox(TextArea text) { var control = new CheckBox { Text = "Wrap" }; control.CheckedBinding.Bind(text, t => t.Wrap); return control; } static Control AcceptsReturnCheckBox(TextArea text) { var control = new CheckBox { Text = "AcceptsReturn" }; control.CheckedBinding.Bind(text, t => t.AcceptsReturn); return control; } static Control AcceptsTabCheckBox(TextArea text) { var control = new CheckBox { Text = "AcceptsTab" }; control.CheckedBinding.Bind(text, t => t.AcceptsTab); return control; } static Control SpellCheckCheckBox(TextArea text) { var control = new CheckBox { Text = "SpellCheck", Enabled = text.SpellCheckIsSupported }; control.CheckedBinding.Bind(text, t => t.SpellCheck); return control; } static Control SetAlignment(TextArea text) { var control = new EnumDropDown<TextAlignment>(); control.SelectedValueBinding.Bind(text, t => t.TextAlignment); return new TableLayout { Padding = Padding.Empty, Spacing = new Size(5, 5), Rows = { new TableRow(new Label { Text = "Alignment", VerticalAlignment = VerticalAlignment.Center }, control) } }; } static Control ShowSelectedText(TextArea text) { var control = new Button { Text = "Show selected text" }; control.Click += (sender, e) => MessageBox.Show(text, string.Format("Selected Text: {0}", text.SelectedText)); return control; } static Control SelectAll(TextArea text) { var control = new Button { Text = "Select All" }; control.Click += (sender, e) => { text.SelectAll(); text.Focus(); }; return control; } static Control SetSelectedText(TextArea textArea) { var control = new Button { Text = "Set selected text" }; control.Click += (sender, e) => { var text = textArea.Text; // select the last half of the text textArea.Selection = new Range<int>(text.Length / 2, text.Length / 2 + 1); textArea.Focus(); }; return control; } static Control ReplaceSelected(TextArea textArea) { var control = new Button { Text = "Replace selected text" }; control.Click += (sender, e) => { textArea.SelectedText = "Some inserted text!"; textArea.Focus(); }; return control; } static Control SetCaretButton(TextArea textArea) { var control = new Button { Text = "Set Caret" }; control.Click += (sender, e) => { textArea.CaretIndex = textArea.Text.Length / 2; textArea.Focus(); }; return control; } static Control ChangeColorButton(TextArea textArea) { var control = new Button { Text = "Change Color" }; control.Click += (sender, e) => { textArea.BackgroundColor = Colors.Black; textArea.TextColor = Colors.Blue; }; return control; } static Control EnabledCheckBox(TextArea textArea) { var control = new CheckBox { Text = "Enabled" }; control.CheckedBinding.Bind(textArea, t => t.Enabled); return control; } static Control ReadOnlyCheckBox(TextArea textArea) { var control = new CheckBox { Text = "ReadOnly" }; control.CheckedBinding.Bind(textArea, t => t.ReadOnly); return control; } void LogEvents(TextArea control) { control.TextChanged += (sender, e) => Log.Write(control, "TextChanged, Text: {0}", control.Text); control.SelectionChanged += (sender, e) => Log.Write(control, "SelectionChanged, Selection: {0}", control.Selection); control.CaretIndexChanged += (sender, e) => Log.Write(control, "CaretIndexChanged, CaretIndex: {0}", control.CaretIndex); } } }
//----------------------------------------------------------------------- // <copyright file="Timers.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using Akka.Streams.Implementation.Fusing; using Akka.Streams.Implementation.Stages; using Akka.Streams.Stage; namespace Akka.Streams.Implementation { /// <summary> /// INTERNAL API /// /// Various stages for controlling timeouts on IO related streams (although not necessarily). /// /// The common theme among the processing stages here that /// - they wait for certain event or events to happen /// - they have a timer that may fire before these events /// - if the timer fires before the event happens, these stages all fail the stream /// - otherwise, these streams do not interfere with the element flow, ordinary completion or failure /// </summary> public static class Timers { /// <summary> /// TBD /// </summary> /// <param name="timeout">TBD</param> /// <returns>TBD</returns> public static TimeSpan IdleTimeoutCheckInterval(TimeSpan timeout) => new TimeSpan(Math.Min(Math.Max(timeout.Ticks/8, 100*TimeSpan.TicksPerMillisecond), timeout.Ticks/2)); /// <summary> /// TBD /// </summary> public const string GraphStageLogicTimer = "GraphStageLogicTimer"; } /// <summary> /// INTERNAL API /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class Initial<T> : SimpleLinearGraphStage<T> { #region Logic private sealed class Logic : TimerGraphStageLogic, IInHandler, IOutHandler { private readonly Initial<T> _stage; private bool _initialHasPassed; public Logic(Initial<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Inlet, this); SetHandler(stage.Outlet, this); } public void OnPush() { _initialHasPassed = true; Push(_stage.Outlet, Grab(_stage.Inlet)); } public void OnUpstreamFinish() => CompleteStage(); public void OnUpstreamFailure(Exception e) => FailStage(e); public void OnPull() => Pull(_stage.Inlet); public void OnDownstreamFinish() => CompleteStage(); protected internal override void OnTimer(object timerKey) { if (!_initialHasPassed) FailStage(new TimeoutException($"The first element has not yet passed through in {_stage.Timeout}.")); } public override void PreStart() => ScheduleOnce(Timers.GraphStageLogicTimer, _stage.Timeout); } #endregion /// <summary> /// TBD /// </summary> public readonly TimeSpan Timeout; /// <summary> /// TBD /// </summary> /// <param name="timeout">TBD</param> public Initial(TimeSpan timeout) { Timeout = timeout; } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = DefaultAttributes.Initial; /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "InitialTimeoutTimer"; } /// <summary> /// INTERNAL API /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class Completion<T> : SimpleLinearGraphStage<T> { #region stage logic private sealed class Logic : TimerGraphStageLogic, IInHandler, IOutHandler { private readonly Completion<T> _stage; public Logic(Completion<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Inlet, this); SetHandler(stage.Outlet, this); } public void OnPush() => Push(_stage.Outlet, Grab(_stage.Inlet)); public void OnUpstreamFinish() => CompleteStage(); public void OnUpstreamFailure(Exception e) => FailStage(e); public void OnPull() => Pull(_stage.Inlet); public void OnDownstreamFinish() => CompleteStage(); protected internal override void OnTimer(object timerKey) => FailStage(new TimeoutException($"The stream has not been completed in {_stage.Timeout}.")); public override void PreStart() => ScheduleOnce(Timers.GraphStageLogicTimer, _stage.Timeout); } #endregion /// <summary> /// TBD /// </summary> public readonly TimeSpan Timeout; /// <summary> /// TBD /// </summary> /// <param name="timeout">TBD</param> public Completion(TimeSpan timeout) { Timeout = timeout; } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = DefaultAttributes.Completion; /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "CompletionTimeout"; } /// <summary> /// INTERNAL API /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class Idle<T> : SimpleLinearGraphStage<T> { #region stage logic private sealed class Logic : TimerGraphStageLogic, IInHandler, IOutHandler { private readonly Idle<T> _stage; private long _nextDeadline; public Logic(Idle<T> stage) : base(stage.Shape) { _stage = stage; _nextDeadline = DateTime.UtcNow.Ticks + stage.Timeout.Ticks; SetHandler(stage.Inlet, this); SetHandler(stage.Outlet, this); } public void OnPush() { _nextDeadline = DateTime.UtcNow.Ticks + _stage.Timeout.Ticks; Push(_stage.Outlet, Grab(_stage.Inlet)); } public void OnUpstreamFinish() => CompleteStage(); public void OnUpstreamFailure(Exception e) => FailStage(e); public void OnPull() => Pull(_stage.Inlet); public void OnDownstreamFinish() => CompleteStage(); protected internal override void OnTimer(object timerKey) { if (_nextDeadline - DateTime.UtcNow.Ticks < 0) FailStage(new TimeoutException($"No elements passed in the last {_stage.Timeout}.")); } public override void PreStart() => ScheduleRepeatedly(Timers.GraphStageLogicTimer, Timers.IdleTimeoutCheckInterval(_stage.Timeout)); } #endregion /// <summary> /// TBD /// </summary> public readonly TimeSpan Timeout; /// <summary> /// TBD /// </summary> /// <param name="timeout">TBD</param> public Idle(TimeSpan timeout) { Timeout = timeout; } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = DefaultAttributes.Idle; /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "IdleTimeout"; } /// <summary> /// INTERNAL API /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class BackpressureTimeout<T> : SimpleLinearGraphStage<T> { #region stage logic private sealed class Logic : TimerGraphStageLogic, IInHandler, IOutHandler { private readonly BackpressureTimeout<T> _stage; private long _nextDeadline; private bool _waitingDemand = true; public Logic(BackpressureTimeout<T> stage) : base(stage.Shape) { _stage = stage; _nextDeadline = DateTime.UtcNow.Ticks + stage.Timeout.Ticks; SetHandler(stage.Inlet, this); SetHandler(stage.Outlet, this); } public void OnPush() { Push(_stage.Outlet, Grab(_stage.Inlet)); _nextDeadline = DateTime.UtcNow.Ticks + _stage.Timeout.Ticks; _waitingDemand = true; } public void OnUpstreamFinish() => CompleteStage(); public void OnUpstreamFailure(Exception e) => FailStage(e); public void OnPull() { _waitingDemand = false; Pull(_stage.Inlet); } public void OnDownstreamFinish() => CompleteStage(); protected internal override void OnTimer(object timerKey) { if (_waitingDemand && (_nextDeadline - DateTime.UtcNow.Ticks < 0)) FailStage(new TimeoutException($"No demand signalled in the last {_stage.Timeout}.")); } public override void PreStart() => ScheduleRepeatedly(Timers.GraphStageLogicTimer, Timers.IdleTimeoutCheckInterval(_stage.Timeout)); } #endregion /// <summary> /// TBD /// </summary> public readonly TimeSpan Timeout; /// <summary> /// TBD /// </summary> /// <param name="timeout">TBD</param> public BackpressureTimeout(TimeSpan timeout) { Timeout = timeout; } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = DefaultAttributes.BackpressureTimeout; /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "BackpressureTimeout"; } /// <summary> /// INTERNAL API /// </summary> /// <typeparam name="TIn">TBD</typeparam> /// <typeparam name="TOut">TBD</typeparam> public sealed class IdleTimeoutBidi<TIn, TOut> : GraphStage<BidiShape<TIn, TIn, TOut, TOut>> { #region Logic private sealed class Logic : TimerGraphStageLogic, IInHandler, IOutHandler { private readonly IdleTimeoutBidi<TIn, TOut> _stage; private long _nextDeadline; public Logic(IdleTimeoutBidi<TIn, TOut> stage) : base(stage.Shape) { _stage = stage; _nextDeadline = DateTime.UtcNow.Ticks + _stage.Timeout.Ticks; SetHandler(_stage.In1, this); SetHandler(_stage.Out1, this); SetHandler(_stage.In2, onPush: () => { OnActivity(); Push(_stage.Out2, Grab(_stage.In2)); }, onUpstreamFinish: () => Complete(_stage.Out2)); SetHandler(_stage.Out2, onPull: () => Pull(_stage.In2), onDownstreamFinish: () => Cancel(_stage.In2)); } public void OnPush() { OnActivity(); Push(_stage.Out1, Grab(_stage.In1)); } public void OnUpstreamFinish() => Complete(_stage.Out1); public void OnUpstreamFailure(Exception e) => FailStage(e); public void OnPull() => Pull(_stage.In1); public void OnDownstreamFinish() => Cancel(_stage.In1); protected internal override void OnTimer(object timerKey) { if (_nextDeadline - DateTime.UtcNow.Ticks < 0) FailStage(new TimeoutException($"No elements passed in the last {_stage.Timeout}.")); } public override void PreStart() => ScheduleRepeatedly(Timers.GraphStageLogicTimer, Timers.IdleTimeoutCheckInterval(_stage.Timeout)); private void OnActivity() => _nextDeadline = DateTime.UtcNow.Ticks + _stage.Timeout.Ticks; } #endregion /// <summary> /// TBD /// </summary> public readonly TimeSpan Timeout; /// <summary> /// TBD /// </summary> public readonly Inlet<TIn> In1 = new Inlet<TIn>("in1"); /// <summary> /// TBD /// </summary> public readonly Inlet<TOut> In2 = new Inlet<TOut>("in2"); /// <summary> /// TBD /// </summary> public readonly Outlet<TIn> Out1 = new Outlet<TIn>("out1"); /// <summary> /// TBD /// </summary> public readonly Outlet<TOut> Out2 = new Outlet<TOut>("out2"); /// <summary> /// TBD /// </summary> /// <param name="timeout">TBD</param> public IdleTimeoutBidi(TimeSpan timeout) { Timeout = timeout; Shape = new BidiShape<TIn, TIn, TOut, TOut>(In1, Out1, In2, Out2); } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = DefaultAttributes.IdleTimeoutBidi; /// <summary> /// TBD /// </summary> public override BidiShape<TIn, TIn, TOut, TOut> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "IdleTimeoutBidi"; } /// <summary> /// INTERNAL API /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class DelayInitial<T> : GraphStage<FlowShape<T, T>> { #region stage logic private sealed class Logic : TimerGraphStageLogic, IInHandler, IOutHandler { private readonly DelayInitial<T> _stage; private bool _isOpen; public Logic(DelayInitial<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(_stage.In, this); SetHandler(_stage.Out, this); } public void OnPush() => Push(_stage.Out, Grab(_stage.In)); public void OnUpstreamFinish() => CompleteStage(); public void OnUpstreamFailure(Exception e) => FailStage(e); public void OnPull() { if (_isOpen) Pull(_stage.In); } public void OnDownstreamFinish() => CompleteStage(); protected internal override void OnTimer(object timerKey) { _isOpen = true; if (IsAvailable(_stage.Out)) Pull(_stage.In); } public override void PreStart() { if (_stage.Delay == TimeSpan.Zero) _isOpen = true; else ScheduleOnce(Timers.GraphStageLogicTimer, _stage.Delay); } } #endregion /// <summary> /// TBD /// </summary> public readonly TimeSpan Delay; /// <summary> /// TBD /// </summary> public readonly Inlet<T> In = new Inlet<T>("DelayInitial.in"); /// <summary> /// TBD /// </summary> public readonly Outlet<T> Out = new Outlet<T>("DelayInitial.out"); /// <summary> /// TBD /// </summary> /// <param name="delay">TBD</param> public DelayInitial(TimeSpan delay) { Delay = delay; Shape = new FlowShape<T, T>(In, Out); } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = DefaultAttributes.DelayInitial; /// <summary> /// TBD /// </summary> public override FlowShape<T, T> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "DelayTimer"; } /// <summary> /// INTERNAL API /// </summary> /// <typeparam name="TIn">TBD</typeparam> /// <typeparam name="TOut">TBD</typeparam> public sealed class IdleInject<TIn, TOut> : GraphStage<FlowShape<TIn, TOut>> where TIn : TOut { #region Logic private sealed class Logic : TimerGraphStageLogic, IInHandler, IOutHandler { private readonly IdleInject<TIn, TOut> _stage; private long _nextDeadline; public Logic(IdleInject<TIn, TOut> stage) : base(stage.Shape) { _stage = stage; _nextDeadline = DateTime.UtcNow.Ticks + _stage._timeout.Ticks; SetHandler(_stage._in, this); SetHandler(_stage._out, this); } public void OnPush() { _nextDeadline = DateTime.UtcNow.Ticks + _stage._timeout.Ticks; CancelTimer(Timers.GraphStageLogicTimer); if (IsAvailable(_stage._out)) { Push(_stage._out, Grab(_stage._in)); Pull(_stage._in); } } public void OnUpstreamFinish() { if (!IsAvailable(_stage._in)) CompleteStage(); } public void OnUpstreamFailure(Exception e) => FailStage(e); public void OnPull() { if (IsAvailable(_stage._in)) { Push(_stage._out, Grab(_stage._in)); if (IsClosed(_stage._in)) CompleteStage(); else Pull(_stage._in); } else { var time = DateTime.UtcNow.Ticks; if (_nextDeadline - time < 0) { _nextDeadline = time + _stage._timeout.Ticks; Push(_stage._out, _stage._inject()); } else ScheduleOnce(Timers.GraphStageLogicTimer, TimeSpan.FromTicks(_nextDeadline - time)); } } public void OnDownstreamFinish() => CompleteStage(); protected internal override void OnTimer(object timerKey) { var time = DateTime.UtcNow.Ticks; if ((_nextDeadline - time < 0) && IsAvailable(_stage._out)) { Push(_stage._out, _stage._inject()); _nextDeadline = DateTime.UtcNow.Ticks + _stage._timeout.Ticks; } } // Prefetching to ensure priority of actual upstream elements public override void PreStart() => Pull(_stage._in); } #endregion private readonly TimeSpan _timeout; private readonly Func<TOut> _inject; private readonly Inlet<TIn> _in = new Inlet<TIn>("IdleInject.in"); private readonly Outlet<TOut> _out = new Outlet<TOut>("IdleInject.out"); /// <summary> /// TBD /// </summary> /// <param name="timeout">TBD</param> /// <param name="inject">TBD</param> public IdleInject(TimeSpan timeout, Func<TOut> inject) { _timeout = timeout; _inject = inject; Shape = new FlowShape<TIn, TOut>(_in, _out); } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = DefaultAttributes.IdleInject; /// <summary> /// TBD /// </summary> public override FlowShape<TIn, TOut> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "IdleTimer"; } }
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.Collections.Generic; using System.Text; using OpenADK.Library.Infra; namespace OpenADK.Library.Log { /// <summary> Provides access to the Zone Integration Server log. /// /// ServerLog functionality can be customized and extended by adding one or /// more <i>ServerLogModule</i> implementations to the chain of loggers. The /// logging chain is hierarchical, comprised of ServerLog instances at the Adk, /// Agent, and Zone levels. Whenever a server-side logging operation is /// performed on a zone, it is delegated to the <i>ServerLogModule</i> instances /// at each level in the hierarchy, beginning with the Zone. /// /// To customize server-side logging on a global basis, call the /// <c>Adk.getServerLog</c> static function and use the methods below to /// manipulate <i>ServerLogModule</i> instances at the root level of the /// hierarchy: /// /// <ul> /// <li><c>addLogger</c></li> /// <li><c>removeLogger</c></li> /// <li><c>clearLoggers</c></li> /// <li><c>getLoggers</c></li> /// </ul> * /// /// Similarly, to customize logging on an agent-global basis or per-zone basis, /// call the <c>Agent.getServerLog</c> or <c>Agent.getServerLog( Zone )</c> /// methods to obtain the ServerLog for the Agent or a Zone, respectively. /// /// /// </summary> public class ServerLog { /// <summary> Get a list of all registered ServerLogModule modules that comprise the /// chain of loggers. /// /// </summary> /// <seealso cref="AddLogger"> /// </seealso> /// <seealso cref="RemoveLogger"> /// </seealso> /// <seealso cref="ClearLoggers"> /// /// @since Adk 1.5 /// </seealso> public virtual IServerLogModule [] GetLoggers() { lock ( fLoggers ) { IServerLogModule [] arr = new IServerLogModule[fLoggers.Count]; fLoggers.CopyTo( arr, 0 ); return arr; } } /// <summary> Global registry of ServerLog instances keyed by ID</summary> private static IDictionary<String, ServerLog> sInstances = new Dictionary<String, ServerLog>(); /// <summary> The parent ServerLog</summary> private ServerLog fParent; /// <summary>The ID</summary> private string fID; /// <summary> The zone to which log entries will be reported</summary> private IZone fZone; /// <summary> ServerLogModule objects to which log information will be posted</summary> private IList<IServerLogModule> fLoggers = new List<IServerLogModule>(); /// <summary> Protected constructor; clients must call <c>getInstance</c></summary> private ServerLog( string id, IZone zone ) { fID = id; fZone = zone; // Determine the parent if ( id.Equals( Adk.LOG_IDENTIFIER ) ) { fParent = null; } else if ( id.Equals( Agent.LOG_IDENTIFIER ) ) { fParent = GetInstance( Adk.LOG_IDENTIFIER, zone ); } else { fParent = GetInstance( Agent.LOG_IDENTIFIER, zone ); } } /// <summary> /// Returns the ID of this logger instance /// </summary> public string Id { get { return fID; } } /// <summary> Get a ServerLog instance with the specified ID. /// /// This method is intended to be called internally by the Adk. You /// should call the <c>Adk.getServerLog</c>, <c>Agent.getServerLog</c>, /// or <c>Zone.getServerLog</c> methods to obtain a ServerLog instance /// rather than directly calling this method. /// /// </summary> /// <param name="id">The ID identifying the ServerLog to return /// </param> /// <param name="zone">The zone that is currently in scope</param> /// <returns> A ServerLog instance /// </returns> public static ServerLog GetInstance( string id, IZone zone ) { if ( id == null ) { throw new ArgumentException( "ID cannot be null" ); } ServerLog log = null; if ( !sInstances.TryGetValue( id, out log ) ) { log = new ServerLog( id, zone ); sInstances[id] = log; } return log; } /// <summary> Adda a ServerLogModule to the chain of loggers. /// /// </summary> /// <param name="logger">A <i>ServerLogModule</i> implementation /// /// </param> /// <seealso cref="RemoveLogger"> /// </seealso> /// <seealso cref="ClearLoggers"> /// </seealso> /// @since Adk 1.5 /// </seealso> public virtual void AddLogger( IServerLogModule logger ) { lock ( fLoggers ) { if ( !fLoggers.Contains( logger ) ) { fLoggers.Add( logger ); } } } /// <summary> Remove a ServerLogModule from the chain of loggers. /// /// </summary> /// <param name="logger">A <i>ServerLogModule</i> implementation /// /// </param> /// <seealso cref="AddLogger"> /// </seealso> /// <seealso cref="ClearLoggers"> /// </seealso> /// <seealso cref="GetLoggers"> /// /// @since Adk 1.5 /// </seealso> public virtual void RemoveLogger( IServerLogModule logger ) { lock ( fLoggers ) { fLoggers.Remove( logger ); } } /// <summary> Clear all ServerLogModule modules from the chain of loggers. /// /// </summary> /// <seealso cref="AddLogger"> /// </seealso> /// <seealso cref="RemoveLogger"> /// </seealso> /// <seealso cref="GetLoggers"> /// /// @since Adk 1.5 /// </seealso> public virtual void ClearLoggers() { lock ( fLoggers ) { fLoggers.Clear(); } } /// <summary> Copies all registered ServerLogModules for this ServerLog into the /// supplied Vector. /// @since Adk 1.5 /// </summary> protected internal virtual void GetLoggersInto( IList<IServerLogModule> target ) { lock ( fLoggers ) { foreach ( IServerLogModule o in fLoggers ) { target.Add( o ); } } } /// <summary> Post a SIF_LogEntry to the server. /// Use this form of the <c>log</c> method to post a simple /// informative message to the server. /// </summary> /// <param name="message">A textual description of the error /// </param> public virtual void Log( string message ) { Log( LogLevel.INFO, message, null, null, - 1, - 1, null, null ); } /// <summary> Post a SIF_LogEntry to the server. /// /// Use this form of the <c>log</c> method to post an /// error, warning, or informative message to the server with an /// description, extended description, and optional application-defined /// error code. /// /// </summary> /// <param name="level">The LogLevel to assign to this log entry /// </param> /// <param name="desc">A textual description of the error /// </param> /// <param name="extDesc">Extended error description, or <c>null</c> if no /// value is to be assigned to the SIF_LogEntry/SIF_ExtDesc element /// </param> /// <param name="appCode">Error code specific to the application posting the log /// entry, or <c>null</c> if no value is to be assigned to the /// SIF_LogEntry/SIF_ApplicationCode element /// </param> public virtual void Log( LogLevel level, string desc, string extDesc, string appCode ) { Log( level, desc, extDesc, appCode, - 1, - 1, null, null ); } /// <summary> Post a SIF_LogEntry to the server. /// /// Use this form of the <c>log</c> method to post an /// error, warning, or informative message to the server with an category /// and code enumerated by the SIF Specification. /// /// </summary> /// <param name="level">The LogLevel to assign to this log entry /// </param> /// <param name="desc">A textual description of the error /// </param> /// <param name="extDesc">Extended error description, or <c>null</c> if no /// value is to be assigned to the SIF_LogEntry/SIF_ExtDesc element /// </param> /// <param name="appCode">Error code specific to the application posting the log /// entry, or <c>null</c> if no value is to be assigned to the /// SIF_LogEntry/SIF_ApplicationCode element /// </param> /// <param name="category">The SIF_Category value to assign to this log entry, as /// defined by the SIF Specification /// </param> /// <param name="category">The SIF_Code value to assign to this log entry, as /// defined by the SIF Specification /// </param> public virtual void Log( LogLevel level, string desc, string extDesc, string appCode, int category, int code ) { Log( level, desc, extDesc, appCode, category, code, null, null ); } /// <summary> Post a SIF_LogEntry to the server. /// /// Use this form of the <c>log</c> method to post a simple /// error, warning, or informative message to the server that references a /// SIF Message and optionally a set of SIF Data Objects previously received /// by the agent. /// /// </summary> /// <param name="level">The LogLevel to assign to this log entry /// </param> /// <param name="message">A textual description of the error /// </param> /// <param name="info">The <i>SifMessageInfo</i> instance from the Adk message /// handler implementation identifying a SIF Message received by the agent /// </param> /// <param name="objects">One or more SifDataObject instances received in the message /// identified by the <i>info</i> parameter /// </param> public virtual void Log( LogLevel level, string message, SifMessageInfo info, SifDataObject [] objects ) { Log( level, message, null, null, - 1, - 1, info, objects ); } /// <summary> Post a SIF_LogEntry to the server. /// /// Use this form of the <c>log</c> method to post an /// error, warning, or informative message to the server that references a /// SIF Message and optionally a set of SIF Data Objects previously received /// by the agent. The log entry can also have an extended error description /// and application-defined error code. /// /// </summary> /// <param name="level">The LogLevel to assign to this log entry /// </param> /// <param name="desc">A textual description of the error /// </param> /// <param name="extDesc">Extended error description, or <c>null</c> if no /// value is to be assigned to the SIF_LogEntry/SIF_ExtDesc element /// </param> /// <param name="appCode">Error code specific to the application posting the log /// entry, or <c>null</c> if no value is to be assigned to the /// SIF_LogEntry/SIF_ApplicationCode element /// </param> /// <param name="info">The <i>SifMessageInfo</i> instance from the Adk message /// handler implementation identifying a SIF Message received by the agent /// </param> /// <param name="objects">One or more SifDataObject instances received in the message /// identified by the <i>info</i> parameter /// </param> public virtual void Log( LogLevel level, string desc, string extDesc, string appCode, SifMessageInfo info, SifDataObject [] objects ) { Log( level, desc, extDesc, appCode, - 1, - 1, info, objects ); } /// <summary> Post a SIF_LogEntry to the server. /// /// Use this form of the <c>log</c> method to post an error, warning, /// or informative message to the server that references a /// SIF Message and optionally a set of SIF Data Objects previously received /// by the agent. The log entry is assigned a category and code defined by /// the SIF Specification, and may have an extended error description and /// optional application-defined error code. /// /// </summary> /// <param name="level">The LogLevel to assign to this log entry /// </param> /// <param name="desc">A textual description of the error /// </param> /// <param name="extDesc">Extended error description, or <c>null</c> if no /// value is to be assigned to the SIF_LogEntry/SIF_ExtDesc element /// </param> /// <param name="appCode">Error code specific to the application posting the log /// entry, or <c>null</c> if no value is to be assigned to the /// SIF_LogEntry/SIF_ApplicationCode element /// </param> /// <param name="category">The SIF_Category value to assign to this log entry, as /// defined by the SIF Specification /// </param> /// <param name="category">The SIF_Code value to assign to this log entry, as /// defined by the SIF Specification /// </param> /// <param name="info">The <i>SifMessageInfo</i> instance from the Adk message /// handler implementation identifying a SIF Message received by the agent /// </param> /// <param name="objects">One or more SifDataObject instances received in the message /// identified by the <i>info</i> parameter /// </param> public virtual void Log( LogLevel level, string desc, string extDesc, string appCode, int category, int code, SifMessageInfo info, params SifDataObject [] objects ) { if ( fZone == null ) { throw new SystemException ( "ServerLog.log can only be called on a zone's ServerLog instance" ); } string msg = null; SIF_LogEntry le = null; if ( Adk.SifVersion.CompareTo( SifVersion.SIF15r1 ) >= 0 ) { // Create a SIF_LogEntry le = new SIF_LogEntry(); le.SetSource( LogSource.AGENT ); le.SetLogLevel( LogLevel.Wrap( level == null ? "Unknown" : level.ToString() ) ); if ( desc != null ) { le.SIF_Desc = desc; } if ( extDesc != null ) { le.SIF_ExtendedDesc = extDesc; } if ( appCode != null ) { le.SIF_ApplicationCode = appCode; } if ( category != - 1 ) { le.SIF_Category = category.ToString(); } if ( code != - 1 ) { le.SIF_Code = code; } // Reference a SIF_Message? if ( info != null ) { try { SIF_Header headerCopy = (SIF_Header) info.SIFHeader.Clone(); SIF_LogEntryHeader sleh = new SIF_LogEntryHeader(); sleh.SIF_Header = headerCopy; // Assign to SIF_OriginalHeader le.SIF_OriginalHeader = sleh; } catch ( Exception ex ) { fZone.Log.Warn ( "Unable to clone SIF_Header for SIF_LogEntry event:" + ex.Message, ex ); } } if ( objects != null ) { SIF_LogObjects slos = new SIF_LogObjects(); le.SIF_LogObjects = slos; for ( int i = 0; i < objects.Length; i++ ) { if ( objects[i] == null ) { continue; } // Package into a SIF_LogObject and add to the repeatable list // of SIF_LogEntry/SIF_LogObjects SIF_LogObject lo = new SIF_LogObject(); lo.ObjectName = objects[i].ObjectType.Tag( info.SifVersion ); lo.AddChild( (SifElement) objects[i].Clone() ); slos.Add( lo ); } } } else { // When running in SIF 1.1 or earlier, there is no // SIF_LogEntry support. Build a string that can be // written to the local zone log, including as much // information from the would-be SIF_LogEntry as // possible. StringBuilder b = new StringBuilder(); b.Append( "Server Log [Level=" ); b.Append( level == null ? "Unknown" : level.ToString() ); if ( category != - 1 && code != - 1 ) { b.Append( ", Category=" ); b.Append( category ); b.Append( ", Code=" ); b.Append( code ); } if ( appCode != null ) { b.Append( ", AppCode=" ); b.Append( appCode ); } b.Append( "] " ); if ( desc != null ) { b.Append( desc ); } if ( extDesc != null ) { b.Append( ". " + extDesc ); } msg = b.ToString(); } // Post the the server IServerLogModule [] chain = _getLogChain( fZone ); for ( int i = 0; i < chain.Length; i++ ) { if ( le != null ) { chain[i].Log( fZone, le ); } else { chain[i].Log( fZone, msg ); } } } private IServerLogModule [] _getLogChain( IZone zone ) { List<IServerLogModule> v = new List<IServerLogModule>(); ServerLog parent = this; while ( parent != null ) { parent.GetLoggersInto( v ); parent = parent.fParent; } return v.ToArray(); } } }
// 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; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Roslyn.Test.Utilities; using Xunit; using SymbolDisplay = Microsoft.CodeAnalysis.CSharp.SymbolDisplay; using VB = Microsoft.CodeAnalysis.VisualBasic; using ObjectFormatterFixtures; using Microsoft.CodeAnalysis.Scripting.CSharp; #region Fixtures #pragma warning disable 169 // unused field #pragma warning disable 649 // field not set, will always be default value namespace ObjectFormatterFixtures { internal class Outer { public class Nested<T> { public readonly int A = 1; public readonly int B = 2; public static readonly int S = 3; } } internal class A<T> { public class B<S> { public class C { public class D<Q, R> { public class E { } } } } public static readonly B<T> X = new B<T>(); } internal class Sort { public readonly byte ab = 1; public readonly sbyte aB = -1; public readonly short Ac = -1; public readonly ushort Ad = 1; public readonly int ad = -1; public readonly uint aE = 1; public readonly long aF = -1; public readonly ulong AG = 1; } internal class RecursiveRootHidden { public readonly int A; public readonly int B; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public RecursiveRootHidden C; } internal class RecursiveProxy { private class Proxy { public Proxy() { } public Proxy(Node node) { x = node.value; y = node.next; } public readonly int x; public readonly Node y; } [DebuggerTypeProxy(typeof(Proxy))] public class Node { public Node(int value) { if (value < 5) { next = new Node(value + 1); } this.value = value; } public readonly int value; public readonly Node next; } } internal class InvalidRecursiveProxy { private class Proxy { public Proxy() { } public Proxy(Node c) { } public readonly int x; public readonly Node p = new Node(); public readonly int y; } [DebuggerTypeProxy(typeof(Proxy))] public class Node { public readonly int a; public readonly int b; } } internal class ComplexProxyBase { private int Foo() { return 1; } } internal class ComplexProxy : ComplexProxyBase { public ComplexProxy() { } public ComplexProxy(object b) { } [DebuggerDisplay("*1")] public int _02_public_property_dd { get { return 1; } } [DebuggerDisplay("*2")] private int _03_private_property_dd { get { return 1; } } [DebuggerDisplay("*3")] protected int _04_protected_property_dd { get { return 1; } } [DebuggerDisplay("*4")] internal int _05_internal_property_dd { get { return 1; } } [DebuggerDisplay("+1")] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public readonly int _06_public_field_dd_never; [DebuggerDisplay("+2")] private readonly int _07_private_field_dd; [DebuggerDisplay("+3")] protected readonly int _08_protected_field_dd; [DebuggerDisplay("+4")] internal readonly int _09_internal_field_dd; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] private readonly int _10_private_collapsed; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private readonly int _10_private_rootHidden; public readonly int _12_public; private readonly int _13_private; protected readonly int _14_protected; internal readonly int _15_internal; [DebuggerDisplay("==\r\n=\r\n=")] public readonly int _16_eolns; [DebuggerDisplay("=={==")] public readonly int _17_braces_0; [DebuggerDisplay("=={{==")] public readonly int _17_braces_1; [DebuggerDisplay("=={'{'}==")] public readonly int _17_braces_2; [DebuggerDisplay("=={'\\{'}==")] public readonly int _17_braces_3; [DebuggerDisplay("=={1/*{*/}==")] public readonly int _17_braces_4; [DebuggerDisplay("=={'{'/*\\}*/}==")] public readonly int _17_braces_5; [DebuggerDisplay("=={'{'/*}*/}==")] public readonly int _17_braces_6; [DebuggerDisplay("==\\{\\x\\t==")] public readonly int _19_escapes; [DebuggerDisplay("{1+1}")] public readonly int _21; [DebuggerDisplay("{\"xxx\"}")] public readonly int _22; [DebuggerDisplay("{\"xxx\",nq}")] public readonly int _23; [DebuggerDisplay("{'x'}")] public readonly int _24; [DebuggerDisplay("{'x',nq}")] public readonly int _25; [DebuggerDisplay("{new B()}")] public readonly int _26_0; [DebuggerDisplay("{new D()}")] public readonly int _26_1; [DebuggerDisplay("{new E()}")] public readonly int _26_2; [DebuggerDisplay("{ReturnVoid()}")] public readonly int _26_3; private void ReturnVoid() { } [DebuggerDisplay("{F1(1)}")] public readonly int _26_4; [DebuggerDisplay("{Foo}")] public readonly int _26_5; [DebuggerDisplay("{foo}")] public readonly int _26_6; private int foo() { return 2; } private int F1(int a) { return 1; } private int F2(short a) { return 2; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public readonly C _27_rootHidden = new C(); public readonly C _28 = new C(); [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public readonly C _29_collapsed = new C(); public int _31 { get; set; } [CompilerGenerated] public readonly int _32; [CompilerGenerated] private readonly int _33; public int _34_Exception { get { throw new Exception("error1"); } } [DebuggerDisplay("-!-")] public int _35_Exception { get { throw new Exception("error2"); } } public readonly object _36 = new ToStringException(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] public int _37 { get { throw new Exception("error3"); } } public int _38_private_get_public_set { private get { return 1; } set { } } public int _39_public_get_private_set { get { return 1; } private set { } } private int _40_private_get_private_set { get { return 1; } set { } } public override string ToString() { return "AStr"; } } [DebuggerTypeProxy(typeof(ComplexProxy))] internal class TypeWithComplexProxy { public override string ToString() { return "BStr"; } } [DebuggerTypeProxy(typeof(Proxy))] [DebuggerDisplay("DD")] internal class TypeWithDebuggerDisplayAndProxy { public override string ToString() { return "<ToString>"; } [DebuggerDisplay("pxy")] private class Proxy { public Proxy(object x) { } public readonly int A; public readonly int B; } } internal class C { public readonly int A = 1; public readonly int B = 2; public override string ToString() { return "CStr"; } } internal class ToStringException { public override string ToString() { throw new MyException(); } } internal class MyException : Exception { public override string ToString() { return "my exception"; } } public class ThrowingDictionary : IDictionary { private readonly int _throwAt; public ThrowingDictionary(int throwAt) { _throwAt = throwAt; } public void Add(object key, object value) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(object key) { throw new NotImplementedException(); } public IDictionaryEnumerator GetEnumerator() { return new E(_throwAt); } public bool IsFixedSize { get { throw new NotImplementedException(); } } public bool IsReadOnly { get { throw new NotImplementedException(); } } public ICollection Keys { get { return new[] { 1, 2 }; } } public void Remove(object key) { } public ICollection Values { get { return new[] { 1, 2 }; } } public object this[object key] { get { return 1; } set { } } public void CopyTo(Array array, int index) { } public int Count { get { return 10; } } public bool IsSynchronized { get { throw new NotImplementedException(); } } public object SyncRoot { get { throw new NotImplementedException(); } } IEnumerator IEnumerable.GetEnumerator() { return new E(-1); } private class E : IEnumerator, IDictionaryEnumerator { private int _i; private readonly int _throwAt; public E(int throwAt) { _throwAt = throwAt; } public object Current { get { return new DictionaryEntry(_i, _i); } } public bool MoveNext() { _i++; if (_i == _throwAt) { throw new Exception(); } return _i < 5; } public void Reset() { } public DictionaryEntry Entry { get { return (DictionaryEntry)Current; } } public object Key { get { return _i; } } public object Value { get { return _i; } } } } public class ListNode { public ListNode next; public object data; } public class LongMembers { public readonly string LongName0123456789_0123456789_0123456789_0123456789_0123456789_0123456789_0123456789 = "hello"; public readonly string LongValue = "0123456789_0123456789_0123456789_0123456789_0123456789_0123456789_0123456789"; } } #pragma warning restore 169 // unused field #pragma warning restore 649 // field not set, will always be default value #endregion namespace Microsoft.CodeAnalysis.Scripting.UnitTests { public class ObjectFormatterTests { private static readonly ObjectFormattingOptions s_hexa = new ObjectFormattingOptions(useHexadecimalNumbers: true); private static readonly ObjectFormattingOptions s_memberList = new ObjectFormattingOptions(memberFormat: MemberDisplayFormat.List); private static readonly ObjectFormattingOptions s_inline = new ObjectFormattingOptions(memberFormat: MemberDisplayFormat.Inline); private void AssertMembers(string str, params string[] expected) { int i = 0; foreach (var line in str.Split(new[] { "\r\n " }, StringSplitOptions.None)) { if (i == 0) { Assert.Equal(expected[i] + " {", line); } else if (i == expected.Length - 1) { Assert.Equal(expected[i] + "\r\n}\r\n", line); } else { Assert.Equal(expected[i] + ",", line); } i++; } Assert.Equal(expected.Length, i); } private string FilterDisplayString(string str) { str = System.Text.RegularExpressions.Regex.Replace(str, @"Id = \d+", "Id = *"); str = System.Text.RegularExpressions.Regex.Replace(str, @"Id=\d+", "Id=*"); str = System.Text.RegularExpressions.Regex.Replace(str, @"Id: \d+", "Id: *"); return str; } [Fact] public void Objects() { string str; object nested = new Outer.Nested<int>(); str = CSharpObjectFormatter.Instance.FormatObject(nested, s_inline); Assert.Equal(@"Outer.Nested<int> { A=1, B=2 }", str); str = CSharpObjectFormatter.Instance.FormatObject(nested, new ObjectFormattingOptions(memberFormat: MemberDisplayFormat.NoMembers)); Assert.Equal(@"Outer.Nested<int>", str); str = CSharpObjectFormatter.Instance.FormatObject(A<int>.X, new ObjectFormattingOptions(memberFormat: MemberDisplayFormat.NoMembers)); Assert.Equal(@"A<int>.B<int>", str); object obj = new A<int>.B<bool>.C.D<string, double>.E(); str = CSharpObjectFormatter.Instance.FormatObject(obj, new ObjectFormattingOptions(memberFormat: MemberDisplayFormat.NoMembers)); Assert.Equal(@"A<int>.B<bool>.C.D<string, double>.E", str); var sort = new Sort(); str = CSharpObjectFormatter.Instance.FormatObject(sort, new ObjectFormattingOptions(maxLineLength: 51, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal(@"Sort { aB=-1, ab=1, Ac=-1, Ad=1, ad=-1, aE=1, a ...", str); Assert.Equal(51, str.Length); str = CSharpObjectFormatter.Instance.FormatObject(sort, new ObjectFormattingOptions(maxLineLength: 5, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal(@"S ...", str); Assert.Equal(5, str.Length); str = CSharpObjectFormatter.Instance.FormatObject(sort, new ObjectFormattingOptions(maxLineLength: 4, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal(@"...", str); str = CSharpObjectFormatter.Instance.FormatObject(sort, new ObjectFormattingOptions(maxLineLength: 3, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal(@"...", str); str = CSharpObjectFormatter.Instance.FormatObject(sort, new ObjectFormattingOptions(maxLineLength: 2, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal(@"...", str); str = CSharpObjectFormatter.Instance.FormatObject(sort, new ObjectFormattingOptions(maxLineLength: 1, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal(@"...", str); str = CSharpObjectFormatter.Instance.FormatObject(sort, new ObjectFormattingOptions(maxLineLength: 80, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal(@"Sort { aB=-1, ab=1, Ac=-1, Ad=1, ad=-1, aE=1, aF=-1, AG=1 }", str); } [Fact] public void ArrayOtInt32_NoMembers() { CSharpObjectFormatter formatter = CSharpObjectFormatter.Instance; object o = new int[4] { 3, 4, 5, 6 }; var str = formatter.FormatObject(o); Assert.Equal("int[4] { 3, 4, 5, 6 }", str); } #region DANGER: Debugging this method under VS2010 might freeze your machine. [Fact] public void RecursiveRootHidden() { var DO_NOT_ADD_TO_WATCH_WINDOW = new RecursiveRootHidden(); DO_NOT_ADD_TO_WATCH_WINDOW.C = DO_NOT_ADD_TO_WATCH_WINDOW; string str = CSharpObjectFormatter.Instance.FormatObject(DO_NOT_ADD_TO_WATCH_WINDOW, s_inline); Assert.Equal(@"RecursiveRootHidden { A=0, B=0 }", str); } #endregion [Fact] public void DebuggerDisplay_ParseSimpleMemberName() { Test_ParseSimpleMemberName("foo", name: "foo", callable: false, nq: false); Test_ParseSimpleMemberName("foo ", name: "foo", callable: false, nq: false); Test_ParseSimpleMemberName(" foo", name: "foo", callable: false, nq: false); Test_ParseSimpleMemberName(" foo ", name: "foo", callable: false, nq: false); Test_ParseSimpleMemberName("foo()", name: "foo", callable: true, nq: false); Test_ParseSimpleMemberName("\nfoo (\r\n)", name: "foo", callable: true, nq: false); Test_ParseSimpleMemberName(" foo ( \t) ", name: "foo", callable: true, nq: false); Test_ParseSimpleMemberName("foo,nq", name: "foo", callable: false, nq: true); Test_ParseSimpleMemberName("foo ,nq", name: "foo", callable: false, nq: true); Test_ParseSimpleMemberName("foo(),nq", name: "foo", callable: true, nq: true); Test_ParseSimpleMemberName(" foo \t( ) ,nq", name: "foo", callable: true, nq: true); Test_ParseSimpleMemberName(" foo \t( ) , nq", name: "foo", callable: true, nq: true); Test_ParseSimpleMemberName("foo, nq", name: "foo", callable: false, nq: true); Test_ParseSimpleMemberName("foo(,nq", name: "foo(", callable: false, nq: true); Test_ParseSimpleMemberName("foo),nq", name: "foo)", callable: false, nq: true); Test_ParseSimpleMemberName("foo ( ,nq", name: "foo (", callable: false, nq: true); Test_ParseSimpleMemberName("foo ) ,nq", name: "foo )", callable: false, nq: true); Test_ParseSimpleMemberName(",nq", name: "", callable: false, nq: true); Test_ParseSimpleMemberName(" ,nq", name: "", callable: false, nq: true); } private void Test_ParseSimpleMemberName(string value, string name, bool callable, bool nq) { bool actualNoQuotes, actualIsCallable; string actualName = CSharpObjectFormatter.Formatter.ParseSimpleMemberName(value, 0, value.Length, out actualNoQuotes, out actualIsCallable); Assert.Equal(name, actualName); Assert.Equal(nq, actualNoQuotes); Assert.Equal(callable, actualIsCallable); actualName = CSharpObjectFormatter.Formatter.ParseSimpleMemberName("---" + value + "-", 3, 3 + value.Length, out actualNoQuotes, out actualIsCallable); Assert.Equal(name, actualName); Assert.Equal(nq, actualNoQuotes); Assert.Equal(callable, actualIsCallable); } [Fact] public void DebuggerDisplay() { string str; var a = new ComplexProxy(); str = CSharpObjectFormatter.Instance.FormatObject(a, s_memberList); AssertMembers(str, @"[AStr]", @"_02_public_property_dd: *1", @"_03_private_property_dd: *2", @"_04_protected_property_dd: *3", @"_05_internal_property_dd: *4", @"_07_private_field_dd: +2", @"_08_protected_field_dd: +3", @"_09_internal_field_dd: +4", @"_10_private_collapsed: 0", @"_12_public: 0", @"_13_private: 0", @"_14_protected: 0", @"_15_internal: 0", "_16_eolns: ==\r\n=\r\n=", @"_17_braces_0: =={==", @"_17_braces_1: =={{==", @"_17_braces_2: ==!<Member ''{'' not found>==", @"_17_braces_3: ==!<Member ''\{'' not found>==", @"_17_braces_4: ==!<Member '1/*{*/' not found>==", @"_17_braces_5: ==!<Member ''{'/*\' not found>*/}==", @"_17_braces_6: ==!<Member ''{'/*' not found>*/}==", @"_19_escapes: ==\{\x\t==", @"_21: !<Member '1+1' not found>", @"_22: !<Member '""xxx""' not found>", @"_23: !<Member '""xxx""' not found>", @"_24: !<Member ''x'' not found>", @"_25: !<Member ''x'' not found>", @"_26_0: !<Method 'new B' not found>", @"_26_1: !<Method 'new D' not found>", @"_26_2: !<Method 'new E' not found>", @"_26_3: ", @"_26_4: !<Member 'F1(1)' not found>", @"_26_5: 1", @"_26_6: 2", @"A: 1", @"B: 2", @"_28: [CStr]", @"_29_collapsed: [CStr]", @"_31: 0", @"_32: 0", @"_33: 0", @"_34_Exception: !<Exception>", @"_35_Exception: -!-", @"_36: !<MyException>", @"_38_private_get_public_set: 1", @"_39_public_get_private_set: 1", @"_40_private_get_private_set: 1" ); var b = new TypeWithComplexProxy(); str = CSharpObjectFormatter.Instance.FormatObject(b, s_memberList); AssertMembers(str, @"[BStr]", @"_02_public_property_dd: *1", @"_04_protected_property_dd: *3", @"_08_protected_field_dd: +3", @"_10_private_collapsed: 0", @"_12_public: 0", @"_14_protected: 0", "_16_eolns: ==\r\n=\r\n=", @"_17_braces_0: =={==", @"_17_braces_1: =={{==", @"_17_braces_2: ==!<Member ''{'' not found>==", @"_17_braces_3: ==!<Member ''\{'' not found>==", @"_17_braces_4: ==!<Member '1/*{*/' not found>==", @"_17_braces_5: ==!<Member ''{'/*\' not found>*/}==", @"_17_braces_6: ==!<Member ''{'/*' not found>*/}==", @"_19_escapes: ==\{\x\t==", @"_21: !<Member '1+1' not found>", @"_22: !<Member '""xxx""' not found>", @"_23: !<Member '""xxx""' not found>", @"_24: !<Member ''x'' not found>", @"_25: !<Member ''x'' not found>", @"_26_0: !<Method 'new B' not found>", @"_26_1: !<Method 'new D' not found>", @"_26_2: !<Method 'new E' not found>", @"_26_3: ", @"_26_4: !<Member 'F1(1)' not found>", @"_26_5: 1", @"_26_6: 2", @"A: 1", @"B: 2", @"_28: [CStr]", @"_29_collapsed: [CStr]", @"_31: 0", @"_32: 0", @"_34_Exception: !<Exception>", @"_35_Exception: -!-", @"_36: !<MyException>", @"_38_private_get_public_set: 1", @"_39_public_get_private_set: 1" ); } [Fact] public void DebuggerProxy_DebuggerDisplayAndProxy() { var obj = new TypeWithDebuggerDisplayAndProxy(); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("TypeWithDebuggerDisplayAndProxy(DD) { A=0, B=0 }", str); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "TypeWithDebuggerDisplayAndProxy(DD)", "A: 0", "B: 0" ); } [Fact] public void DebuggerProxy_Recursive() { string str; object obj = new RecursiveProxy.Node(0); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "Node", "x: 0", "y: Node { x=1, y=Node { x=2, y=Node { x=3, y=Node { x=4, y=Node { x=5, y=null } } } } }" ); obj = new InvalidRecursiveProxy.Node(); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); // TODO: better overflow handling Assert.Equal("!<Stack overflow while evaluating object>", str); } [Fact] public void Array_Recursive() { string str; ListNode n2; ListNode n1 = new ListNode(); object[] obj = new object[5]; obj[0] = 1; obj[1] = obj; obj[2] = n2 = new ListNode() { data = obj, next = n1 }; obj[3] = new object[] { 4, 5, obj, 6, new ListNode() }; obj[4] = 3; n1.next = n2; n1.data = new object[] { 7, n2, 8, obj }; str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "object[5]", "1", "{ ... }", "ListNode { data={ ... }, next=ListNode { data=object[4] { 7, ListNode { ... }, 8, { ... } }, next=ListNode { ... } } }", "object[5] { 4, 5, { ... }, 6, ListNode { data=null, next=null } }", "3" ); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal(str, "object[5] { 1, { ... }, ListNode { data={ ... }, next=ListNode { data=object[4] { 7, ListNode { ... }, 8, { ... } }, next=ListNode { ... } } }, object[5] { 4, 5, { ... }, 6, ListNode { data=null, next=null } }, 3 }"); } [Fact] public void LargeGraph() { var list = new LinkedList<object>(); object obj = list; for (int i = 0; i < 10000; i++) { var node = list.AddFirst(i); var newList = new LinkedList<object>(); list.AddAfter(node, newList); list = newList; } string output = "LinkedList<object>(2) { 0, LinkedList<object>(2) { 1, LinkedList<object>(2) { 2, LinkedList<object>(2) {"; for (int i = 100; i > 4; i--) { var options = new ObjectFormattingOptions(maxOutputLength: i, memberFormat: MemberDisplayFormat.Inline); var str = CSharpObjectFormatter.Instance.FormatObject(obj, options); var expected = output.Substring(0, i - " ...".Length); if (!expected.EndsWith(" ", StringComparison.Ordinal)) { expected += " "; } expected += "..."; Assert.Equal(expected, str); } } [Fact] public void LongMembers() { object obj = new LongMembers(); var options = new ObjectFormattingOptions(maxLineLength: 20, memberFormat: MemberDisplayFormat.Inline); //str = ObjectFormatter.Instance.FormatObject(obj, options); //Assert.Equal("LongMembers { Lo ...", str); options = new ObjectFormattingOptions(maxLineLength: 20, memberFormat: MemberDisplayFormat.List); var str = CSharpObjectFormatter.Instance.FormatObject(obj, options); Assert.Equal("LongMembers {\r\n LongName012345 ...\r\n LongValue: \"01 ...\r\n}\r\n", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Array() { var obj = new Object[] { new C(), 1, "str", 'c', true, null, new bool[] { true, false, true, false } }; var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "object[7]", "[CStr]", "1", "\"str\"", "'c'", "true", "null", "bool[4] { true, false, true, false }" ); } [Fact] public void DebuggerProxy_FrameworkTypes_MdArray() { string str; int[,,] a = new int[2, 3, 4] { { { 000, 001, 002, 003 }, { 010, 011, 012, 013 }, { 020, 021, 022, 023 }, }, { { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 }, } }; str = CSharpObjectFormatter.Instance.FormatObject(a, s_inline); Assert.Equal("int[2, 3, 4] { { { 0, 1, 2, 3 }, { 10, 11, 12, 13 }, { 20, 21, 22, 23 } }, { { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 } } }", str); str = CSharpObjectFormatter.Instance.FormatObject(a, s_memberList); AssertMembers(str, "int[2, 3, 4]", "{ { 0, 1, 2, 3 }, { 10, 11, 12, 13 }, { 20, 21, 22, 23 } }", "{ { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 } }" ); int[][,][,,,] obj = new int[2][,][,,,]; obj[0] = new int[1, 2][,,,]; obj[0][0, 0] = new int[1, 2, 3, 4]; str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("int[2][,][,,,] { int[1, 2][,,,] { { int[1, 2, 3, 4] { { { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } } } }, null } }, null }", str); Array x = Array.CreateInstance(typeof(Object), lengths: new int[] { 2, 3 }, lowerBounds: new int[] { 2, 9 }); str = CSharpObjectFormatter.Instance.FormatObject(x, s_inline); Assert.Equal("object[2..4, 9..12] { { null, null, null }, { null, null, null } }", str); Array y = Array.CreateInstance(typeof(Object), lengths: new int[] { 1, 1 }, lowerBounds: new int[] { 0, 0 }); str = CSharpObjectFormatter.Instance.FormatObject(y, s_inline); Assert.Equal("object[1, 1] { { null } }", str); Array z = Array.CreateInstance(typeof(Object), lengths: new int[] { 0, 0 }, lowerBounds: new int[] { 0, 0 }); str = CSharpObjectFormatter.Instance.FormatObject(z, s_inline); Assert.Equal("object[0, 0] { }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_IEnumerable() { string str; object obj; obj = Enumerable.Range(0, 10); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("RangeIterator { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_IEnumerable_Exception() { string str; object obj; obj = Enumerable.Range(0, 10).Where(i => { if (i == 5) throw new Exception("xxx"); return i < 7; }); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("Enumerable.WhereEnumerableIterator<int> { 0, 1, 2, 3, 4, !<Exception> ... }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_IDictionary() { string str; object obj; obj = new ThrowingDictionary(throwAt: -1); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ThrowingDictionary(10) { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 4 } }", str); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "ThrowingDictionary(10)", "{ 1, 1 }", "{ 2, 2 }", "{ 3, 3 }", "{ 4, 4 }" ); } [Fact] public void DebuggerProxy_FrameworkTypes_IDictionary_Exception() { string str; object obj; obj = new ThrowingDictionary(throwAt: 3); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ThrowingDictionary(10) { { 1, 1 }, { 2, 2 }, !<Exception> ... }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ArrayList() { var obj = new ArrayList { 1, 2, true, "foo" }; var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ArrayList(4) { 1, 2, true, \"foo\" }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_BitArray() { // BitArray doesn't have debugger proxy/display var obj = new System.Collections.BitArray(new int[] { 1 }); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("BitArray(32) { true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Hashtable() { var obj = new Hashtable { { new byte[] { 1, 2 }, new[] { 1,2,3 } }, }; var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "Hashtable(1)", "{ byte[2] { 1, 2 }, int[3] { 1, 2, 3 } }" ); } [Fact] public void DebuggerProxy_FrameworkTypes_Queue() { var obj = new Queue(); obj.Enqueue(1); obj.Enqueue(2); obj.Enqueue(3); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("Queue(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Stack() { var obj = new Stack(); obj.Push(1); obj.Push(2); obj.Push(3); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("Stack(3) { 3, 2, 1 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Dictionary() { var obj = new Dictionary<string, int> { { "x", 1 }, }; var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "Dictionary<string, int>(1)", "{ \"x\", 1 }" ); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("Dictionary<string, int>(1) { { \"x\", 1 } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_KeyValuePair() { var obj = new KeyValuePair<int, string>(1, "x"); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("KeyValuePair<int, string> { 1, \"x\" }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_List() { var obj = new List<object> { 1, 2, 'c' }; var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("List<object>(3) { 1, 2, 'c' }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_LinkedList() { var obj = new LinkedList<int>(); obj.AddLast(1); obj.AddLast(2); obj.AddLast(3); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("LinkedList<int>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedList() { SortedList obj = new SortedList(); obj.Add(3, 4); obj.Add(1, 5); obj.Add(2, 6); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("SortedList(3) { { 1, 5 }, { 2, 6 }, { 3, 4 } }", str); obj = new SortedList(); obj.Add(new[] { 3 }, new int[] { 4 }); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("SortedList(1) { { int[1] { 3 }, int[1] { 4 } } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedDictionary() { var obj = new SortedDictionary<int, int>(); obj.Add(1, 0x1a); obj.Add(3, 0x3c); obj.Add(2, 0x2b); var str = CSharpObjectFormatter.Instance. FormatObject(obj, new ObjectFormattingOptions(useHexadecimalNumbers: true, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal("SortedDictionary<int, int>(3) { { 0x00000001, 0x0000001a }, { 0x00000002, 0x0000002b }, { 0x00000003, 0x0000003c } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_HashSet() { var obj = new HashSet<int>(); obj.Add(1); obj.Add(2); // HashSet doesn't implement ICollection (it only implements ICollection<T>) so we don't call Count, // instead a DebuggerDisplay.Value is used. var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("HashSet<int>(Count = 2) { 1, 2 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedSet() { var obj = new SortedSet<int>(); obj.Add(1); obj.Add(2); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("SortedSet<int>(2) { 1, 2 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentDictionary() { var obj = new ConcurrentDictionary<string, int>(); obj.AddOrUpdate("x", 1, (k, v) => v); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ConcurrentDictionary<string, int>(1) { { \"x\", 1 } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentQueue() { var obj = new ConcurrentQueue<object>(); obj.Enqueue(1); obj.Enqueue(2); obj.Enqueue(3); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ConcurrentQueue<object>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentStack() { var obj = new ConcurrentStack<object>(); obj.Push(1); obj.Push(2); obj.Push(3); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ConcurrentStack<object>(3) { 3, 2, 1 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_BlockingCollection() { var obj = new BlockingCollection<int>(); obj.Add(1); obj.Add(2, new CancellationToken()); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("BlockingCollection<int>(2) { 1, 2 }", str); } // TODO(tomat): this only works with System.dll file version 30319.16644 (Win8 build) //[Fact] //public void DebuggerProxy_FrameworkTypes_ConcurrentBag() //{ // var obj = new ConcurrentBag<int>(); // obj.Add(1); // var str = ObjectFormatter.Instance.FormatObject(obj, quoteStrings: true, memberFormat: MemberDisplayFormat.Inline); // Assert.Equal("ConcurrentBag<int>(1) { 1 }", str); //} [Fact] public void DebuggerProxy_FrameworkTypes_ReadOnlyCollection() { var obj = new System.Collections.ObjectModel.ReadOnlyCollection<int>(new[] { 1, 2, 3 }); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ReadOnlyCollection<int>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Lazy() { var obj = new Lazy<int[]>(() => new int[] { 1, 2 }, LazyThreadSafetyMode.None); // Lazy<T> has both DebuggerDisplay and DebuggerProxy attributes and both display the same information. var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=false, IsValueFaulted=false, Value=null) { IsValueCreated=false, IsValueFaulted=false, Mode=None, Value=null }", str); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=false, IsValueFaulted=false, Value=null)", "IsValueCreated: false", "IsValueFaulted: false", "Mode: None", "Value: null" ); Assert.NotNull(obj.Value); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=true, IsValueFaulted=false, Value=int[2] { 1, 2 }) { IsValueCreated=true, IsValueFaulted=false, Mode=None, Value=int[2] { 1, 2 } }", str); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=true, IsValueFaulted=false, Value=int[2] { 1, 2 })", "IsValueCreated: true", "IsValueFaulted: false", "Mode: None", "Value: int[2] { 1, 2 }" ); } public void TaskMethod() { } [Fact] public void DebuggerProxy_FrameworkTypes_Task() { var obj = new System.Threading.Tasks.Task(TaskMethod); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal( @"Task(Id = *, Status = Created, Method = ""Void TaskMethod()"") { AsyncState=null, CancellationPending=false, CreationOptions=None, Exception=null, Id=*, Status=Created }", FilterDisplayString(str)); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(FilterDisplayString(str), @"Task(Id = *, Status = Created, Method = ""Void TaskMethod()"")", "AsyncState: null", "CancellationPending: false", "CreationOptions: None", "Exception: null", "Id: *", "Status: Created" ); } [Fact] public void DebuggerProxy_FrameworkTypes_SpinLock() { var obj = new SpinLock(); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("SpinLock(IsHeld = false) { IsHeld=false, IsHeldByCurrentThread=false, OwnerThreadID=0 }", str); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "SpinLock(IsHeld = false)", "IsHeld: false", "IsHeldByCurrentThread: false", "OwnerThreadID: 0" ); } [Fact] public void DebuggerProxy_DiagnosticBag() { var obj = new DiagnosticBag(); obj.Add(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_AbstractAndExtern, "bar"), NoLocation.Singleton); obj.Add(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_BadExternIdentifier, "foo"), NoLocation.Singleton); using (new EnsureEnglishUICulture()) { var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("DiagnosticBag(Count = 2) { =error CS0180: 'bar' cannot be both extern and abstract, =error CS1679: Invalid extern alias for '/reference'; 'foo' is not a valid identifier }", str); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "DiagnosticBag(Count = 2)", ": error CS0180: 'bar' cannot be both extern and abstract", ": error CS1679: Invalid extern alias for '/reference'; 'foo' is not a valid identifier" ); } } [Fact] public void DebuggerProxy_ArrayBuilder() { var obj = new ArrayBuilder<int>(); obj.AddRange(new[] { 1, 2, 3, 4, 5 }); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ArrayBuilder<int>(Count = 5) { 1, 2, 3, 4, 5 }", str); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "ArrayBuilder<int>(Count = 5)", "1", "2", "3", "4", "5" ); } [Fact] public void VBBackingFields_DebuggerBrowsable() { string source = @" Imports System Class C Public WithEvents WE As C Public Event E As Action Public Property A As Integer End Class "; var compilation = VB.VisualBasicCompilation.Create( "foo", new[] { VB.VisualBasicSyntaxTree.ParseText(source) }, new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly) }, new VB.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Debug)); Assembly a; using (var stream = new MemoryStream()) { var result = compilation.Emit(stream); a = Assembly.Load(stream.ToArray()); } var c = a.GetType("C"); var obj = Activator.CreateInstance(c); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "C", "A: 0", "WE: null" ); var attrsA = c.GetField("_A", BindingFlags.Instance | BindingFlags.NonPublic).GetCustomAttributes(typeof(DebuggerBrowsableAttribute), true); var attrsWE = c.GetField("_WE", BindingFlags.Instance | BindingFlags.NonPublic).GetCustomAttributes(typeof(DebuggerBrowsableAttribute), true); var attrsE = c.GetField("EEvent", BindingFlags.Instance | BindingFlags.NonPublic).GetCustomAttributes(typeof(DebuggerBrowsableAttribute), true); Assert.Equal(1, attrsA.Length); Assert.Equal(1, attrsWE.Length); Assert.Equal(1, attrsE.Length); } } }
using System; using Newtonsoft.Json; namespace CurrencyCloud.Entity { public sealed class ReportParameters { [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public string Description { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public string Currency { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public decimal? AmountFrom { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public decimal? AmountTo { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public string Status { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public DateTime? PaymentDateFrom { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public DateTime? PaymentDateTo { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public DateTime? TransferredAtFrom { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public DateTime? TransferredAtTo { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public DateTime? CreatedAtFrom { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public DateTime? CreatedAtTo { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public DateTime? UpdatedAtFrom { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public DateTime? UpdatedAtTo { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public string BeneficiaryId { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public string ConversionId { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public bool? WithDeleted { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public string PaymentGroupId { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public string UniqueRequestId { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public string Scope { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public string BuyCurrency { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public string SellCurrency { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public decimal? ClientBuyAmountFrom { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public decimal? ClientBuyAmountTo { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public decimal? ClientSellAmountFrom { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public decimal? ClientSellAmountTo { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public decimal? PartnerBuyAmountFrom { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public decimal? PartnerBuyAmountTo { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public decimal? PartnerSellAmountFrom { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public decimal? PartnerSellAmountTo { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public string ClientStatus { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public DateTime? ConversionDateFrom { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public DateTime? ConversionDateTo { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public DateTime? SettlementDateFrom { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [Param] public DateTime? SettlementDateTo { get; set; } public override bool Equals(object obj) { if (!(obj is ReportParameters)) { return false; } var reportParameters = obj as ReportParameters; return Description == reportParameters.Description && Currency == reportParameters.Currency && AmountFrom == reportParameters.AmountFrom && AmountTo == reportParameters.AmountTo && Status == reportParameters.Status && PaymentDateFrom == reportParameters.PaymentDateFrom && PaymentDateTo == reportParameters.PaymentDateTo && TransferredAtFrom == reportParameters.TransferredAtFrom && TransferredAtTo == reportParameters.TransferredAtTo && CreatedAtFrom == reportParameters.CreatedAtFrom && CreatedAtTo == reportParameters.CreatedAtTo && UpdatedAtFrom == reportParameters.UpdatedAtFrom && UpdatedAtTo == reportParameters.UpdatedAtTo && BeneficiaryId == reportParameters.BeneficiaryId && ConversionId == reportParameters.ConversionId && WithDeleted == reportParameters.WithDeleted && PaymentGroupId == reportParameters.PaymentGroupId && UniqueRequestId == reportParameters.UniqueRequestId && Scope == reportParameters.Scope && BuyCurrency == reportParameters.BuyCurrency && SellCurrency == reportParameters.SellCurrency && ClientBuyAmountFrom == reportParameters.ClientBuyAmountFrom && ClientBuyAmountTo == reportParameters.ClientBuyAmountTo && ClientSellAmountFrom == reportParameters.ClientSellAmountFrom && ClientSellAmountTo == reportParameters.ClientSellAmountTo && PartnerBuyAmountFrom == reportParameters.PartnerBuyAmountFrom && PartnerBuyAmountTo == reportParameters.PartnerBuyAmountTo && PartnerSellAmountFrom == reportParameters.PartnerSellAmountFrom && PartnerSellAmountTo == reportParameters.PartnerSellAmountTo && ClientStatus == reportParameters.ClientStatus && ConversionDateFrom == reportParameters.ConversionDateFrom && ConversionDateTo == reportParameters.ConversionDateTo && SettlementDateFrom == reportParameters.SettlementDateFrom && SettlementDateTo == reportParameters.SettlementDateTo; } public override int GetHashCode() { unchecked { var hashCode = (Description != null ? Description.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Currency != null ? Currency.GetHashCode() : 0); hashCode = (hashCode * 397) ^ AmountFrom.GetHashCode(); hashCode = (hashCode * 397) ^ AmountTo.GetHashCode(); hashCode = (hashCode * 397) ^ (Status != null ? Status.GetHashCode() : 0); hashCode = (hashCode * 397) ^ PaymentDateFrom.GetHashCode(); hashCode = (hashCode * 397) ^ PaymentDateTo.GetHashCode(); hashCode = (hashCode * 397) ^ TransferredAtFrom.GetHashCode(); hashCode = (hashCode * 397) ^ TransferredAtTo.GetHashCode(); hashCode = (hashCode * 397) ^ CreatedAtFrom.GetHashCode(); hashCode = (hashCode * 397) ^ CreatedAtTo.GetHashCode(); hashCode = (hashCode * 397) ^ UpdatedAtFrom.GetHashCode(); hashCode = (hashCode * 397) ^ UpdatedAtTo.GetHashCode(); hashCode = (hashCode * 397) ^ (BeneficiaryId != null ? BeneficiaryId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (ConversionId != null ? ConversionId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ WithDeleted.GetHashCode(); hashCode = (hashCode * 397) ^ (PaymentGroupId != null ? PaymentGroupId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (UniqueRequestId != null ? UniqueRequestId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Scope != null ? Scope.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (BuyCurrency != null ? BuyCurrency.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (SellCurrency != null ? SellCurrency.GetHashCode() : 0); hashCode = (hashCode * 397) ^ ClientBuyAmountFrom.GetHashCode(); hashCode = (hashCode * 397) ^ ClientBuyAmountTo.GetHashCode(); hashCode = (hashCode * 397) ^ ClientSellAmountFrom.GetHashCode(); hashCode = (hashCode * 397) ^ ClientSellAmountTo.GetHashCode(); hashCode = (hashCode * 397) ^ PartnerBuyAmountFrom.GetHashCode(); hashCode = (hashCode * 397) ^ PartnerBuyAmountTo.GetHashCode(); hashCode = (hashCode * 397) ^ PartnerSellAmountFrom.GetHashCode(); hashCode = (hashCode * 397) ^ PartnerSellAmountTo.GetHashCode(); hashCode = (hashCode * 397) ^ (ClientStatus != null ? ClientStatus.GetHashCode() : 0); hashCode = (hashCode * 397) ^ ConversionDateFrom.GetHashCode(); hashCode = (hashCode * 397) ^ ConversionDateTo.GetHashCode(); hashCode = (hashCode * 397) ^ SettlementDateFrom.GetHashCode(); hashCode = (hashCode * 397) ^ SettlementDateTo.GetHashCode(); return hashCode; } } } }
// // Fleece_native.cs // // Copyright (c) 2021 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.Linq; using System.Runtime.InteropServices; using LiteCore.Util; namespace LiteCore.Interop { internal unsafe static partial class Native { [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLDoc* FLDoc_FromResultData(FLSliceResult data, FLTrust x, FLSharedKeys* shared, FLSlice externData); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLDoc_Release(FLDoc* x); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLValue* FLDoc_GetRoot(FLDoc* x); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLSharedKeys* FLDoc_GetSharedKeys(FLDoc* x); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLDoc* FLValue_FindDoc(FLValue* value); public static FLValue* FLValue_FromData(byte[] data, FLTrust x) { fixed(byte *data_ = data) { return NativeRaw.FLValue_FromData(new FLSlice(data_, (ulong)data.Length), x); } } public static string FLValue_ToJSON(FLValue* value) { using(var retVal = NativeRaw.FLValue_ToJSON(value)) { return ((FLSlice)retVal).CreateString(); } } public static string FLValue_ToJSONX(FLValue* v, bool json5, bool canonicalForm) { using(var retVal = NativeRaw.FLValue_ToJSONX(v, json5, canonicalForm)) { return ((FLSlice)retVal).CreateString(); } } public static string FLJSON5_ToJSON(string json5, FLSlice* outErrorMessage, UIntPtr* outErrPos, FLError* err) { using(var json5_ = new C4String(json5)) { using(var retVal = NativeRaw.FLJSON5_ToJSON((FLSlice)json5_.AsFLSlice(), outErrorMessage, outErrPos, err)) { return ((FLSlice)retVal).CreateString(); } } } [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLValueType FLValue_GetType(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLValue_IsEqual(FLValue* value1, FLValue* value2); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLValue_IsInteger(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLValue_IsUnsigned(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLValue_IsDouble(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLValue_AsBool(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern long FLValue_AsInt(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern ulong FLValue_AsUnsigned(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern float FLValue_AsFloat(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern double FLValue_AsDouble(FLValue* value); public static string FLValue_AsString(FLValue* value) { return NativeRaw.FLValue_AsString(value).CreateString(); } public static byte[] FLValue_AsData(FLValue* value) { return (NativeRaw.FLValue_AsData(value)).ToArrayFast(); } [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLArray* FLValue_AsArray(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLDict* FLValue_AsDict(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLValue_Release(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern uint FLArray_Count(FLArray* array); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLValue* FLArray_Get(FLArray* array, uint index); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLArrayIterator_Begin(FLArray* array, FLArrayIterator* i); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLValue* FLArrayIterator_GetValue(FLArrayIterator* i); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLValue* FLArrayIterator_GetValueAt(FLArrayIterator* i, uint offset); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern uint FLArrayIterator_GetCount(FLArrayIterator* i); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLArrayIterator_Next(FLArrayIterator* i); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern uint FLDict_Count(FLDict* dict); public static FLValue* FLDict_Get(FLDict* dict, byte[] keyString) { fixed(byte *keyString_ = keyString) { return NativeRaw.FLDict_Get(dict, new FLSlice(keyString_, (ulong)keyString.Length)); } } [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLDictIterator_Begin(FLDict* dict, FLDictIterator* i); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLValue* FLDictIterator_GetKey(FLDictIterator* i); public static string FLDictIterator_GetKeyString(FLDictIterator* i) { return NativeRaw.FLDictIterator_GetKeyString(i).CreateString(); } [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLValue* FLDictIterator_GetValue(FLDictIterator* i); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLDictIterator_Next(FLDictIterator* i); // Note: Allocates unmanaged heap memory; should only be used with constants public static FLDictKey FLDictKey_Init(string str) { return NativeRaw.FLDictKey_Init(FLSlice.Constant(str)); } public static string FLDictKey_GetString(FLDictKey* dictKey) { return NativeRaw.FLDictKey_GetString(dictKey).CreateString(); } [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLValue* FLDict_GetWithKey(FLDict* dict, FLDictKey* dictKey); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLEncoder* FLEncoder_New(); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLEncoder_Free(FLEncoder* encoder); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLEncoder_SetExtraInfo(FLEncoder* encoder, void* info); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void* FLEncoder_GetExtraInfo(FLEncoder* encoder); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLEncoder_Reset(FLEncoder* encoder); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLEncoder_WriteNull(FLEncoder* encoder); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLEncoder_WriteBool(FLEncoder* encoder, [MarshalAs(UnmanagedType.U1)]bool b); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLEncoder_WriteInt(FLEncoder* encoder, long l); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLEncoder_WriteUInt(FLEncoder* encoder, ulong u); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLEncoder_WriteFloat(FLEncoder* encoder, float f); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLEncoder_WriteDouble(FLEncoder* encoder, double d); public static bool FLEncoder_WriteString(FLEncoder* encoder, string str) { using(var str_ = new C4String(str)) { return NativeRaw.FLEncoder_WriteString(encoder, (FLSlice)str_.AsFLSlice()); } } public static bool FLEncoder_WriteData(FLEncoder* encoder, byte[] slice) { fixed(byte *slice_ = slice) { return NativeRaw.FLEncoder_WriteData(encoder, new FLSlice(slice_, (ulong)slice.Length)); } } public static bool FLEncoder_BeginArray(FLEncoder* encoder, ulong reserveCount) { return NativeRaw.FLEncoder_BeginArray(encoder, (UIntPtr)reserveCount); } [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLEncoder_EndArray(FLEncoder* encoder); public static bool FLEncoder_BeginDict(FLEncoder* encoder, ulong reserveCount) { return NativeRaw.FLEncoder_BeginDict(encoder, (UIntPtr)reserveCount); } public static bool FLEncoder_WriteKey(FLEncoder* encoder, string str) { using(var str_ = new C4String(str)) { return NativeRaw.FLEncoder_WriteKey(encoder, (FLSlice)str_.AsFLSlice()); } } [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLEncoder_EndDict(FLEncoder* encoder); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLEncoder_WriteValue(FLEncoder* encoder, FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLDoc* FLEncoder_FinishDoc(FLEncoder* encoder, FLError* outError); public static byte[] FLEncoder_Finish(FLEncoder* e, FLError* outError) { using(var retVal = NativeRaw.FLEncoder_Finish(e, outError)) { return ((FLSlice)retVal).ToArrayFast(); } } [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLSlot_SetNull(FLSlot* x); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLSlot_SetBool(FLSlot* x, [MarshalAs(UnmanagedType.U1)]bool b); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLSlot_SetInt(FLSlot* x, long l); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLSlot_SetUInt(FLSlot* x, ulong u); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLSlot_SetFloat(FLSlot* x, float f); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLSlot_SetDouble(FLSlot* x, double d); public static void FLSlot_SetString(FLSlot* x, string str) { using(var str_ = new C4String(str)) { NativeRaw.FLSlot_SetString(x, (FLSlice)str_.AsFLSlice()); } } [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLSlot_SetValue(FLSlot* x, FLValue* value); } internal unsafe static partial class NativeRaw { [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLValue* FLValue_FromData(FLSlice data, FLTrust x); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLSliceResult FLData_ConvertJSON(FLSlice json, FLError* outError); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLSliceResult FLValue_ToJSON(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLSliceResult FLValue_ToJSONX(FLValue* v, [MarshalAs(UnmanagedType.U1)]bool json5, [MarshalAs(UnmanagedType.U1)]bool canonicalForm); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLSliceResult FLJSON5_ToJSON(FLSlice json5, FLSlice* outErrorMessage, UIntPtr* outErrorPos, FLError* outError); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLSlice FLValue_AsString(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLSlice FLValue_AsData(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLSliceResult FLValue_ToString(FLValue* value); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLValue* FLDict_Get(FLDict* dict, FLSlice keyString); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLSlice FLDictIterator_GetKeyString(FLDictIterator* i); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLDictKey FLDictKey_Init(FLSlice @string); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLSlice FLDictKey_GetString(FLDictKey* dictKey); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLMutableDict_Remove(FLMutableDict* x, FLSlice key); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLMutableArray* FLMutableDict_GetMutableArray(FLMutableDict* x, FLSlice key); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLMutableDict* FLMutableDict_GetMutableDict(FLMutableDict* x, FLSlice key); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLEncoder_WriteString(FLEncoder* encoder, FLSlice str); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLEncoder_WriteData(FLEncoder* encoder, FLSlice slice); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLEncoder_BeginArray(FLEncoder* encoder, UIntPtr reserveCount); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLEncoder_BeginDict(FLEncoder* encoder, UIntPtr reserveCount); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool FLEncoder_WriteKey(FLEncoder* encoder, FLSlice str); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLSliceResult FLEncoder_Finish(FLEncoder* e, FLError* outError); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern FLSlot* FLMutableDict_Set(FLMutableDict* FL_, FLSlice key); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLSlot_SetString(FLSlot* x, FLSlice str); [DllImport(Constants.DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void FLSlot_SetData(FLSlot* x, FLSlice slice); } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// Organization: Sports team. /// </summary> public class SportsTeam_Core : TypeCore, IOrganization { public SportsTeam_Core() { this._TypeId = 249; this._Id = "SportsTeam"; this._Schema_Org_Url = "http://schema.org/SportsTeam"; string label = ""; GetLabel(out label, "SportsTeam", typeof(SportsTeam_Core)); this._Label = label; this._Ancestors = new int[]{266,193}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{193}; this._Properties = new int[]{67,108,143,229,5,10,47,75,77,85,91,94,95,115,130,137,199,196}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
/******************************************************************************* * Copyright 2010 University of Southern California * * 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. * * This code was developed as part of the Strabo map processing project * by the Spatial Sciences Institute and by the Information Integration Group * at the Information Sciences Institute of the University of Southern * California. For more information, publications, and related projects, * please see: http://spatial-computing.github.io/ ******************************************************************************/ using System; using System.IO; using System.Collections.Generic; using System.Collections; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Threading; using Emgu.CV; using Emgu.CV.CvEnum; using Emgu.CV.Features2D; using Emgu.CV.Structure; using Emgu.CV.Util; //using Emgu.CV.GPU; using Emgu.Util; namespace Strabo.Core.SymbolRecognition { public class DrawMatches { public Tuple<Image<Bgr, byte>, HomographyMatrix> DrawHomography(Image<Gray, byte> model, Image<Gray, byte> observed, double uniquenessThreshold) { HomographyMatrix homography = null; Image<Bgr, Byte> result = observed.Convert<Bgr, byte>(); SURFDetector surfCPU = new SURFDetector(500, false); VectorOfKeyPoint modelKeyPoints; VectorOfKeyPoint observedKeyPoints; Matrix<int> indices; Matrix<byte> mask; int k = 2; modelKeyPoints = surfCPU.DetectKeyPointsRaw(model, null); // Extract features from the object image Matrix<float> modelDescriptors = surfCPU.ComputeDescriptorsRaw(model, null, modelKeyPoints); observedKeyPoints = surfCPU.DetectKeyPointsRaw(observed, null); // Extract features from the observed image if (modelKeyPoints.Size <= 0) { throw new System.ArgumentException("Can't find any keypoints in your model image!"); } if (observedKeyPoints.Size > 0) { Matrix<float> observedDescriptors = surfCPU.ComputeDescriptorsRaw (observed, null, observedKeyPoints); BruteForceMatcher<float> matcher = new BruteForceMatcher<float> (DistanceType.L2); matcher.Add (modelDescriptors); indices = new Matrix<int> (observedDescriptors.Rows, k); using (Matrix<float> dist = new Matrix<float>(observedDescriptors.Rows, k)) { matcher.KnnMatch (observedDescriptors, indices, dist, k, null); mask = new Matrix<byte> (dist.Rows, 1); mask.SetValue (255); Features2DToolbox.VoteForUniqueness (dist, uniquenessThreshold, mask); } int nonZeroCount = CvInvoke.cvCountNonZero (mask); if (nonZeroCount >= 10) { nonZeroCount = Features2DToolbox.VoteForSizeAndOrientation (modelKeyPoints, observedKeyPoints, indices, mask, 1.5, 20); if (nonZeroCount >= 10) homography = Features2DToolbox.GetHomographyMatrixFromMatchedFeatures (modelKeyPoints, observedKeyPoints, indices, mask, 2); } result = Features2DToolbox.DrawMatches(model, modelKeyPoints, observed, observedKeyPoints, indices, new Bgr(255, 255, 255), new Bgr(255, 255, 255), mask, Features2DToolbox.KeypointDrawType.DEFAULT); } return new Tuple<Image<Bgr, byte>, HomographyMatrix>(result, homography); } public Tuple<Image<Bgr, Byte>, float[]> Draw(Image<Gray, byte> modelImage, Image<Gray, byte> observedImage, Image<Bgr, byte> modifiedImage, int x0, int y0, string path, string topic, int counter, TextWriter log) { Rectangle recShift = new Rectangle(0, 0, 0, 0); double bpScore = -1; Stopwatch watch = Stopwatch.StartNew(); Image<Bgr, Byte> result = observedImage.Convert<Bgr, byte>(); TextWriter capturedLog = File.AppendText(path + topic + "/capturedLog.txt"); Tuple<Image<Bgr, byte>, HomographyMatrix> homo1 = DrawHomography(modelImage, observedImage, 1); if (homo1.Item2 != null) { Bitmap bD = homo1.Item1.ToBitmap(); using (Graphics gD = Graphics.FromImage(bD)) { (observedImage.Sobel(1, 0, 3).AbsDiff(new Gray(0))+observedImage.Sobel(0, 1, 3).AbsDiff(new Gray(0))).Save(string.Format("{0}{1}/captured/oedge{2}.jpg", path, topic, counter.ToString("D5"))); Tuple<Image<Bgr, byte>, Rectangle, double> tup = btnCalcBackProjectPatch(modelImage, observedImage, homo1.Item1); Bitmap bS = tup.Item1.ToBitmap(); Rectangle rec = tup.Item2; gD.DrawImage(bS, new Rectangle(observedImage.Width+1, modelImage.Height+1, modelImage.Width, modelImage.Height), new Rectangle(0, 0, modelImage.Width, modelImage.Height), GraphicsUnit.Pixel); result = new Image<Bgr, byte>(bD); capturedLog.Write("\n#" + counter.ToString("D5")); bpScore = tup.Item3; if (bpScore > 0.7) { result.Draw(rec, new Bgr(Color.Red), 2); recShift = new Rectangle(new Point(x0 + rec.X, y0 + rec.Y), rec.Size); capturedLog.Write("\t" + tup.Item3.ToString()); } result.Save(string.Format("{0}{1}/captured/{2}.jpg", path, topic, counter.ToString("D5"))); } } result.Save(string.Format("{0}{1}/out/{2}.jpg", path, topic, counter.ToString("D5"))); capturedLog.Close(); watch.Stop(); Console.WriteLine(watch.Elapsed); if (recShift.Width > 0 && bpScore > 0) { return new Tuple<Image<Bgr, byte>, float[]> (modifiedImage, new float[] {recShift.X, recShift.Y, (float)bpScore}); } else { return new Tuple<Image<Bgr, byte>, float[]> (modifiedImage, new float[] {0, 0, 0}); } } private Tuple<Image<Bgr, byte>, Rectangle, double> btnCalcBackProjectPatch(Image<Gray, byte> model, Image<Gray, byte> observed, Image<Bgr, byte> result) { Stopwatch sw = new Stopwatch(); sw.Start(); Image<Bgr, Byte> imageSource = observed.Convert<Bgr, byte>(); double scale = GetScale(); Image<Bgr, Byte> imageSource2 = imageSource.Resize(scale, INTER.CV_INTER_LINEAR); Image<Bgr, Byte> imageTarget = model.Convert<Bgr, byte>(); Image<Bgr, Byte> imageTarget2 = imageTarget.Resize(scale, INTER.CV_INTER_LINEAR); Image<Gray, Single> imageDest = null; int edgeX = imageTarget2.Size.Width; int edgeY = imageTarget2.Size.Height; Size patchSize = new Size(edgeX, edgeY); string colorSpace = "Gray"; double normalizeFactor = 1d; Image<Gray, Byte>[] imagesSource; int[] bins; RangeF[] ranges; string[] captions; Color[] colors; // Get all the color bins from the source images. GetImagesBinsAndRanges(imageSource2, colorSpace, out imagesSource, out bins, out ranges, out captions, out colors); // Histogram calculation. DenseHistogram histTarget = CalcHist(imageTarget2.Bitmap); // Backproject compare method. HISTOGRAM_COMP_METHOD compareMethod = GetHistogramCompareMethod(); imageDest = BackProjectPatch<Byte>(imagesSource, patchSize, histTarget, compareMethod, (float)normalizeFactor); // Best-match value. double bestValue; Point bestPoint; FindBestMatchPointAndValue(imageDest, compareMethod, out bestValue, out bestPoint); // Draw a rectangle with the same size of the template at the best-match point Rectangle rect = new Rectangle(bestPoint, patchSize); result = imageDest.Convert<Bgr, byte>(); sw.Stop(); // Disposal imageSource.Dispose(); imageSource2.Dispose(); imageTarget.Dispose(); imageTarget2.Dispose(); if (imageDest != null) imageDest.Dispose(); foreach (Image<Gray, Byte> image in imagesSource) image.Dispose(); histTarget.Dispose(); return new Tuple<Image<Bgr, byte>, Rectangle, double>(result, rect, bestValue); } // Histogram calculation. private DenseHistogram CalcHist(Image image) { Image<Bgr, Byte> imageSource = new Image<Bgr, byte>((Bitmap)image); string colorSpace = "Gray"; Image<Gray, Byte>[] images; int[] bins; RangeF[] ranges; string[] captions; Color[] colors; // Get all the color bins from the source images. GetImagesBinsAndRanges(imageSource, colorSpace, out images, out bins, out ranges, out captions, out colors); SetBins(ref bins); // Histogram calculation. DenseHistogram hist = new DenseHistogram(bins, ranges); hist.Calculate<Byte>(images, false, null); return hist; } // Histogram compare method. private HISTOGRAM_COMP_METHOD GetHistogramCompareMethod() { HISTOGRAM_COMP_METHOD compareMethod = HISTOGRAM_COMP_METHOD.CV_COMP_CORREL; compareMethod = HISTOGRAM_COMP_METHOD.CV_COMP_CORREL; return compareMethod; } // Compares histogram over each possible rectangular patch of the specified size in the input images, and stores the results to the output map dst. // Destination back projection image of the same type as the source images public Image<Gray, Single> BackProjectPatch<TDepth>(Image<Gray, TDepth>[] srcs, Size patchSize, DenseHistogram hist, HISTOGRAM_COMP_METHOD method, double factor) where TDepth : new() { Debug.Assert(srcs.Length == hist.Dimension, "The number of the source image and the dimension of the histogram must be the same."); IntPtr[] imgPtrs = Array.ConvertAll<Image<Gray, TDepth>, IntPtr>( srcs, delegate(Image<Gray, TDepth> img) { return img.Ptr; }); Size size = srcs[0].Size; size.Width = size.Width - patchSize.Width + 1; size.Height = size.Height - patchSize.Height + 1; Image<Gray, Single> res = new Image<Gray, float>(size); CvInvoke.cvCalcBackProjectPatch(imgPtrs, res.Ptr, patchSize, hist.Ptr, method, factor); return res; } public void GetImagesBinsAndRanges(Image<Bgr, Byte> imageSource, string colorSpace, out Image<Gray, Byte>[] images, out int[] bins, out RangeF[] ranges,out string[] captions,out Color[] colors) { images = null; bins = null; ranges = null; captions = null; colors = null; int channels = 0; Image<Gray, Byte> imageGray = null; Image<Gray, Byte> imageRed = null; Image<Gray, Byte> imageGreen = null; Image<Gray, Byte> imageBlue = null; Image<Gray, Byte> imageHue = null; Image<Gray, Byte> imageSaturation = null; Image<Gray, Byte> imageBrightness = null; if (colorSpace == "Gray") { channels = 1; imageGray = imageSource.Convert<Gray, Byte>(); } else if (colorSpace == "Red") { channels = 1; Image<Gray, Byte>[] images2 = imageSource.Split(); imageRed = images2[2]; } else if (colorSpace == "RGB") { channels = 3; Image<Gray, Byte>[] images2 = imageSource.Split(); imageRed = images2[2]; imageGreen = images2[1]; imageBlue = images2[0]; } else if (colorSpace == "Hue") { channels = 1; Image<Hsv, Byte> imageHsv = imageSource.Convert<Hsv, Byte>(); Image<Gray, Byte>[] images2 = imageHsv.Split(); imageHue = images2[0]; } else if (colorSpace == "H&S") { channels = 2; Image<Hsv, Byte> imageHsv = imageSource.Convert<Hsv, Byte>(); Image<Gray, Byte>[] images2 = imageHsv.Split(); imageHue = images2[0]; imageSaturation = images2[1]; } else if (colorSpace == "HSV") { channels = 3; Image<Hsv, Byte> imageHsv = imageSource.Convert<Hsv, Byte>(); Image<Gray, Byte>[] images2 = imageHsv.Split(); imageHue = images2[0]; imageSaturation = images2[1]; imageBrightness = images2[2]; } if (channels > 0) { images = new Image<Gray, byte>[channels]; bins = new int[channels]; ranges = new RangeF[channels]; captions = new string[channels]; colors = new Color[channels]; int idx = 0; if (imageGray != null) { images[idx] = imageGray; bins[idx] = 256; ranges[idx] = new RangeF(0f, 255f); captions[idx] = "Gray"; colors[idx] = Color.Black; idx++; } if (imageRed != null) { images[idx] = imageRed; bins[idx] = 256; ranges[idx] = new RangeF(0f, 255f); captions[idx] = "Red"; colors[idx] = Color.Red; idx++; } if (imageGreen != null) { images[idx] = imageGreen; bins[idx] = 256; ranges[idx] = new RangeF(0f, 255f); captions[idx] = "Green"; colors[idx] = Color.Green; idx++; } if (imageBlue != null) { images[idx] = imageBlue; bins[idx] = 256; ranges[idx] = new RangeF(0f, 255f); captions[idx] = "Blue"; colors[idx] = Color.Blue; idx++; } if (imageHue != null) { images[idx] = imageHue; bins[idx] = 180; ranges[idx] = new RangeF(0f, 179f); captions[idx] = "Hue"; colors[idx] = Color.BurlyWood; idx++; } if (imageSaturation != null) { images[idx] = imageSaturation; bins[idx] = 256; ranges[idx] = new RangeF(0f, 255f); captions[idx] = "Saturation"; colors[idx] = Color.Chocolate; idx++; } if (imageBrightness != null) { images[idx] = imageBrightness; bins[idx] = 256; ranges[idx] = new RangeF(0f, 255f); captions[idx] = "Brightness"; colors[idx] = Color.Crimson; idx++; } } } private void SetBins(ref int[] bins) { int bin = 20; int.TryParse("25", out bin); for (int i = 0; i < bins.Length; i++) bins[i] = bin; } // Get the scaling factor. private double GetScale() { double scale = 1d; double.TryParse("1", out scale); return scale; } // Find the best match point and its value. private void FindBestMatchPointAndValue(Image<Gray, Single> image, HISTOGRAM_COMP_METHOD compareMethod, out double bestValue, out Point bestPoint) { bestValue = 0d; bestPoint = new Point(0, 0); double[] minValues, maxValues; Point[] minLocations, maxLocations; image.MinMax(out minValues, out maxValues, out minLocations, out maxLocations); if (compareMethod == HISTOGRAM_COMP_METHOD.CV_COMP_CHISQR || compareMethod == HISTOGRAM_COMP_METHOD.CV_COMP_BHATTACHARYYA) { bestValue = minValues[0]; bestPoint = minLocations[0]; } else { bestValue = maxValues[0]; bestPoint = maxLocations[0]; } } } }
/*************************************************************************** * Track.cs * * Copyright (C) 2006-2007 Alan McGovern * Authors: * Alan McGovern (alan.mcgovern@gmail.com) ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using System.Runtime.InteropServices; namespace Mtp { public class Track { internal TrackStruct trackStruct; private MtpDevice device; public uint FileId { get { return trackStruct.item_id; } } public string Album { get { return trackStruct.album; } set { trackStruct.album = value;} } public string Artist { get { return trackStruct.artist; } set { trackStruct.artist = value; } } public uint Bitrate { get { return trackStruct.bitrate; } } public ushort BitrateType { get { return trackStruct.bitratetype; } } public string ReleaseDate { get { return trackStruct.date; } set { trackStruct.date = value; } } public int Year { get { return ReleaseDate == null || ReleaseDate.Length < 4 ? 0 : Int32.Parse (ReleaseDate.Substring(0, 4)); } set { ReleaseDate = String.Format ("{0:0000}0101T0000.00", value); } } public uint Duration { get { return trackStruct.duration; } set { trackStruct.duration = value; } } public string FileName { get { return trackStruct.filename; } set { trackStruct.filename = value; } } public ulong FileSize { get { return trackStruct.filesize; } set { trackStruct.filesize = value; } } public FileType FileType { get { return trackStruct.filetype; } set { trackStruct.filetype = value; } } public string Genre { get { return trackStruct.genre; } set { trackStruct.genre = value; } } public ushort NoChannels { get { return trackStruct.nochannels; } set { trackStruct.nochannels = value; } } // 0 to 100 public ushort Rating { get { return trackStruct.rating; } set { if (value < 0 || value > 100) throw new ArgumentOutOfRangeException ("Rating", "Rating must be between zero and 100"); trackStruct.rating = value; } } public uint SampleRate { get { return trackStruct.samplerate; } set { trackStruct.samplerate = value; } } public string Title { get { return trackStruct.title; } set { trackStruct.title = value; } } public ushort TrackNumber { get { return trackStruct.tracknumber; } set { trackStruct.tracknumber = value; } } public uint WaveCodec { get { return trackStruct.wavecodec; } } public uint UseCount { get { return trackStruct.usecount; } set { trackStruct.usecount = value; } } public string Composer { get { return trackStruct.composer; } set { trackStruct.composer = value; } } public Track (string filename, ulong filesize) : this (filename, filesize, null) { } public Track (string filename, ulong filesize, MtpDevice device) : this (new TrackStruct (), device) { this.trackStruct.filename = filename; this.trackStruct.filesize = filesize; this.trackStruct.filetype = DetectFileType (this); } internal Track (TrackStruct track, MtpDevice device) { this.device = device; this.trackStruct = track; } public bool InFolder (Folder folder) { return InFolder (folder, false); } public bool InFolder (Folder folder, bool recursive) { if (folder == null) { return false; } bool is_parent = trackStruct.parent_id == folder.FolderId; if (is_parent || !recursive) { return is_parent; } return Folder.Find (device, trackStruct.parent_id).HasAncestor (folder); } public void Download (string path) { Download (path, null); } public void Download (string path, ProgressFunction callback) { if (String.IsNullOrEmpty (path)) throw new ArgumentException ("Cannot be null or empty", "path"); GetTrack (device.Handle, trackStruct.item_id, path, callback, IntPtr.Zero); } public void UpdateMetadata () { UpdateTrackMetadata (device.Handle, ref trackStruct); } private static FileType DetectFileType (Track track) { string ext = System.IO.Path.GetExtension (track.FileName); // Strip leading . if (ext.Length > 0) ext = ext.Substring (1, ext.Length - 1); // this is a hack; catch all m4(a|b|v|p) if (ext != null && ext.ToLower ().StartsWith ("m4")) ext = "mp4"; FileType type = (FileType) Enum.Parse (typeof(FileType), ext, true); //if (type == null) // return FileType.UNKNOWN; return type; } internal static void DestroyTrack (IntPtr track) { LIBMTP_destroy_track_t (track); } internal static void GetTrack (MtpDeviceHandle handle, uint trackId, string destPath, ProgressFunction callback, IntPtr data) { if (LIBMTP_Get_Track_To_File (handle, trackId, destPath, callback, data) != 0) { LibMtpException.CheckErrorStack (handle); throw new LibMtpException (ErrorCode.General, "Could not download track from the device"); } } internal static IntPtr GetTrackListing (MtpDeviceHandle handle, ProgressFunction function, IntPtr data) { return LIBMTP_Get_Tracklisting_With_Callback (handle, function, data); } internal static void SendTrack (MtpDeviceHandle handle, string path, ref TrackStruct metadata, ProgressFunction callback, IntPtr data) { if (LIBMTP_Send_Track_From_File (handle, path, ref metadata, callback, data) != 0) { LibMtpException.CheckErrorStack (handle); throw new LibMtpException (ErrorCode.General, "Could not upload the track"); } } internal static void UpdateTrackMetadata (MtpDeviceHandle handle, ref TrackStruct metadata) { if (LIBMTP_Update_Track_Metadata (handle, ref metadata) != 0) throw new LibMtpException (ErrorCode.General); } //[DllImport("libmtp.dll")] //private static extern IntPtr LIBMTP_new_track_t (); // LIBMTP_track_t * [DllImport("libmtp.dll")] private static extern void LIBMTP_destroy_track_t (IntPtr track); // LIBMTP_track_t * //[DllImport("libmtp.dll")] //private static extern IntPtr LIBMTP_Get_Tracklisting (MtpDeviceHandle handle); //LIBMTP_track_t * [DllImport("libmtp.dll")] private static extern IntPtr LIBMTP_Get_Tracklisting_With_Callback (MtpDeviceHandle handle, ProgressFunction callback, IntPtr data); // LIBMTP_track_t * //[DllImport("libmtp.dll")] //private static extern IntPtr LIBMTP_Get_Trackmetadata (MtpDeviceHandle handle, uint trackId); // LIBMTP_track_t * [DllImport("libmtp.dll")] private static extern int LIBMTP_Get_Track_To_File (MtpDeviceHandle handle, uint trackId, string path, ProgressFunction callback, IntPtr data); [DllImport("libmtp.dll")] private static extern int LIBMTP_Send_Track_From_File (MtpDeviceHandle handle, string path, ref TrackStruct track, ProgressFunction callback, IntPtr data); [DllImport("libmtp.dll")] private static extern int LIBMTP_Update_Track_Metadata (MtpDeviceHandle handle, ref TrackStruct metadata); //[DllImport("libmtp.dll")] //private static extern int LIBMTP_Track_Exists (MtpDeviceHandle handle, uint trackId); //int LIBMTP_Get_Track_To_File_Descriptor (MtpDeviceHandle handle, uint trackId, int const, LIBMTP_progressfunc_t const, void const *const) //int LIBMTP_Send_Track_From_File_Descriptor (MtpDeviceHandle handle, int const, LIBMTP_track_t *const, LIBMTP_progressfunc_t const, void const *const, uint32_t const) } [StructLayout(LayoutKind.Sequential)] internal struct TrackStruct { public uint item_id; public uint parent_id; public uint storage_id; [MarshalAs(UnmanagedType.LPStr)] public string title; [MarshalAs(UnmanagedType.LPStr)] public string artist; [MarshalAs(UnmanagedType.LPStr)] public string composer; [MarshalAs(UnmanagedType.LPStr)] public string genre; [MarshalAs(UnmanagedType.LPStr)] public string album; [MarshalAs(UnmanagedType.LPStr)] public string date; [MarshalAs(UnmanagedType.LPStr)] public string filename; public ushort tracknumber; public uint duration; public uint samplerate; public ushort nochannels; public uint wavecodec; public uint bitrate; public ushort bitratetype; public ushort rating; // 0 -> 100 public uint usecount; public ulong filesize; #if LIBMTP_SIZEOF_TIME_T_64 public ulong modificationdate; #else public uint modificationdate; #endif public FileType filetype; public IntPtr next; // Track Null if last /* public Track? Next { get { if (next == IntPtr.Zero) return null; return (Track)Marshal.PtrToStructure(next, typeof(Track)); } }*/ } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Vevo; public partial class AdminAdvanced_Components_Template_AdminContentDefault : System.Web.UI.UserControl { private ITemplate _messageTemplate; private ITemplate _validationSummaryTemplate; private ITemplate _validationDenotesTemplate; private ITemplate _languageControlTemplate; private ITemplate _buttonEventTemplate; private ITemplate _buttonCommandTemplate; private ITemplate _topContentBoxTemplate; private ITemplate _footerTemplate; //For Grid Template. private ITemplate _filterTemplate; private ITemplate _pageNumberTemplate; private ITemplate _gridTemplate; private ITemplate _bottomContentBoxTemplate; private ITemplate _contentTemplate; private string _headerText; private bool _showLinkBacktoTop = false; private bool _showBorderContent = true; [TemplateInstance( TemplateInstance.Single )] [PersistenceMode( PersistenceMode.InnerProperty )] public ITemplate FooterTemplate { get { return _footerTemplate; } set { _footerTemplate = value; } } [TemplateInstance( TemplateInstance.Single )] [PersistenceMode( PersistenceMode.InnerProperty )] public ITemplate ContentTemplate { get { return _contentTemplate; } set { _contentTemplate = value; } } [TemplateInstance( TemplateInstance.Single )] [PersistenceMode( PersistenceMode.InnerProperty )] public ITemplate MessageTemplate { get { return _messageTemplate; } set { _messageTemplate = value; } } [TemplateInstance( TemplateInstance.Single )] [PersistenceMode( PersistenceMode.InnerProperty )] public ITemplate ValidationSummaryTemplate { get { return _validationSummaryTemplate; } set { _validationSummaryTemplate = value; } } [TemplateInstance( TemplateInstance.Single )] [PersistenceMode( PersistenceMode.InnerProperty )] public ITemplate ValidationDenotesTemplate { get { return _validationDenotesTemplate; } set { _validationDenotesTemplate = value; } } [TemplateInstance( TemplateInstance.Single )] [PersistenceMode( PersistenceMode.InnerProperty )] public ITemplate LanguageControlTemplate { get { return _languageControlTemplate; } set { _languageControlTemplate = value; } } [TemplateInstance( TemplateInstance.Single )] [PersistenceMode( PersistenceMode.InnerProperty )] public ITemplate ButtonEventTemplate { get { return _buttonEventTemplate; } set { _buttonEventTemplate = value; } } [TemplateInstance( TemplateInstance.Single )] [PersistenceMode( PersistenceMode.InnerProperty )] public ITemplate ButtonCommandTemplate { get { return _buttonCommandTemplate; } set { _buttonCommandTemplate = value; } } [TemplateInstance( TemplateInstance.Single )] [PersistenceMode( PersistenceMode.InnerProperty )] public ITemplate TopContentBoxTemplate { get { return _topContentBoxTemplate; } set { _topContentBoxTemplate = value; } } [TemplateInstance( TemplateInstance.Single )] [PersistenceMode( PersistenceMode.InnerProperty )] public ITemplate FilterTemplate { get { return _filterTemplate; } set { _filterTemplate = value; } } [TemplateInstance( TemplateInstance.Single )] [PersistenceMode( PersistenceMode.InnerProperty )] public ITemplate PageNumberTemplate { get { return _pageNumberTemplate; } set { _pageNumberTemplate = value; } } [TemplateInstance( TemplateInstance.Single )] [PersistenceMode( PersistenceMode.InnerProperty )] public ITemplate GridTemplate { get { return _gridTemplate; } set { _gridTemplate = value; } } [TemplateInstance( TemplateInstance.Single )] [PersistenceMode( PersistenceMode.InnerProperty )] public ITemplate BottomContentBoxTemplate { get { return _bottomContentBoxTemplate; } set { _bottomContentBoxTemplate = value; } } [PersistenceMode( PersistenceMode.Attribute )] public String HeaderText { get { return _headerText; } set { _headerText = value; } } [PersistenceMode( PersistenceMode.Attribute )] public Boolean BackToTopLink { get { return _showLinkBacktoTop; } set { _showLinkBacktoTop = value; } } [PersistenceMode( PersistenceMode.Attribute )] public Boolean ShowBorderContent { get { return _showBorderContent; } set { _showBorderContent = value; } } protected override void OnInit( EventArgs e ) { base.OnInit( e ); uxMessagePlaceHolder.Controls.Clear(); uxValidationSummaryPlaceHolder.Controls.Clear(); uxValidationDenotePlaceHolder.Controls.Clear(); uxLanguageControlPlaceHolder.Controls.Clear(); uxButtonEventPlaceHolder.Controls.Clear(); uxButtonCommandPlaceHolder.Controls.Clear(); uxTopContentBoxPlaceHolder.Controls.Clear(); uxFooterPlaceHolder.Controls.Clear(); uxFilterPlaceHolder.Controls.Clear(); uxPageNumberPlaceHolder.Controls.Clear(); uxGridPlaceHolder.Controls.Clear(); uxBottomContentBoxPlaceHolder.Controls.Clear(); uxContentPlaceHolder.Controls.Clear(); // Message. ContentContainer container = new ContentContainer(); if (MessageTemplate != null) { MessageTemplate.InstantiateIn( container ); uxMessagePlaceHolder.Controls.Add( container ); uxMessagePlaceHolder.Visible = true; } else { uxMessagePlaceHolder.Controls.Add( new LiteralControl( "No Message Defined" ) ); uxMessagePlaceHolder.Visible = false; } // Validation Summary container = new ContentContainer(); if (ValidationSummaryTemplate != null) { ValidationSummaryTemplate.InstantiateIn( container ); uxValidationSummaryPlaceHolder.Controls.Add( container ); uxValidationSummaryPanel.Visible = true; } else { uxValidationSummaryPlaceHolder.Controls.Add( new LiteralControl( "No Validation Summary Defined" ) ); uxValidationSummaryPanel.Visible = false; } // Validation Denotes container = new ContentContainer(); if (ValidationDenotesTemplate != null) { ValidationDenotesTemplate.InstantiateIn( container ); uxValidationDenotePlaceHolder.Controls.Add( container ); uxValidationDenotePanel.Visible = true; } else { uxValidationDenotePlaceHolder.Controls.Add( new LiteralControl( "No Validation Denotes Defined" ) ); uxValidationDenotePanel.Visible = false; } // If all message disapear message panel will not show. if (!uxMessagePlaceHolder.Visible & !uxValidationSummaryPanel.Visible & !uxValidationDenotePanel.Visible) uxMessagePanel.Visible = false; else uxMessagePanel.Visible = true; container = new ContentContainer(); if (LanguageControlTemplate != null) { LanguageControlTemplate.InstantiateIn( container ); uxLanguageControlPlaceHolder.Controls.Add( container ); uxLanguageControlPanel.Visible = true; } else { uxLanguageControlPlaceHolder.Controls.Add( new LiteralControl( "No Language Control Defined" ) ); uxLanguageControlPanel.Visible = false; } // If don't have any language and message top panel will not show. if (!uxMessagePanel.Visible & !uxLanguageControlPanel.Visible) uxTopPagePanel.Visible = false; else uxTopPagePanel.Visible = true; if (ButtonEventTemplate == null) uxButtonEventPanel.Visible = false; else { container = new ContentContainer(); ButtonEventTemplate.InstantiateIn( container ); uxButtonEventPlaceHolder.Controls.Add( container ); uxButtonEventPanel.Visible = true; } if (ButtonCommandTemplate == null) { uxButtonCommandPanel.Visible = false; } else { container = new ContentContainer(); ButtonCommandTemplate.InstantiateIn( container ); uxButtonCommandPlaceHolder.Controls.Add( container ); uxButtonCommandPanel.Visible = true; } container = new ContentContainer(); if (TopContentBoxTemplate != null) { TopContentBoxTemplate.InstantiateIn( container ); uxTopContentBoxPlaceHolder.Controls.Add( container ); uxTopContentBoxPlaceHolder.Visible = true; } else { uxTopContentBoxPlaceHolder.Controls.Add( new LiteralControl( "No TopContentBox Content Defined" ) ); uxTopContentBoxPlaceHolder.Visible = false; uxTopContentBoxPanel.Visible = false; } container = new ContentContainer(); if (ContentTemplate != null) { ContentTemplate.InstantiateIn( container ); uxContentPlaceHolder.Controls.Add( container ); uxContentPanel.Visible = true; } else { uxContentPlaceHolder.Controls.Add( new LiteralControl( "No Template Defined" ) ); uxContentPanel.Visible = false; } if (FilterTemplate == null) uxFilterPanel.Visible = false; else { container = new ContentContainer(); FilterTemplate.InstantiateIn( container ); uxFilterPlaceHolder.Controls.Add( container ); uxFilterPanel.Visible = true; } if (PageNumberTemplate == null) uxPageNumberPanel.Visible = false; else { container = new ContentContainer(); PageNumberTemplate.InstantiateIn( container ); uxPageNumberPlaceHolder.Controls.Add( container ); uxPageNumberPanel.Visible = true; } if (GridTemplate == null) uxGridPanel.Visible = false; else { container = new ContentContainer(); GridTemplate.InstantiateIn( container ); uxGridPlaceHolder.Controls.Add( container ); uxGridPanel.Visible = true; } if (uxGridPanel.Visible || uxPageNumberPanel.Visible || uxFilterPanel.Visible || uxTopContentBoxPlaceHolder.Visible) uxTopContentBoxSet.Visible = true; else uxTopContentBoxSet.Visible = false; if (BottomContentBoxTemplate == null) { uxBottomContentBoxPlaceHolder.Visible = false; uxBottomContentBoxPanel.Visible = false; } else { container = new ContentContainer(); BottomContentBoxTemplate.InstantiateIn( container ); uxBottomContentBoxPlaceHolder.Controls.Add( container ); uxBottomContentBoxPlaceHolder.Visible = true; } if (FooterTemplate != null) { container = new ContentContainer(); FooterTemplate.InstantiateIn( container ); uxFooterPlaceHolder.Controls.Add( container ); } uxBackToTopHyperLink.Visible = BackToTopLink; } protected void Page_Load( object sender, EventArgs e ) { } protected void Page_PreRender( object sender, EventArgs e ) { if (!ShowBorderContent) uxTopContentBoxSet.CssClass = "BoxSet1 b6 c4 dn"; else uxTopContentBoxSet.CssClass = "BoxSet1 b6 c4"; } }
/* Copyright 2019-2020 Sannel Software, L.L.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/ using Microsoft.EntityFrameworkCore; using Sannel.House.Base.Models; using Sannel.House.Devices.Data; using Sannel.House.Devices.Interfaces; using Sannel.House.Devices.Models; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; namespace Sannel.House.Devices.Repositories { public class DbContextRepository : IDeviceRepository { private readonly DevicesDbContext context; /// <summary> /// Initializes a new instance of the <see cref="DbContextRepository"/> class. /// </summary> /// <param name="context">The context.</param> /// <exception cref="ArgumentNullException">context</exception> public DbContextRepository([NotNull] DevicesDbContext context) => this.context = context ?? throw new ArgumentNullException(nameof(context)); /// <summary> /// Gets the device by identifier asynchronous. /// </summary> /// <param name="deviceId">The device identifier.</param> /// <returns></returns> public async Task<Device?> GetDeviceByIdAsync(int deviceId) => await context.Devices.AsNoTracking().FirstOrDefaultAsync(i => i.DeviceId == deviceId); /// <summary> /// Gets the device by mac address asynchronous. /// </summary> /// <param name="macAddress">The mac address.</param> /// <returns></returns> public async Task<Device?> GetDeviceByMacAddressAsync(long macAddress) { var alt = await context.AlternateDeviceIds .Include(nameof(AlternateDeviceId.Device)).AsNoTracking() .FirstOrDefaultAsync(i => i.MacAddress == macAddress); return alt?.Device; } /// <summary> /// Gets the count of devices asynchronous. /// </summary> /// <returns></returns> public async Task<long> GetCountAsync() => await context.Devices.LongCountAsync().ConfigureAwait(false); /// <summary> /// Gets a list of devices asynchronous. /// </summary> /// <param name="pageIndex">Index of the page.</param> /// <param name="pageSize">Size of the page.</param> /// <returns></returns> public async Task<IList<Device>> GetListAsync(int pageIndex, int pageSize) => await context.Devices.AsNoTracking() .OrderBy(i => i.DisplayOrder) .Skip(pageIndex * pageSize) .Take(pageSize) .ToListAsync(); /// <summary> /// Gets the devices list asynchronous. /// </summary> /// <param name="pageIndex">Index of the page.</param> /// <param name="pageSize">Size of the page.</param> /// <returns></returns> public async Task<PagedResponseModel<Device>> GetDevicesListAsync(int pageIndex, int pageSize) { var result = await Task.Run(() => new PagedResponseModel<Device>( string.Empty, context.Devices.AsNoTracking() .OrderBy(i => i.DisplayOrder) .Skip(pageIndex * pageSize) .Take(pageSize), context.Devices.LongCount(), pageIndex, pageSize) ); return result; } /// <summary> /// Gets the device by UUID/Guid asynchronous. /// </summary> /// <param name="uuid">The UUID/Guid.</param> /// <returns></returns> public async Task<Device?> GetDeviceByUuidAsync(Guid uuid) { var alt = await context.AlternateDeviceIds .Include(nameof(AlternateDeviceId.Device)) .AsNoTracking() .FirstOrDefaultAsync(i => i.Uuid == uuid); return alt?.Device; } /// <summary> /// Creates the device asynchronous. /// </summary> /// <param name="device">The device.</param> /// <returns></returns> /// <exception cref="ArgumentNullException">device</exception> [return: NotNull] public async Task<Device> AddDeviceAsync([NotNull]Device device) { if(device == null) { throw new ArgumentNullException(nameof(device)); } device.DeviceId = 0; // reset deviceId to 1 so its auto generated. var displayOrder = (context.Devices.Any()) ?await context.Devices.MaxAsync(i => i.DisplayOrder) :0; device.DisplayOrder = displayOrder + 1; var result = await context.Devices.AddAsync(device); await context.SaveChangesAsync(); var id = result.Entity.DeviceId; var dbDevice = await context.Devices.AsNoTracking().FirstAsync(i => i.DeviceId == id); return dbDevice; } /// <summary> /// Updates the device asynchronous. /// </summary> /// <param name="device">The device.</param> /// <returns> /// The device thats update or null if the passed device is not found in the database /// </returns> /// <exception cref="ArgumentNullException">device is null</exception> /// <exception cref="ReadOnlyException">The device is marked read only</exception> public async Task<Device?> UpdateDeviceAsync([NotNull]Device device) { if(device == null) { throw new ArgumentNullException(nameof(device)); } var d = await context.Devices.FirstOrDefaultAsync(i => i.DeviceId == device.DeviceId); if(d is null) { return null; } if(d.IsReadOnly) { throw new ReadOnlyException($"Device {d.DeviceId} is Read Only"); } d.Name = device.Name; d.Description = device.Description; d.DisplayOrder = device.DisplayOrder; d.Verified = device.Verified; await context.SaveChangesAsync(); return await context.Devices.AsNoTracking().FirstOrDefaultAsync(i => i.DeviceId == d.DeviceId); } /// <summary> /// Adds the alternate mac address asynchronous. /// </summary> /// <param name="deviceId">The device identifier.</param> /// <param name="macAddress">The mac address.</param> /// <returns> /// The device or null if there is no device with <paramref name="deviceId" /> /// </returns> /// <exception cref="AlternateDeviceIdException">If the macAddress is already connected to another device</exception> public async Task<Device?> AddAlternateMacAddressAsync(int deviceId, long macAddress) { var device = await context.Devices.AsNoTracking().FirstOrDefaultAsync(i => i.DeviceId == deviceId); if (device == null) { return null; } var altId = await context.AlternateDeviceIds.AsNoTracking().FirstOrDefaultAsync(i => i.MacAddress == macAddress); if (altId != null) { throw new AlternateDeviceIdException($"The macAddress {macAddress} is already associated with a device {altId.DeviceId}"); } altId = new AlternateDeviceId() { DeviceId = device.DeviceId, DateCreated = DateTimeOffset.UtcNow, MacAddress = macAddress }; await context.AlternateDeviceIds.AddAsync(altId); await context.SaveChangesAsync(); return device; } /// <summary> /// Adds the alternate UUID asynchronous. /// </summary> /// <param name="deviceId">The device identifier.</param> /// <param name="uuid">The UUID.</param> /// <returns> /// The device or null if there is no device with <paramref name="deviceId" /> /// </returns> /// <exception cref="AlternateDeviceIdException">If the Uuid is already associated with a device</exception> public async Task<Device?> AddAlternateUuidAsync(int deviceId, Guid uuid) { var device = await context.Devices.AsNoTracking().FirstOrDefaultAsync(i => i.DeviceId == deviceId); if (device == null) { return null; } var altId = await context.AlternateDeviceIds.AsNoTracking().FirstOrDefaultAsync(i => i.Uuid == uuid); if (altId != null) { throw new AlternateDeviceIdException($"The Uuid {uuid} is already associated with a device {altId.DeviceId}"); } altId = new AlternateDeviceId() { DeviceId = device.DeviceId, DateCreated = DateTimeOffset.UtcNow, Uuid = uuid }; await context.AlternateDeviceIds.AddAsync(altId); await context.SaveChangesAsync(); return device; } /// <summary> /// Adds the alternate device identifier asynchronous. /// </summary> /// <param name="deviceId">The device identifier.</param> /// <param name="manufacture">The manufacture.</param> /// <param name="manufactureId">The manufacture identifier.</param> /// <returns> /// The device or null if there is no device with <paramref name="deviceId" /> is found /// </returns> /// <exception cref="ArgumentNullException"> /// manufacture /// or /// manufactureId /// </exception> /// <exception cref="AlternateDeviceIdException">The manufacture {manufacture} and manufacture id {manufactureId} are already associated with a device {altId.DeviceId}.</exception> public async Task<Device?> AddAlternateManufactureIdAsync(int deviceId, [NotNull]string manufacture, [NotNull]string manufactureId) { if (string.IsNullOrWhiteSpace(manufacture)) { throw new ArgumentNullException(nameof(manufacture)); } if(string.IsNullOrWhiteSpace(manufactureId)) { throw new ArgumentNullException(nameof(manufactureId)); } var device = await context.Devices.AsNoTracking().FirstOrDefaultAsync(i => i.DeviceId == deviceId); if(device == null) { return null; } var altId = await context.AlternateDeviceIds.AsNoTracking().FirstOrDefaultAsync(i => i.Manufacture == manufacture && i.ManufactureId == manufactureId); if(altId != null) { throw new AlternateDeviceIdException($"The manufacture {manufacture} and manufacture id {manufactureId} are already associated with a device {altId.DeviceId}."); } altId = new AlternateDeviceId() { DeviceId = device.DeviceId, DateCreated = DateTimeOffset.UtcNow, Manufacture = manufacture, ManufactureId = manufactureId }; await context.AlternateDeviceIds.AddAsync(altId); await context.SaveChangesAsync(); return device; } /// <summary> /// Removes the alternate mac address asynchronous. /// </summary> /// <param name="macAddress">The mac address.</param> /// <returns> /// The device or null if the macAddress is not found /// </returns> public async Task<Device?> RemoveAlternateMacAddressAsync(long macAddress) { var altId = await context.AlternateDeviceIds .AsNoTracking() .FirstOrDefaultAsync(i => i.MacAddress == macAddress); if (altId == null) { return null; } var device = await context.Devices.AsNoTracking().FirstOrDefaultAsync(i => i.DeviceId == altId.DeviceId); context.AlternateDeviceIds.Remove(altId); await context.SaveChangesAsync(); return device; } /// <summary> /// Removes the alternate UUID asynchronous. /// </summary> /// <param name="uuid">The UUID.</param> /// <returns> /// The device or null if the uuid is not found /// </returns> public async Task<Device?> RemoveAlternateUuidAsync(Guid uuid) { var altId = await context.AlternateDeviceIds .AsNoTracking().FirstOrDefaultAsync(i => i.Uuid == uuid); if (altId == null) { return null; } var device = await context.Devices.AsNoTracking().FirstOrDefaultAsync(i => i.DeviceId == altId.DeviceId); context.AlternateDeviceIds.Remove(altId); await context.SaveChangesAsync(); return device; } /// <summary> /// Gets the alternate ids for the device asynchronous. /// </summary> /// <param name="deviceId">The device identifier.</param> /// <returns> /// The AlternateDeviceIds or empty if <paramref name="deviceId" /> is not found /// </returns> public async Task<IEnumerable<AlternateDeviceId>> GetAlternateIdsForDeviceAsync(int deviceId) => await Task.Run(() => context .AlternateDeviceIds .AsNoTracking() .Where(i => i.DeviceId == deviceId)); /// <summary> /// Gets the device by manufacture identifier asynchronous. /// </summary> /// <param name="manufacture">The manufacture.</param> /// <param name="manufactureId">The manufacture identifier.</param> /// <returns> /// The Device or null if no device is found with the passed <paramref name="manufacture" /><paramref name="manufactureId" /> combination /// </returns> public async Task<Device?> GetDeviceByManufactureIdAsync([NotNull]string manufacture, [NotNull]string manufactureId) { var alt = await context.AlternateDeviceIds .Include(nameof(AlternateDeviceId.Device)) .AsNoTracking() .FirstOrDefaultAsync(i => i.Manufacture == manufacture && i.ManufactureId == manufactureId); return alt?.Device; } /// <summary> /// Removes the alternate manufacture identifier asynchronous. /// </summary> /// <param name="manufacture">The manufacture.</param> /// <param name="manufactureId">The manufacture identifier.</param> /// <returns> /// The device associated with the <paramref name="manufacture" /><paramref name="manufactureId" /> combo or null if its not found /// </returns> public async Task<Device?> RemoveAlternateManufactureIdAsync([NotNull]string manufacture, [NotNull]string manufactureId) { var altId = await context.AlternateDeviceIds .AsNoTracking().FirstOrDefaultAsync(i => i.Manufacture == manufacture && i.ManufactureId == manufactureId); if (altId == null) { return null; } var device = await context.Devices.AsNoTracking().FirstOrDefaultAsync(i => i.DeviceId == altId.DeviceId); context.AlternateDeviceIds.Remove(altId); await context.SaveChangesAsync(); return device; } } }
// 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.AddImport; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.SymbolSearch; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CSharp.CodeFixes.AddImport.AddImportDiagnosticIds; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.AddImport { internal static class AddImportDiagnosticIds { /// <summary> /// name does not exist in context /// </summary> public const string CS0103 = nameof(CS0103); /// <summary> /// type or namespace could not be found /// </summary> public const string CS0246 = nameof(CS0246); /// <summary> /// wrong number of type args /// </summary> public const string CS0305 = nameof(CS0305); /// <summary> /// type does not contain a definition of method or extension method /// </summary> public const string CS1061 = nameof(CS1061); /// <summary> /// cannot find implementation of query pattern /// </summary> public const string CS1935 = nameof(CS1935); /// <summary> /// The non-generic type 'A' cannot be used with type arguments /// </summary> public const string CS0308 = nameof(CS0308); /// <summary> /// 'A' is inaccessible due to its protection level /// </summary> public const string CS0122 = nameof(CS0122); /// <summary> /// The using alias 'A' cannot be used with type arguments /// </summary> public const string CS0307 = nameof(CS0307); /// <summary> /// 'A' is not an attribute class /// </summary> public const string CS0616 = nameof(CS0616); /// <summary> /// No overload for method 'X' takes 'N' arguments /// </summary> public const string CS1501 = nameof(CS1501); /// <summary> /// cannot convert from 'int' to 'string' /// </summary> public const string CS1503 = nameof(CS1503); /// <summary> /// XML comment on 'construct' has syntactically incorrect cref attribute 'name' /// </summary> public const string CS1574 = nameof(CS1574); /// <summary> /// Invalid type for parameter 'parameter number' in XML comment cref attribute /// </summary> public const string CS1580 = nameof(CS1580); /// <summary> /// Invalid return type in XML comment cref attribute /// </summary> public const string CS1581 = nameof(CS1581); /// <summary> /// XML comment has syntactically incorrect cref attribute /// </summary> public const string CS1584 = nameof(CS1584); /// <summary> /// Type 'X' does not contain a valid extension method accepting 'Y' /// </summary> public const string CS1929 = nameof(CS1929); /// <summary> /// Cannot convert method group 'X' to non-delegate type 'Y'. Did you intend to invoke the method? /// </summary> public const string CS0428 = nameof(CS0428); /// <summary> /// There is no argument given that corresponds to the required formal parameter 'X' of 'Y' /// </summary> public const string CS7036 = nameof(CS7036); public static ImmutableArray<string> FixableTypeIds = ImmutableArray.Create( CS0103, CS0246, CS0305, CS0308, CS0122, CS0307, CS0616, CS1580, CS1581); public static ImmutableArray<string> FixableDiagnosticIds = FixableTypeIds.Concat(ImmutableArray.Create( CS1061, CS1935, CS1501, CS1503, CS1574, CS1584, CS1929, CS0428, CS7036)); } [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddUsingOrImport), Shared] internal class CSharpAddImportCodeFixProvider : AbstractAddImportCodeFixProvider<SimpleNameSyntax> { public override ImmutableArray<string> FixableDiagnosticIds => AddImportDiagnosticIds.FixableDiagnosticIds; public CSharpAddImportCodeFixProvider() { } /// <summary>For testing purposes only (so that tests can pass in mock values)</summary> internal CSharpAddImportCodeFixProvider( IPackageInstallerService installerService, ISymbolSearchService symbolSearchService) : base(installerService, symbolSearchService) { } protected override bool CanAddImport(SyntaxNode node, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return false; } return node.CanAddUsingDirectives(cancellationToken); } protected override bool CanAddImportForMethod( Diagnostic diagnostic, ISyntaxFactsService syntaxFacts, SyntaxNode node, out SimpleNameSyntax nameNode) { nameNode = null; switch (diagnostic.Id) { case CS7036: case CS0428: case CS1061: if (node.IsKind(SyntaxKind.ConditionalAccessExpression)) { node = (node as ConditionalAccessExpressionSyntax).WhenNotNull; } else if (node.IsKind(SyntaxKind.MemberBindingExpression)) { node = (node as MemberBindingExpressionSyntax).Name; } else if (node.Parent.IsKind(SyntaxKind.CollectionInitializerExpression)) { return true; } break; case CS0122: case CS1501: if (node is SimpleNameSyntax) { break; } else if (node is MemberBindingExpressionSyntax) { node = (node as MemberBindingExpressionSyntax).Name; } break; case CS1929: var memberAccessName = (node.Parent as MemberAccessExpressionSyntax)?.Name; var conditionalAccessName = (((node.Parent as ConditionalAccessExpressionSyntax)?.WhenNotNull as InvocationExpressionSyntax)?.Expression as MemberBindingExpressionSyntax)?.Name; if (memberAccessName == null && conditionalAccessName == null) { return false; } node = memberAccessName ?? conditionalAccessName; break; case CS1503: //// look up its corresponding method name var parent = node.GetAncestor<InvocationExpressionSyntax>(); if (parent == null) { return false; } var method = parent.Expression as MemberAccessExpressionSyntax; if (method != null) { node = method.Name; } break; default: return false; } nameNode = node as SimpleNameSyntax; if (!nameNode.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) && !nameNode.IsParentKind(SyntaxKind.MemberBindingExpression)) { return false; } var memberAccess = nameNode.Parent as MemberAccessExpressionSyntax; var memberBinding = nameNode.Parent as MemberBindingExpressionSyntax; if (memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) || memberAccess.IsParentKind(SyntaxKind.ElementAccessExpression) || memberBinding.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) || memberBinding.IsParentKind(SyntaxKind.ElementAccessExpression)) { return false; } if (!syntaxFacts.IsMemberAccessExpressionName(node)) { return false; } return true; } protected override bool CanAddImportForNamespace(Diagnostic diagnostic, SyntaxNode node, out SimpleNameSyntax nameNode) { nameNode = null; return false; } protected override bool CanAddImportForQuery(Diagnostic diagnostic, SyntaxNode node) { if (diagnostic.Id != CS1935) { return false; } return node.AncestorsAndSelf().Any(n => n is QueryExpressionSyntax && !(n.Parent is QueryContinuationSyntax)); } protected override bool CanAddImportForType(Diagnostic diagnostic, SyntaxNode node, out SimpleNameSyntax nameNode) { nameNode = null; switch (diagnostic.Id) { case CS0103: case CS0246: case CS0305: case CS0308: case CS0122: case CS0307: case CS0616: case CS1580: case CS1581: break; case CS1574: case CS1584: var cref = node as QualifiedCrefSyntax; if (cref != null) { node = cref.Container; } break; default: return false; } return TryFindStandaloneType(node, out nameNode); } private static bool TryFindStandaloneType(SyntaxNode node, out SimpleNameSyntax nameNode) { var qn = node as QualifiedNameSyntax; if (qn != null) { node = GetLeftMostSimpleName(qn); } nameNode = node as SimpleNameSyntax; return nameNode.LooksLikeStandaloneTypeName(); } private static SimpleNameSyntax GetLeftMostSimpleName(QualifiedNameSyntax qn) { while (qn != null) { var left = qn.Left; var simpleName = left as SimpleNameSyntax; if (simpleName != null) { return simpleName; } qn = left as QualifiedNameSyntax; } return null; } protected override ISet<INamespaceSymbol> GetNamespacesInScope( SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { return semanticModel.GetUsingNamespacesInScope(node); } protected override ITypeSymbol GetQueryClauseInfo( SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { var query = node.AncestorsAndSelf().OfType<QueryExpressionSyntax>().First(); if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(query.FromClause, cancellationToken))) { return null; } foreach (var clause in query.Body.Clauses) { if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(clause, cancellationToken))) { return null; } } if (InfoBoundSuccessfully(semanticModel.GetSymbolInfo(query.Body.SelectOrGroup, cancellationToken))) { return null; } var fromClause = query.FromClause; return semanticModel.GetTypeInfo(fromClause.Expression, cancellationToken).Type; } private bool InfoBoundSuccessfully(SymbolInfo symbolInfo) { return InfoBoundSuccessfully(symbolInfo.Symbol); } private bool InfoBoundSuccessfully(QueryClauseInfo semanticInfo) { return InfoBoundSuccessfully(semanticInfo.OperationInfo); } private static bool InfoBoundSuccessfully(ISymbol operation) { operation = operation.GetOriginalUnreducedDefinition(); return operation != null; } protected override string GetDescription(IReadOnlyList<string> nameParts) { return $"using { string.Join(".", nameParts) };"; } protected override string TryGetDescription( INamespaceOrTypeSymbol namespaceOrTypeSymbol, SemanticModel semanticModel, SyntaxNode contextNode, bool checkForExistingUsing) { var root = GetCompilationUnitSyntaxNode(contextNode); // See if this is a reference to a type from a reference that has a specific alias // associated with it. If that extern alias hasn't already been brought into scope // then add that one. var externAlias = TryGetExternAliasDirective( namespaceOrTypeSymbol, semanticModel, contextNode, checkForExistingExternAlias: true); if (externAlias != null) { return $"extern alias {externAlias.Identifier.ValueText};"; } var usingDirective = TryGetUsingDirective( namespaceOrTypeSymbol, semanticModel, root, contextNode); if (usingDirective != null) { var displayString = namespaceOrTypeSymbol.ToDisplayString(); return namespaceOrTypeSymbol.IsKind(SymbolKind.Namespace) ? $"using {displayString};" : $"using static {displayString};"; } return null; } private bool HasExistingUsingDirective( CompilationUnitSyntax root, NamespaceDeclarationSyntax namespaceToAddTo, UsingDirectiveSyntax usingDirective) { var usings = namespaceToAddTo?.Usings ?? root.Usings; foreach (var existingUsing in usings) { if (SyntaxFactory.AreEquivalent(usingDirective, existingUsing)) { return true; } } return false; } protected override async Task<Document> AddImportAsync( SyntaxNode contextNode, INamespaceOrTypeSymbol namespaceOrTypeSymbol, Document document, bool placeSystemNamespaceFirst, CancellationToken cancellationToken) { var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken); var newRoot = await AddImportWorkerAsync(document, root, contextNode, namespaceOrTypeSymbol, placeSystemNamespaceFirst, cancellationToken).ConfigureAwait(false); return document.WithSyntaxRoot(newRoot); } private async Task<CompilationUnitSyntax> AddImportWorkerAsync( Document document, CompilationUnitSyntax root, SyntaxNode contextNode, INamespaceOrTypeSymbol namespaceOrTypeSymbol, bool placeSystemNamespaceFirst, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var firstContainingNamespaceWithUsings = GetFirstContainingNamespaceWithUsings(contextNode); var namespaceToUpdate = firstContainingNamespaceWithUsings; var externAliasDirective = TryGetExternAliasDirective( namespaceOrTypeSymbol, semanticModel, contextNode, checkForExistingExternAlias: true); var usingDirective = TryGetUsingDirective( namespaceOrTypeSymbol, semanticModel, root, contextNode); if (externAliasDirective != null) { AddExterns(ref root, ref namespaceToUpdate, externAliasDirective); } if (usingDirective != null) { AddUsingDirective(ref root, ref namespaceToUpdate, placeSystemNamespaceFirst, usingDirective); } return firstContainingNamespaceWithUsings != null ? root.ReplaceNode(firstContainingNamespaceWithUsings, namespaceToUpdate) : root; } private void AddUsingDirective( ref CompilationUnitSyntax root, ref NamespaceDeclarationSyntax namespaceToUpdate, bool placeSystemNamespaceFirst, UsingDirectiveSyntax usingDirective) { IList<UsingDirectiveSyntax> directives = new[] { usingDirective }; if (namespaceToUpdate != null) { namespaceToUpdate = namespaceToUpdate.AddUsingDirectives( directives, placeSystemNamespaceFirst); } else { root = root.AddUsingDirectives( directives, placeSystemNamespaceFirst); } } private void AddExterns( ref CompilationUnitSyntax root, ref NamespaceDeclarationSyntax namespaceToUpdate, ExternAliasDirectiveSyntax externAliasDirective) { if (namespaceToUpdate != null) { namespaceToUpdate = namespaceToUpdate.AddExterns(externAliasDirective); } else { root = root.AddExterns(externAliasDirective); } } protected override Task<Document> AddImportAsync( SyntaxNode contextNode, IReadOnlyList<string> namespaceParts, Document document, bool placeSystemNamespaceFirst, CancellationToken cancellationToken) { var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken); // Suppress diagnostics on the import we create. Because we only get here when we are // adding a nuget package, it is certainly the case that in the preview this will not // bind properly. It will look silly to show such an error, so we just suppress things. var simpleUsingDirective = SyntaxFactory.UsingDirective( CreateNameSyntax(namespaceParts, namespaceParts.Count - 1)).WithAdditionalAnnotations( SuppressDiagnosticsAnnotation.Create()); // If we have an existing using with this name then don't bother adding this new using. if (root.Usings.Any(u => u.IsEquivalentTo(simpleUsingDirective, topLevel: false))) { return Task.FromResult(document); } var newRoot = root.AddUsingDirective( simpleUsingDirective, contextNode, placeSystemNamespaceFirst, Formatter.Annotation); return Task.FromResult(document.WithSyntaxRoot(newRoot)); } private NameSyntax CreateNameSyntax(IReadOnlyList<string> namespaceParts, int index) { var part = namespaceParts[index]; if (SyntaxFacts.GetKeywordKind(part) != SyntaxKind.None) { part = "@" + part; } var namePiece = SyntaxFactory.IdentifierName(part); return index == 0 ? (NameSyntax)namePiece : SyntaxFactory.QualifiedName(CreateNameSyntax(namespaceParts, index - 1), namePiece); } private static ExternAliasDirectiveSyntax TryGetExternAliasDirective( INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, SyntaxNode contextNode, bool checkForExistingExternAlias) { string externAliasString; if (TryGetExternAliasString(namespaceSymbol, semanticModel, contextNode, checkForExistingExternAlias, out externAliasString)) { return SyntaxFactory.ExternAliasDirective(SyntaxFactory.Identifier(externAliasString)) .WithAdditionalAnnotations(Formatter.Annotation); } return null; } private UsingDirectiveSyntax TryGetUsingDirective( INamespaceOrTypeSymbol namespaceOrTypeSymbol, SemanticModel semanticModel, CompilationUnitSyntax root, SyntaxNode contextNode) { var namespaceToAddTo = GetFirstContainingNamespaceWithUsings(contextNode); var usingDirectives = namespaceToAddTo?.Usings ?? root.Usings; var nameSyntax = namespaceOrTypeSymbol.GenerateNameSyntax(); // Replace the alias that GenerateTypeSyntax added if we want this to be looked // up off of an extern alias. var externAliasDirective = TryGetExternAliasDirective( namespaceOrTypeSymbol, semanticModel, contextNode, checkForExistingExternAlias: false); var externAlias = externAliasDirective?.Identifier.ValueText; if (externAlias != null) { nameSyntax = AddOrReplaceAlias(nameSyntax, SyntaxFactory.IdentifierName(externAlias)); } else { // The name we generated will have the global:: alias on it. We only need // that if the name of our symbol is actually ambiguous in this context. // If so, keep global:: on it, otherwise remove it. // // Note: doing this has a couple of benefits. First, it's easy for us to see // if we have an existing using for this with the same syntax. Second, // it's easy to sort usings properly. If "global::" was attached to the // using directive, then it would make both of those operations more difficult // to achieve. nameSyntax = RemoveGlobalAliasIfUnnecessary(semanticModel, nameSyntax, namespaceToAddTo); } var usingDirective = SyntaxFactory.UsingDirective(nameSyntax) .WithAdditionalAnnotations(Formatter.Annotation); if (HasExistingUsingDirective(root, namespaceToAddTo, usingDirective)) { return null; } return namespaceOrTypeSymbol.IsKind(SymbolKind.Namespace) ? usingDirective : usingDirective.WithStaticKeyword(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } private NameSyntax RemoveGlobalAliasIfUnnecessary( SemanticModel semanticModel, NameSyntax nameSyntax, NamespaceDeclarationSyntax namespaceToAddTo) { var aliasQualifiedName = nameSyntax.DescendantNodesAndSelf() .OfType<AliasQualifiedNameSyntax>() .FirstOrDefault(); if (aliasQualifiedName != null) { var rightOfAliasName = aliasQualifiedName.Name.Identifier.ValueText; if (!ConflictsWithExistingMember(semanticModel, namespaceToAddTo, rightOfAliasName)) { // Strip off the alias. return nameSyntax.ReplaceNode(aliasQualifiedName, aliasQualifiedName.Name); } } return nameSyntax; } private bool ConflictsWithExistingMember( SemanticModel semanticModel, NamespaceDeclarationSyntax namespaceToAddTo, string rightOfAliasName) { if (namespaceToAddTo != null) { var containingNamespaceSymbol = semanticModel.GetDeclaredSymbol(namespaceToAddTo); while (containingNamespaceSymbol != null && !containingNamespaceSymbol.IsGlobalNamespace) { if (containingNamespaceSymbol.GetMembers(rightOfAliasName).Any()) { // A containing namespace had this name in it. We need to stay globally qualified. return true; } containingNamespaceSymbol = containingNamespaceSymbol.ContainingNamespace; } } // Didn't conflict with anything. We shoudl remove the global:: alias. return false; } private NameSyntax AddOrReplaceAlias( NameSyntax nameSyntax, IdentifierNameSyntax alias) { var simpleName = nameSyntax as SimpleNameSyntax; if (simpleName != null) { return SyntaxFactory.AliasQualifiedName(alias, simpleName); } var qualifiedName = nameSyntax as QualifiedNameSyntax; if (qualifiedName != null) { return qualifiedName.WithLeft(AddOrReplaceAlias(qualifiedName.Left, alias)); } var aliasName = nameSyntax as AliasQualifiedNameSyntax; return aliasName.WithAlias(alias); } private NamespaceDeclarationSyntax GetFirstContainingNamespaceWithUsings(SyntaxNode contextNode) { var usingDirective = contextNode.GetAncestor<UsingDirectiveSyntax>(); if (usingDirective != null) { contextNode = usingDirective.Parent; } return contextNode.GetAncestors<NamespaceDeclarationSyntax>() .Where(n => n.Usings.Count > 0) .FirstOrDefault(); } private static bool TryGetExternAliasString( INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, SyntaxNode contextNode, bool checkForExistingExternAlias, out string externAliasString) { externAliasString = null; var metadataReference = semanticModel.Compilation.GetMetadataReference(namespaceSymbol.ContainingAssembly); if (metadataReference == null) { return false; } var aliases = metadataReference.Properties.Aliases; if (aliases.IsEmpty) { return false; } aliases = metadataReference.Properties.Aliases.Where(a => a != MetadataReferenceProperties.GlobalAlias).ToImmutableArray(); if (!aliases.Any()) { return false; } // Just default to using the first alias we see for this symbol. externAliasString = aliases.First(); return !checkForExistingExternAlias || ShouldAddExternAlias(externAliasString, contextNode); } private static bool ShouldAddExternAlias(string alias, SyntaxNode contextNode) { foreach (var externAlias in contextNode.GetEnclosingExternAliasDirectives()) { // We already have this extern alias in scope. No need to add it. if (externAlias.Identifier.ValueText == alias) { return false; } } return true; } private static CompilationUnitSyntax GetCompilationUnitSyntaxNode(SyntaxNode contextNode, CancellationToken cancellationToken = default(CancellationToken)) { return (CompilationUnitSyntax)contextNode.SyntaxTree.GetRoot(cancellationToken); } protected override bool IsViableExtensionMethod(IMethodSymbol method, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken) { var leftExpression = syntaxFacts.GetExpressionOfMemberAccessExpression(expression); if (leftExpression == null) { if (expression.IsKind(SyntaxKind.CollectionInitializerExpression)) { leftExpression = expression.GetAncestor<ObjectCreationExpressionSyntax>(); } else { return false; } } var semanticInfo = semanticModel.GetTypeInfo(leftExpression, cancellationToken); var leftExpressionType = semanticInfo.Type; return IsViableExtensionMethod(method, leftExpressionType); } internal override bool IsAddMethodContext(SyntaxNode node, SemanticModel semanticModel) { if (node.Parent.IsKind(SyntaxKind.CollectionInitializerExpression)) { var objectCreationExpressionSyntax = node.GetAncestor<ObjectCreationExpressionSyntax>(); if (objectCreationExpressionSyntax == null) { return false; } return true; } return false; } } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library 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 Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Security.Cryptography; using System.Text; using System.Xml; using System.IO; using System.Management; using System.Text.RegularExpressions; using System.Security; using System.Runtime.InteropServices; using System.Collections.Generic; using MLifter.Generics.Properties; using System.Net; using Microsoft.Win32; using System.Diagnostics; using System.ServiceModel.Syndication; using System.Xml.Serialization; namespace MLifter.Generics { /// <summary> /// This struct stores the general information about a module. /// </summary> /// <remarks>Documented by Dev05, 2012-02-07</remarks> [Serializable] public struct ModuleInfo { public string Id; public string Title; public SerializableList<string> Categories; public string Author; public string AuthorMail; public string AuthorUrl; public int Cards; public byte[] IconBig; public byte[] IconSmall; public string Description; public byte[] Preview; public string EditDate; public long Size; public string DownloadUrl; } /// <summary> /// This struct stores the cached information about a module. /// </summary> /// <remarks>Documented by Dev05, 2012-02-07</remarks> [Serializable] public struct ModuleInfoCacheItem { public string Id; public string IconBig; public string IconSmall; public string Preview; /// <summary> /// Initializes a new instance of the <see cref="ModuleInfoCacheItem"/> struct. /// </summary> /// <param name="id">The id.</param> /// <remarks>CFI, 2012-03-10</remarks> public ModuleInfoCacheItem(string id) { Id = id; IconBig = IconSmall = Preview = null; } } /// <summary> /// The category of a module. /// </summary> /// <remarks>Documented by Dev05, 2012-02-07</remarks> [Serializable] public struct ModuleCategory { public int Id; public int ParentCategory; public string Title; } /// <summary> /// Defines the relation ship type of a link in an atom feed entry. /// </summary> /// <remarks>Documented by Dev05, 2012-02-07</remarks> public enum AtomLinkRelationshipType { /// <summary> /// The link points to a parent entry. /// </summary> /// <remarks>Documented by Dev05, 2012-02-07</remarks> Parent, /// <summary> /// The link points to a learning module. /// </summary> /// <remarks>Documented by Dev05, 2012-02-07</remarks> Module, /// <summary> /// The link points to a preview image. /// </summary> /// <remarks>Documented by Dev05, 2012-02-07</remarks> Preview, /// <summary> /// The link points to a big icon for the module. /// </summary> /// <remarks>Documented by Dev05, 2012-02-07</remarks> IconBig, /// <summary> /// The link points to a small icon for the module. /// </summary> /// <remarks>Documented by Dev05, 2012-02-07</remarks> IconSmall } /// <summary> /// documented by SDE, 24.2.2009 /// </summary> public struct DataArray { public string UnlockKey; public byte[] EncryptedData; public byte[] Signature; public DataArray(string publicKey, byte[] encryptedData, byte[] signature) { UnlockKey = publicKey; EncryptedData = encryptedData; Signature = signature; } } /// <summary> /// </summary> /// <remarks>Documented by Dev04, 2009-03-12</remarks> public struct KeyArray { public string LicenseKey; public string UnlockKey; public KeyArray(string licenseKey, string unlockKey) { LicenseKey = licenseKey; UnlockKey = unlockKey; } } public class Methods { private static Random rand = new Random(); private static Regex regHex = new Regex("[^0-9A-F]", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static string CompressedAlphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; /// <summary> /// Converts a byte array to compressed string. /// </summary> /// <param name="Bytes">The byte array to be compressed.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-02-09</remarks> public static string ByteArrayToCompressedArrayString(byte[] Bytes) { if (Bytes == (byte[])null) throw new ArgumentNullException("Bytes"); Random rand = new Random((int)DateTime.Now.Ticks); string result = string.Empty; int fillupCount = 5 - Bytes.Length * 8 % 5; string binary = string.Empty; for (int i = 0; i < Bytes.Length || (i >= Bytes.Length && binary.Length % 5 != 0); i++) { if (i >= Bytes.Length) for (int j = 0; j < fillupCount; j++) binary += rand.NextDouble() > 0.5 ? "1" : "0"; else binary += GetBinaryString(Bytes[i], 8); } string binHolder = string.Empty; for (int i = 0; i < binary.Length; i++) { binHolder += binary[i]; if (i % 5 == 4) { result += CompressedAlphabet[Convert.ToInt32(binHolder, 2)]; binHolder = string.Empty; } } return result; } /// <summary> /// Converts a compressed string to a uncompressed byte array. /// </summary> /// <param name="compressedArray">The compressed array.</param> /// <param name="expectedLength">The expected length.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-02-09</remarks> public static byte[] CompressedArrayStringToByteArray(string compressedArray, int expectedLength) { if (expectedLength == 0) throw new ArgumentException("expectedLength == 0", "expectedLength"); if (compressedArray == (string)null) throw new ArgumentNullException("compressedArray"); if (expectedLength < 0) throw new ArgumentException("expectedLength < 0", "expectedLength"); byte[] Bytes = new byte[expectedLength]; //For all Data: compressedArray.Length / 8 * 5 string binary = string.Empty; for (int i = 0; i < compressedArray.Length; i++) binary += GetBinaryString(CompressedAlphabet.IndexOf(compressedArray[i]), 5); string binHolder = string.Empty; for (int i = 0; i < binary.Length; i++) { binHolder += binary[i]; if (i % 8 == 7) { int byteNumber = (i / 8); Bytes[byteNumber] = (byte)Convert.ToInt32(binHolder, 2); binHolder = string.Empty; if (byteNumber + 1 >= expectedLength) break; } } return Bytes; } /// <summary> /// Gets the binary string. /// </summary> /// <param name="data">The data.</param> /// <param name="length">The length of the resulting string (filled with zeros).</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-02-09</remarks> private static string GetBinaryString(int data, int length) { int numbase = 2; string strBin = ""; int[] result = new int[length]; int MaxBit = length; for (; data > 0; data /= numbase) { int rem = data % numbase; result[--MaxBit] = rem; } for (int i = 0; i < result.Length; i++) strBin += result.GetValue(i); return strBin; } /// <summary> /// License Type /// </summary> private enum LicenseType { /// <summary> /// Server /// </summary> Server, /// <summary> /// Client /// </summary> Client } /// <summary> /// Creates the license key. /// </summary> /// <param name="LicenseType">Type of the license (client|server).</param> /// <returns></returns> /// <remarks>Documented by Dev04, 2009-02-11</remarks> public static string CreateLicenseKey(string LicenseType) { bool even; LicenseType lt = (LicenseType)Enum.Parse(typeof(LicenseType), LicenseType, true); even = (lt == Methods.LicenseType.Server); string LicenseKey = ""; string block = ""; int i = 0; int blocks = 4; do { block = CreateKeyBlock(even).ToString(); if (!LicenseKey.Contains(block) && i < blocks) { if (i == 0) LicenseKey = block; else LicenseKey = LicenseKey + "-" + block; i++; } } while (i < blocks); return LicenseKey; } /// <summary> /// Generates the sync key. /// </summary> /// <param name="Password">The password.</param> /// <returns></returns> /// <remarks>Documented by Dev04, 2009-02-11</remarks> public static string GenerateSymKey(string Password) { return BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(ASCIIEncoding.ASCII.GetBytes(Password))).Replace("-", "").ToLower().Substring(0, 24); } /// <summary> /// Ts the DES decrypt. /// </summary> /// <param name="toDecrypt">To decrypt.</param> /// <param name="key">The key.</param> /// <param name="useHashing">if set to <c>true</c> [use hashing].</param> /// <returns></returns> /// <remarks>Documented by Dev04, 2009-02-11</remarks> public static string TDesDecrypt(string toDecrypt, string key, bool useHashing) { if (toDecrypt == (string)null) throw new ArgumentNullException("toDecrypt"); byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); return TDesDecrypt(toEncryptArray, key, useHashing); } /// <summary> /// Ts the DES decrypt. /// </summary> /// <param name="toEncryptArray">To encrypt array.</param> /// <param name="key">The key.</param> /// <param name="useHashing">if set to <c>true</c> [use hashing].</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-02-11</remarks> public static string TDesDecrypt(byte[] toDecryptArray, string key, bool useHashing) { return UTF8Encoding.UTF8.GetString(TDesDecryptBytes(toDecryptArray, key, useHashing)); } /// <summary> /// Ts the DES decrypt bytes. /// </summary> /// <param name="toDecryptArray">To decrypt array.</param> /// <param name="key">The key.</param> /// <param name="useHashing">if set to <c>true</c> [use hashing].</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-02-11</remarks> public static byte[] TDesDecryptBytes(byte[] toDecryptArray, string key, bool useHashing) { if (key == (string)null) throw new ArgumentNullException("key"); if (key.Trim().Length == 0) throw new ArgumentException("key"); if (toDecryptArray == (byte[])null) throw new ArgumentNullException("toDecryptArray"); byte[] keyArray; if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateDecryptor(); return cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length); } /// <summary> /// Ts the DES encrypt. /// </summary> /// <param name="toEncrypt">To encrypt.</param> /// <param name="key">The key.</param> /// <param name="useHashing">if set to <c>true</c> [use hashing].</param> /// <returns></returns> /// <remarks>Documented by Dev04, 2009-02-11</remarks> public static string TDesEncrypt(string toEncrypt, string key, bool useHashing) { if (toEncrypt == (string)null) throw new ArgumentNullException("toEncrypt"); byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); return TDesEncrypt(toEncryptArray, key, useHashing); } /// <summary> /// Ts the DES encrypt. /// </summary> /// <param name="toEncryptArray">To encrypt array.</param> /// <param name="key">The key.</param> /// <param name="useHashing">if set to <c>true</c> [use hashing].</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-02-11</remarks> public static string TDesEncrypt(byte[] toEncryptArray, string key, bool useHashing) { byte[] resultArray = TDesEncryptBytes(toEncryptArray, key, useHashing); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } /// <summary> /// Ts the DES encrypt bytes. /// </summary> /// <param name="toEncryptArray">To encrypt array.</param> /// <param name="key">The key.</param> /// <param name="useHashing">if set to <c>true</c> [use hashing].</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-02-11</remarks> public static byte[] TDesEncryptBytes(string toEncrypt, string key, bool useHashing) { if (toEncrypt == (string)null) throw new ArgumentNullException("toEncrypt"); byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); return TDesEncryptBytes(toEncryptArray, key, useHashing); } /// <summary> /// Ts the DES encrypt bytes. /// </summary> /// <param name="toEncryptArray">To encrypt array.</param> /// <param name="key">The key.</param> /// <param name="useHashing">if set to <c>true</c> [use hashing].</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-02-11</remarks> public static byte[] TDesEncryptBytes(byte[] toEncryptArray, string key, bool useHashing) { if (toEncryptArray == (byte[])null) throw new ArgumentNullException("toEncryptArray"); if (key == (string)null) throw new ArgumentNullException("key"); byte[] keyArray; if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateEncryptor(); return cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); } /// <summary> /// Creates the key block. /// </summary> /// <param name="even">if set to <c>true</c> [even].</param> /// <returns></returns> /// <remarks>Documented by Dev04, 2009-02-11</remarks> private static int CreateKeyBlock(bool even) { int block = 0; block = rand.Next(1000, 9999); while (IsEven(block) != even) { block = CreateKeyBlock(even); } return block; } /// <summary> /// Determines whether the specified block is even. /// </summary> /// <param name="block">The block.</param> /// <returns> /// <c>true</c> if the specified block is even; otherwise, <c>false</c>. /// </returns> /// <remarks>Documented by Dev04, 2009-02-11</remarks> public static bool IsEven(int block) { if ((block < 0) || (block > 9999)) throw new ArgumentOutOfRangeException("0 - 9999", "block"); int lastDigit = block % 10; int total = lastDigit; int nextDigit = (block / 10) % 10; total = total + nextDigit; nextDigit = (block / 100) % 10; total = total + nextDigit; nextDigit = (block / 1000) % 10; total = total + nextDigit; if (total % 2 == 0) return true; else return false; } /// <summary> /// Extracts the public key. /// </summary> /// <param name="PublicKey">The public key.</param> /// <returns></returns> /// <remarks>Documented by Dev04, 2009-02-11</remarks> public static string ExtractPublicKey(string PublicKey) { if (PublicKey == (string)null) throw new ArgumentNullException("PublicKey"); XmlDocument doc = new XmlDocument(); try { doc.LoadXml(PublicKey); } catch (Exception ex) { throw new ArgumentException("Could not extract modulus from key!", "PublicKey", ex); } XmlElement root = doc.DocumentElement; XmlNode node = root.SelectSingleNode("Modulus"); if (node != null) return Base64ToHex(node.InnerText); else throw new ArgumentException("Could not extract modulus from key!", "PublicKey"); } /// <summary> /// Extracts the exponent. /// </summary> /// <param name="PublicKey">The public key.</param> /// <returns></returns> /// <remarks>Documented by Dev04, 2009-02-11</remarks> public static string ExtractExponent(string PublicKey) { if (PublicKey == (string)null) throw new ArgumentNullException("PublicKey"); XmlDocument doc = new XmlDocument(); try { doc.LoadXml(PublicKey); } catch (Exception ex) { throw new ArgumentException("Could not extract exponent from key!", "PublicKey", ex); } XmlElement root = doc.DocumentElement; XmlNode node = root.SelectSingleNode("Exponent"); if (node != null) return Base64ToHex(node.InnerText); else throw new ArgumentException("Could not extract exponent from key!", "PublicKey"); } /// <summary> /// Converts a base64 encoded string to a hex encoded string. /// </summary> /// <param name="base64">The base64.</param> /// <returns></returns> /// <remarks>Documented by Dev04, 2009-02-11</remarks> public static string Base64ToHex(string base64) { if (base64 == (string)null) throw new ArgumentNullException("base64"); return ByteArrayToHexString(Convert.FromBase64String(base64)); } /// <summary> /// Converts a hex encoded string to a base64 encoded string. /// </summary> /// <param name="hex">The hex.</param> /// <returns></returns> /// <remarks>Documented by Dev04, 2009-02-11</remarks> public static string HexToBase64(string hex) { if (hex == (string)null) throw new ArgumentNullException("hex"); return Convert.ToBase64String(HexStringToByteArray(hex)); } /// <summary> /// Converts a byte array to a hex encoded string. /// </summary> /// <param name="Bytes">The bytes.</param> /// <returns></returns> /// <remarks>Documented by Dev04, 2009-02-11</remarks> public static string ByteArrayToHexString(byte[] Bytes) { if (Bytes == (byte[])null) throw new ArgumentNullException("Bytes"); StringBuilder Result = new StringBuilder(); string HexAlphabet = "0123456789ABCDEF"; //string HexAlphabet = "ABCDEFGHIJKLMNOP"; foreach (byte B in Bytes) { Result.Append(HexAlphabet[(int)(B >> 4)]); Result.Append(HexAlphabet[(int)(B & 0xF)]); } return Result.ToString(); } /// <summary> /// Converts a hex encoded string to a byte array. /// </summary> /// <param name="Hex">The hex encoded string.</param> /// <returns></returns> /// <remarks>Documented by Dev04, 2009-02-11</remarks> public static byte[] HexStringToByteArray(string Hex) { if (Hex == (string)null) throw new ArgumentNullException("Hex"); if ((Hex.Length % 2 != 0) || (regHex.Match(Hex).Success)) throw new ArgumentException("Not a hex string!", "Hex"); byte[] Bytes = new byte[Hex.Length / 2]; int[] HexValue = new int[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; for (int x = 0, i = 0; i < Hex.Length; i += 2, x += 1) { Bytes[x] = (byte)(HexValue[Char.ToUpper(Hex[i + 0]) - '0'] << 4 | HexValue[Char.ToUpper(Hex[i + 1]) - '0']); } return Bytes; } /// <summary> /// Shifts the specified param right /// </summary> /// <param name="param">The param.</param> /// <param name="length">The length.</param> /// <returns></returns> /// <remarks>Documented by Dev04, 2009-02-11</remarks> public static string Right(string param, int length) { if (param == (string)null) throw new ArgumentNullException("param"); if (param.Length - length < 0 || param.Length < param.Length - length || length < 0) throw new ArgumentOutOfRangeException("length"); //start at the index based on the lenght of the sting minus //the specified lenght and assign it a variable string result = param.Substring(param.Length - length, length); //return the result of the operation return result; } private static string mid = string.Empty; /// <summary> /// Gets the MID. /// </summary> /// <returns></returns> /// <remarks>Documented by Dev08, 2009-02-12</remarks> public static string GetMID() { lock (mid) { if (mid != string.Empty) return mid; string value; try { value = Identifier("Win32_BaseBoard", "SerialNumber") + Identifier("Win32_Processor", "ProcessorId"); } catch (MachineIDGenerationException mex) { value = getOsMID(); if (value == null) throw mex; } HashAlgorithm hashObject = new RIPEMD160Managed(); byte[] hash = hashObject.ComputeHash(Encoding.ASCII.GetBytes(value)); mid = ByteArrayToCompressedArrayString(hash).Substring(13, 8); return mid; } } /// <summary> /// Returns the MachineGuid created by Microsoft upon installation of the OS. /// Modifying this number on a computer causes problems throughout Windows. /// </summary> /// <returns></returns> /// <remarks>Documented by Dev09, 2009-09-09</remarks> private static string getOsMID() { RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Cryptography"); if (key != null) { string MID = key.GetValue("MachineGuid").ToString(); return MID; } return null; } /// <summary> /// Creates some Strings which will be part of the MID. /// </summary> /// <param name="wmiClass">The WMI class.</param> /// <param name="wmiProperty">The WMI property.</param> /// <returns></returns> /// Documented by FabThe, somewhen /// Updated by MatBre, 10.09.2009 private static string Identifier(string wmiClass, string wmiProperty) { try { if (wmiClass == null || wmiProperty == null || wmiClass == string.Empty || wmiProperty == string.Empty) throw new MachineIDGenerationException(new Exception("One of wmiClass, wmiProperty is either null or empty")); string result = string.Empty; ManagementClass mc = new ManagementClass(wmiClass); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { object temp = mo[wmiProperty]; if (temp != null) return temp.ToString(); } throw new MachineIDGenerationException(new Exception("ManagementObject list is empty")); } catch (Exception ex) { throw new MachineIDGenerationException(ex); } } /// <summary> /// Gets the hashed password. /// </summary> /// <param name="password">The password.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-03-04</remarks> public static string GetHashedPassword(SecureString password) { IntPtr ptr = Marshal.SecureStringToBSTR(password); System.Security.Cryptography.MD5 md5Hasher = System.Security.Cryptography.MD5.Create(); byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(Marshal.PtrToStringUni(ptr))); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); } /// <summary> /// Gets the hashed password. /// </summary> /// <param name="password">The password.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-03-04</remarks> public static string GetHashedPassword(string password) { System.Security.Cryptography.MD5 md5Hasher = System.Security.Cryptography.MD5.Create(); byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(password)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); } /// <summary> /// Checks the user id. /// </summary> /// <param name="value">The value.</param> /// <remarks>Documented by Dev05, 2009-03-04</remarks> public static void CheckUserId(int value) { switch (value) { case -1: throw new InvalidUsernameException("Wrong Username!"); case -2: throw new InvalidPasswordException("Wrong Password!"); case -3: throw new WrongAuthenticationException("Wrong User Authentication"); //allowed regarding DBInformation, but not in Userprofile case -4: throw new ForbiddenAuthenticationException("Forbidden User Authentication"); //not allowed, regarding DatabaseInformation case -5: throw new UserSessionCreationException("The new session could not be created."); //in case the user already has another session open } } /// <summary> /// Private variable for caching WMP version. /// </summary> private static bool? WMP7OrGreater = null; /// <summary> /// Determines whether user has Windows Media Player 7 or greater. /// </summary> /// <returns> /// <c>true</c> if WMP7 or greater; otherwise, <c>false</c>. /// </returns> /// <remarks>Documented by Dev09, 2009-06-05</remarks> public static bool IsWMP7OrGreater() { if (!WMP7OrGreater.HasValue) { try { Guid clsid = new Guid("6BF52A52-394A-11D3-B153-00C04F79FAA6"); System.Type oType = System.Type.GetTypeFromCLSID(clsid, true); object o = System.Activator.CreateInstance(oType); WMP7OrGreater = true; } catch (COMException) { WMP7OrGreater = false; } catch { WMP7OrGreater = true; } } return WMP7OrGreater.Value; } /// <summary> /// Gets the windows media player version. /// </summary> /// <returns>The media player version.</returns> /// <remarks>Documented by Dev03, 2009-07-15</remarks> public static Version GetWindowsMediaPlayerVersion() { try { return new Version(Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MediaPlayer\PlayerUpgrade", "PlayerVersion", "1.0.0.0").ToString().Replace(',', '.')); } catch { } return new Version(); } /// <summary> /// Gets the internet explorer version. /// </summary> /// <returns>The internet explorer version.</returns> /// <remarks>Documented by Dev03, 2009-07-15</remarks> public static Version GetInternetExplorerVersion() { try { return new Version(Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer", "Version", "1.0.0.0").ToString()); } catch { } return new Version(); } /// <summary> /// Gets the learning module hash. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-03-20</remarks> public static byte[] GetLearningModuleHash(string path) { FileStream input = File.OpenRead(path); try { return (new MD5CryptoServiceProvider()).ComputeHash(input); } finally { input.Close(); } } /// <summary> /// Gets the MLifter stick check file. /// </summary> /// <value>The M lifter stick check file.</value> /// <remarks>Documented by Dev05, 2009-04-01</remarks> public static string MLifterStickCheckFile { get { return Settings.Default.MLifterStickCheckFile; } } /// <summary> /// Gets the MLifter sticks attached to this PC. /// </summary> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-03-25</remarks> public static List<DriveInfo> GetMLifterSticks() { List<DriveInfo> drives = new List<DriveInfo>(); foreach (string driveLetter in Environment.GetLogicalDrives()) { if (driveLetter.ToLower().StartsWith("a") || driveLetter.ToLower().StartsWith("b")) //exptect drive letter A: and B: continue; DriveInfo info = new DriveInfo(driveLetter); if (info.DriveType != DriveType.Removable) continue; if (Directory.Exists(Path.Combine(info.RootDirectory.FullName, Settings.Default.MLifterStickCheckFile))) drives.Add(info); } return drives; } public static bool IsOnMLifterStick(string path) { foreach (DriveInfo info in GetMLifterSticks()) if (path.StartsWith(info.RootDirectory.FullName)) return true; return false; } /// <summary> /// Gets the size of the file in a nice string. /// </summary> /// <param name="Bytes">The bytes.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-03-26</remarks> public static string GetFileSize(long Bytes) { return GetFileSize(Bytes, true); } /// <summary> /// Gets the size of the file in a nice string. /// </summary> /// <param name="Bytes">The bytes.</param> /// <param name="showDecimalPlaces">if set to <c>true</c> show decimal places.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-03-26</remarks> public static string GetFileSize(long Bytes, bool showDecimalPlaces) { if (Bytes >= 1073741824) { Decimal size = Decimal.Divide(Bytes, 1073741824); return String.Format("{0:##" + (showDecimalPlaces ? ".##" : string.Empty) + "} GB", size); } else if (Bytes >= 1048576) { Decimal size = Decimal.Divide(Bytes, 1048576); return String.Format("{0:##" + (showDecimalPlaces ? ".##" : string.Empty) + "} MB", size); } else if (Bytes >= 1024) { Decimal size = Decimal.Divide(Bytes, 1024); return String.Format("{0:##" + (showDecimalPlaces ? ".##" : string.Empty) + "} KB", size); } else if (Bytes > 0) { Decimal size = Bytes; return showDecimalPlaces ? String.Format("{0:##" + (showDecimalPlaces ? ".##" : string.Empty) + "} Bytes", size) : "1 KB"; } else { return showDecimalPlaces ? "0 Bytes" : "-"; } } /// <summary> /// Gets the valid path. /// </summary> /// <param name="path">The path.</param> /// <param name="replacement">The replacement.</param> /// <returns></returns> /// <remarks> /// Documented by Dev05, 2009-04-22 /// </remarks> public static string GetValidPathName(string path, string replacement = "_") { StringBuilder file = new StringBuilder(path); foreach (char c in Path.GetInvalidPathChars()) file = file.Replace(c.ToString(), replacement); return file.ToString(); } /// <summary> /// Gets the valid name of the file. /// </summary> /// <param name="filename">The filename.</param> /// <param name="replacement">The replacement.</param> /// <returns></returns> /// <remarks>CFI, 2012-02-09</remarks> public static string GetValidFileName(string filename, string replacement = "_") { StringBuilder file = new StringBuilder(filename); foreach (char c in Path.GetInvalidFileNameChars()) file = file.Replace(c.ToString(), replacement); return file.ToString(); } /// <summary> /// A private cache variable for the value of RunningFromStick. /// </summary> private static bool? isRunningFromStick = null; /// <summary> /// Gets a value indicating whether [running from stick]. /// </summary> /// <value><c>true</c> if [running from stick]; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev02, 2009-07-20</remarks> public static bool IsRunningFromStick() { //Add cache if (isRunningFromStick.HasValue) return isRunningFromStick.Value; DirectoryInfo appPath = new DirectoryInfo(System.Windows.Forms.Application.StartupPath); //check if the app directory is writeable string testfileName = Path.Combine(appPath.FullName, Path.GetRandomFileName()); try { File.Create(testfileName).Close(); File.Delete(testfileName); } catch { isRunningFromStick = false; return false; } //check if the app directory is on a removable drive try { DriveInfo appDrive = new DriveInfo(appPath.Root.FullName); if (appDrive.DriveType == DriveType.Removable) { isRunningFromStick = true; return true; } } catch { } isRunningFromStick = false; return false; } /// <summary> /// Determines whether the specified object1 is equal to object2. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="object1">The object1.</param> /// <param name="object2">The object2.</param> /// <returns> /// <c>true</c> if the specified object1 is equal; otherwise, <c>false</c>. /// </returns> /// <remarks>Documented by Dev05, 2009-11-25</remarks> public static bool IsEqual<T>(T object1, T object2) { try { if (EqualityComparer<T>.Default.Equals(object1, object2)) return true; Type t = typeof(T); if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { if (t.IsAssignableFrom(typeof(int?))) { if (object1 == null && object2 as int? == 0 || object1 as int? == 0 && object2 == null) return true; } if (t.IsAssignableFrom(typeof(string))) { if (object1 == null && object2 as string == string.Empty || object1 as string == string.Empty && object2 == null) return true; } } } catch (Exception exp) { Trace.WriteLine(exp.ToString()); } return false; } } /// <summary> /// WebClient which handles Cookies/Sessions. /// </summary> /// <remarks>Documented by Dev05, 2009-05-08</remarks> public class CookieAwareWebClient : WebClient { private CookieContainer m_container = new CookieContainer(); protected override WebRequest GetWebRequest(Uri address) { WebRequest request = base.GetWebRequest(address); if (request is HttpWebRequest) { (request as HttpWebRequest).CookieContainer = m_container; } return request; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Text; namespace WrtSettings { internal class Nvram { public Nvram(string fileName, NvramFormat format) { try { byte[] buffer; using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { buffer = new byte[(int)stream.Length]; stream.Read(buffer, 0, buffer.Length); } this.Variables = new Dictionary<string, string>(StringComparer.Ordinal); if (((format & NvramFormat.AsuswrtVersion1) != 0) && TryParseAsuswrtVersion1(buffer)) { } else if (((format & NvramFormat.AsuswrtVersion2) != 0) && TryParseAsuswrtVersion2(buffer)) { } else if (((format & NvramFormat.DDWrt) != 0) && TryParseDDWrt(buffer)) { } else if (((format & NvramFormat.Tomato) != 0) && TryParseTomato(buffer)) { } else if (((format & NvramFormat.Text) != 0) && TryParseText(buffer)) { } else { throw new FormatException("Unrecognized format."); } this.FileName = fileName; } catch (FormatException) { throw; } catch (Exception ex) { throw new FormatException(ex.Message); } } public string FileName { get; private set; } public NvramFormat Format { get; set; } public IDictionary<String, String> Variables { get; private set; } public void Save(string fileName) { try { byte[] buffer; switch (this.Format) { case NvramFormat.AsuswrtVersion1: buffer = GetBytesForAsuswrtVersion1(); break; case NvramFormat.AsuswrtVersion2: buffer = GetBytesForAsuswrtVersion2(); break; case NvramFormat.Tomato: buffer = GetBytesForTomato(); break; case NvramFormat.DDWrt: buffer = GetBytesForDDWrt(); break; case NvramFormat.Text: buffer = GetBytesForText(); break; default: throw new InvalidOperationException("Unsupported format!"); } using (var stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Read)) { stream.Write(buffer, 0, buffer.Length); } this.FileName = fileName; } catch (InvalidOperationException) { throw; } catch (Exception ex) { throw new InvalidOperationException(ex.Message); } } #region Open private bool TryParseAsuswrtVersion1(byte[] buffer) { if (buffer.Length < 8) { Debug.WriteLine("NVRAM: Asuswrt 1: File is too small!"); return false; } string header = ToString(buffer, 0, 4); if (!header.Equals("HDR1")) { Debug.WriteLine("NVRAM: Asuswrt 1: Unknown header '" + header + "'!"); return false; } var len = ToUInt32(buffer, 4); if (len > (buffer.Length - 8)) { Debug.WriteLine("NVRAM: Asuswrt 1: length mismatch!"); return false; } //decode variables var lastStart = 8; for (int i = 8; i < len + 8; i++) { if (buffer[i] == 0x00) { if (i != lastStart) { //skip empty ones var variable = Encoding.ASCII.GetString(buffer, lastStart, i - lastStart); Debug.WriteLine("NVRAM: Asuswrt 1: " + variable); var parts = variable.Split(new char[] { '=' }, 2); if (parts.Length == 2) { AddVariable(parts[0], parts[1]); } else { Debug.WriteLine("NVRAM: Asuswrt 1: Cannot parse '" + variable + "'!"); return false; } } lastStart = i + 1; } } this.Format = NvramFormat.AsuswrtVersion1; return true; } private bool TryParseAsuswrtVersion2(byte[] buffer) { if (buffer.Length < 8) { Debug.WriteLine("NVRAM: Asuswrt 2: File is too small!"); return false; } string header = ToString(buffer, 0, 4); if (!header.Equals("HDR2")) { Debug.WriteLine("NVRAM: Asuswrt 2: Unknown header '" + header + "'!"); return false; } var len = ToUInt24(buffer, 4); if (len > (buffer.Length - 8)) { Debug.WriteLine("NVRAM: Asuswrt 2: Length mismatch!"); return false; } //decoding stupid "encryption" var random = buffer[7]; for (int i = 8; i < len + 8; i++) { if (buffer[i] > (0xFD - 0x01)) { buffer[i] = 0x00; } else { buffer[i] = (byte)((0xFF + random - buffer[i]) % 256); } } //decode variables var lastStart = 8; for (int i = 8; i < len + 8; i++) { if (buffer[i] == 0x00) { if (i != lastStart) { //skip empty ones var variable = Encoding.ASCII.GetString(buffer, lastStart, i - lastStart); Debug.WriteLine("NVRAM: Asuswrt 2: " + variable); var parts = variable.Split(new char[] { '=' }, 2); if (parts.Length == 2) { AddVariable(parts[0], parts[1]); } else { Debug.WriteLine("NVRAM: Asuswrt 2: Cannot parse '" + variable + "'!"); return false; } } lastStart = i + 1; } } if (Settings.ShowAsuswrt2Random) { AddVariable(".Random", random.ToString(CultureInfo.InvariantCulture)); } this.Format = NvramFormat.AsuswrtVersion2; return true; } private bool TryParseTomato(byte[] buffer) { try { using (var msIn = new MemoryStream(buffer) { Position = 0 }) using (var msOut = new MemoryStream()) using (var gzStream = new GZipStream(msIn, CompressionMode.Decompress)) { var midBuffer = new byte[65536]; int read; while ((read = gzStream.Read(midBuffer, 0, midBuffer.Length)) > 0) { msOut.Write(midBuffer, 0, read); } buffer = msOut.ToArray(); } } catch (InvalidDataException ex) { Debug.WriteLine("NVRAM: Tomato: Cannot ungzip (" + ex.Message + ")!"); return false; } string header = ToString(buffer, 0, 4); if (!header.Equals("TCF1")) { Debug.WriteLine("NVRAM: Tomato: Unknown header '" + header + "'!"); return false; } //decode variables var lastStart = 8; for (int i = 8; i < buffer.Length; i++) { if (buffer[i] == 0x00) { if (i != lastStart) { //skip empty ones var variable = Encoding.ASCII.GetString(buffer, lastStart, i - lastStart); Debug.WriteLine("NVRAM: Tomato: " + variable); var parts = variable.Split(new char[] { '=' }, 2); if (parts.Length == 2) { AddVariable(parts[0], parts[1]); } else { Debug.WriteLine("NVRAM: Tomato: Cannot parse '" + variable + "'!"); return false; } } lastStart = i + 1; } } var hardwareType = ToUInt32(buffer, 4); AddVariable(".HardwareType", hardwareType.ToString(CultureInfo.InvariantCulture)); this.Format = NvramFormat.Tomato; return true; } private bool TryParseDDWrt(byte[] buffer) { if (buffer.Length < 8) { Debug.WriteLine("NVRAM: DDWrt: File is too small!"); return false; } string header = ToString(buffer, 0, 6); if (!header.Equals("DD-WRT")) { Debug.WriteLine("NVRAM: DDWrt: Unknown header '" + header + "'!"); return false; } var count = ToUInt16(buffer, 6); int count2 = 0; int i = 8; while (i < buffer.Length) { var keyLen = buffer[i]; i += 1; var key = Encoding.ASCII.GetString(buffer, i, keyLen); i += keyLen; var valueLen = ToUInt16(buffer, i); i += 2; var value = Encoding.ASCII.GetString(buffer, i, valueLen); i += valueLen; Debug.WriteLine("NVRAM: DDWrt: " + key + "=" + value); count2 += 1; if (!AddVariable(key, value)) { if (count2 > 1) { count2--; }; } //because we don't add empty entries present in some newer DD-WRT } if (count != count2) { Debug.WriteLine("NVRAM: DDWrt: Length mismatch!"); return false; } this.Format = NvramFormat.DDWrt; return true; } private bool TryParseText(byte[] buffer) { var content = Encoding.ASCII.GetString(buffer); var lines = content.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); foreach (var variable in lines) { Debug.WriteLine("NVRAM: Text: " + variable); var parts = variable.Split(new char[] { '=' }, 2); if (parts.Length == 2) { AddVariable(DecodeText(parts[0]), DecodeText(parts[1])); } else { Debug.WriteLine("NVRAM: Text: Cannot parse '" + variable + "'!"); return false; } } this.Format = NvramFormat.Text; return true; } #endregion #region Save private byte[] GetBytesForAsuswrtVersion1() { var buffer = new List<Byte>(); foreach (var pair in this.Variables) { buffer.AddRange(Encoding.ASCII.GetBytes(pair.Key + "=" + pair.Value + "\0")); } //length has to be multiple of 1024 var len = buffer.Count + (1024 - buffer.Count % 1024); //padding var padding = new byte[len - buffer.Count]; buffer.AddRange(padding); //insert header in reverse order buffer.InsertRange(0, FromUInt32((uint)len)); buffer.InsertRange(0, Encoding.ASCII.GetBytes("HDR1")); return buffer.ToArray(); } private Random Random = new Random(); private byte[] GetBytesForAsuswrtVersion2() { var buffer = new List<Byte>(); byte rand; if (this.Variables.ContainsKey(".Random")) { //use user's value if (!byte.TryParse(this.Variables[".Random"], NumberStyles.Integer, CultureInfo.InvariantCulture, out rand)) { throw new InvalidOperationException("Invalid predefined random number (.Random)!"); } rand %= 30; //limit to 0-29 to match algorithm; might get corrected if it falls in 8-14 range } else { rand = (byte)this.Random.Next(0, 30); } while ((rand >= 8) && (rand <= 13)) { //limiting encryption value to prevent file corruption (https://bitbucket.org/kille72/tomato-arm-kille72/pull-requests/2/mainc-edited-to-fix-random-corruption-of/diff) rand = (byte)this.Random.Next(0, 30); } foreach (var pair in this.Variables) { if (pair.Key.Equals(".Random", StringComparison.Ordinal)) { continue; } //skip random number buffer.AddRange(Encoding.ASCII.GetBytes(pair.Key + "=" + pair.Value + "\0")); } //length has to be multiple of 1024 var len = buffer.Count + (1024 - buffer.Count % 1024); //padding var padding = new byte[len - buffer.Count]; buffer.AddRange(padding); //do stupid "encryption" for (int i = 0; i < buffer.Count; i++) { if (buffer[i] == 0x00) { buffer[i] = (byte)(0xFD + Random.Next(0, 3)); } else { buffer[i] = (byte)((0xFF - buffer[i] + rand) % 256); } } //insert header in reverse order buffer.Insert(0, rand); buffer.InsertRange(0, FromUInt24((uint)len)); buffer.InsertRange(0, Encoding.ASCII.GetBytes("HDR2")); return buffer.ToArray(); } private byte[] GetBytesForTomato() { var buffer = new List<Byte>(); if (!this.Variables.ContainsKey(".HardwareType")) { throw new InvalidOperationException("Data format requires hardware type to be defined (.HardwareType)!"); } var hardwareTypeText = this.Variables[".HardwareType"]; uint hardwareType; if (!uint.TryParse(hardwareTypeText, NumberStyles.Integer, CultureInfo.InvariantCulture, out hardwareType)) { throw new InvalidOperationException("Data format requires hardware type to be defined (.HardwareType) as an integer!"); } buffer.AddRange(Encoding.ASCII.GetBytes("TCF1")); buffer.AddRange(FromUInt32(hardwareType)); foreach (var pair in this.Variables) { if (pair.Key.Equals(".HardwareType", StringComparison.Ordinal)) { continue; } //skip virtual keys buffer.AddRange(Encoding.ASCII.GetBytes(pair.Key + "=" + pair.Value + "\0")); } buffer.Add(0); //add one more null byte for end using (var msOut = new MemoryStream()) { using (var gzStream = new GZipStream(msOut, CompressionMode.Compress)) { gzStream.Write(buffer.ToArray(), 0, buffer.Count); } //must close stream before returning array (or flush) return msOut.ToArray(); } } private byte[] GetBytesForDDWrt() { var buffer = new List<Byte>(); buffer.AddRange(Encoding.ASCII.GetBytes("DD-WRT")); buffer.AddRange(FromUInt16((ushort)this.Variables.Count)); foreach (var pair in this.Variables) { if (pair.Key.StartsWith("wl_", StringComparison.Ordinal)) { //save wl_ entries first if (pair.Key.Length > 255) { throw new InvalidOperationException("Cannot have key longer than 255 bytes"); } if (pair.Value.Length > 65535) { throw new InvalidOperationException("Cannot have value longer than 65535 bytes"); } buffer.Add((byte)pair.Key.Length); buffer.AddRange(Encoding.ASCII.GetBytes(pair.Key)); buffer.AddRange(FromUInt16((ushort)pair.Value.Length)); buffer.AddRange(Encoding.ASCII.GetBytes(pair.Value)); } } foreach (var pair in this.Variables) { if (!pair.Key.StartsWith("wl_", StringComparison.Ordinal)) { if (pair.Key.Length > 255) { throw new InvalidOperationException("Cannot have key longer than 255 bytes"); } if (pair.Value.Length > 65535) { throw new InvalidOperationException("Cannot have value longer than 65535 bytes"); } buffer.Add((byte)pair.Key.Length); buffer.AddRange(Encoding.ASCII.GetBytes(pair.Key)); buffer.AddRange(FromUInt16((ushort)pair.Value.Length)); buffer.AddRange(Encoding.ASCII.GetBytes(pair.Value)); } } return buffer.ToArray(); } private byte[] GetBytesForText() { var list = new List<string>(); foreach (var pair in this.Variables) { list.Add(string.Format(CultureInfo.InvariantCulture, "{0}={1}", EncodeText(pair.Key), EncodeText(pair.Value))); } list.Sort(); var sb = new StringBuilder(); foreach (var item in list) { sb.AppendLine(item); } return Encoding.ASCII.GetBytes(sb.ToString()); } #endregion #region Helpers private static UInt16 ToUInt16(byte[] buffer, int offset) { return BitConverter.ToUInt16(buffer, offset); } private static byte[] FromUInt16(UInt16 value) { return BitConverter.GetBytes(value); } private static UInt32 ToUInt24(byte[] buffer, int offset) { var bufferAlt = new byte[4]; Buffer.BlockCopy(buffer, offset, bufferAlt, 0, 3); return BitConverter.ToUInt32(bufferAlt, 0); } private static byte[] FromUInt24(UInt32 value) { var buffer = BitConverter.GetBytes(value); return new byte[] { buffer[0], buffer[1], buffer[2] }; } private static UInt32 ToUInt32(byte[] buffer, int offset) { return BitConverter.ToUInt32(buffer, offset); } private static byte[] FromUInt32(UInt32 value) { return BitConverter.GetBytes(value); } private static string ToString(byte[] buffer, int offset, int count) { return Encoding.ASCII.GetString(buffer, offset, count); } private bool AddVariable(string key, string value) { if (string.IsNullOrEmpty(key)) { return false; } //newer DD-WRT might have multiple empty key/value pairs if (!this.Variables.ContainsKey(key)) { this.Variables.Add(key, value); return true; } else { this.Variables[key] = value; return false; } } internal static string EncodeText(string text) { var sb = new StringBuilder(); foreach (var ch in text) { if (ch == '\n') { sb.Append(@"\n"); } else if (ch == '\r') { sb.Append(@"\r"); } else if (ch == '\t') { sb.Append(@"\t"); } else if (ch == '\b') { sb.Append(@"\b"); } else if (ch == '\f') { sb.Append(@"\f"); } else if (ch == '\\') { sb.Append(@"\\"); } else { var value = Encoding.ASCII.GetBytes(new char[] { ch })[0]; if ((value < 32) || (value > 127)) { sb.AppendFormat(CultureInfo.InvariantCulture, @"\x{0:X2}", value); } else { sb.Append(ch); } } } return sb.ToString(); } internal static string DecodeText(string text) { var sb = new StringBuilder(); var sbHex = new StringBuilder(); var state = DTState.Text; foreach (var ch in text) { switch (state) { case DTState.Text: { if (ch == '\\') { state = DTState.Escape; } else { sb.Append(ch); } } break; case DTState.Escape: { switch (ch) { case 'n': sb.Append("\n"); state = DTState.Text; break; case 'r': sb.Append("\r"); state = DTState.Text; break; case 't': sb.Append("\t"); state = DTState.Text; break; case 'b': sb.Append("\b"); state = DTState.Text; break; case 'f': sb.Append("\f"); state = DTState.Text; break; case '\\': sb.Append(@"\"); state = DTState.Text; break; case 'x': state = DTState.EscapeHex; break; default: throw new FormatException("Invalid escape sequence."); } } break; case DTState.EscapeHex: { sbHex.Append(ch); if (sbHex.Length == 2) { var hex = sbHex.ToString(); sbHex.Length = 0; byte value; if (!byte.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value)) { throw new FormatException("Invalid hexadecimal escape sequence."); } sb.Append(Encoding.ASCII.GetString(new byte[] { value })); state = DTState.Text; } } break; } } if (state == DTState.Text) { return sb.ToString(); } else { throw new FormatException("Invalid character sequence."); } } private enum DTState { Text, Escape, EscapeHex } #endregion } [Flags] internal enum NvramFormat { AsuswrtVersion1 = 1, AsuswrtVersion2 = 2, Tomato = 4, DDWrt = 8, Text = 0x40000000, All = 0x7FFFFFFF, } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Linq; using System.Windows.Markup; using Prism.Properties; namespace Prism.Modularity { /// <summary> /// The <see cref="ModuleCatalog"/> holds information about the modules that can be used by the /// application. Each module is described in a <see cref="ModuleInfo"/> class, that records the /// name, type and location of the module. /// /// It also verifies that the <see cref="ModuleCatalog"/> is internally valid. That means that /// it does not have: /// <list> /// <item>Circular dependencies</item> /// <item>Missing dependencies</item> /// <item> /// Invalid dependencies, such as a Module that's loaded at startup that depends on a module /// that might need to be retrieved. /// </item> /// </list> /// The <see cref="ModuleCatalog"/> also serves as a baseclass for more specialized Catalogs . /// </summary> [ContentProperty("Items")] public class ModuleCatalog : IModuleCatalog { private readonly ModuleCatalogItemCollection items; private bool isLoaded; /// <summary> /// Initializes a new instance of the <see cref="ModuleCatalog"/> class. /// </summary> public ModuleCatalog() { this.items = new ModuleCatalogItemCollection(); this.items.CollectionChanged += this.ItemsCollectionChanged; } /// <summary> /// Initializes a new instance of the <see cref="ModuleCatalog"/> class while providing an /// initial list of <see cref="ModuleInfo"/>s. /// </summary> /// <param name="modules">The initial list of modules.</param> public ModuleCatalog(IEnumerable<ModuleInfo> modules) : this() { if (modules == null) throw new System.ArgumentNullException("modules"); foreach (ModuleInfo moduleInfo in modules) { this.Items.Add(moduleInfo); } } /// <summary> /// Gets the items in the <see cref="ModuleCatalog"/>. This property is mainly used to add <see cref="ModuleInfoGroup"/>s or /// <see cref="ModuleInfo"/>s through XAML. /// </summary> /// <value>The items in the catalog.</value> public Collection<IModuleCatalogItem> Items { get { return this.items; } } /// <summary> /// Gets all the <see cref="ModuleInfo"/> classes that are in the <see cref="ModuleCatalog"/>, regardless /// if they are within a <see cref="ModuleInfoGroup"/> or not. /// </summary> /// <value>The modules.</value> public virtual IEnumerable<ModuleInfo> Modules { get { return this.GrouplessModules.Union(this.Groups.SelectMany(g => g)); } } /// <summary> /// Gets the <see cref="ModuleInfoGroup"/>s that have been added to the <see cref="ModuleCatalog"/>. /// </summary> /// <value>The groups.</value> public IEnumerable<ModuleInfoGroup> Groups { get { return this.Items.OfType<ModuleInfoGroup>(); } } /// <summary> /// Gets or sets a value that remembers whether the <see cref="ModuleCatalog"/> has been validated already. /// </summary> protected bool Validated { get; set; } /// <summary> /// Returns the list of <see cref="ModuleInfo"/>s that are not contained within any <see cref="ModuleInfoGroup"/>. /// </summary> /// <value>The groupless modules.</value> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Groupless")] protected IEnumerable<ModuleInfo> GrouplessModules { get { return this.Items.OfType<ModuleInfo>(); } } /// <summary> /// Creates a <see cref="ModuleCatalog"/> from XAML. /// </summary> /// <param name="xamlStream"><see cref="Stream"/> that contains the XAML declaration of the catalog.</param> /// <returns>An instance of <see cref="ModuleCatalog"/> built from the XAML.</returns> public static ModuleCatalog CreateFromXaml(Stream xamlStream) { if (xamlStream == null) { throw new ArgumentNullException("xamlStream"); } return XamlReader.Load(xamlStream) as ModuleCatalog; } /// <summary> /// Creates a <see cref="ModuleCatalog"/> from a XAML included as an Application Resource. /// </summary> /// <param name="builderResourceUri">Relative <see cref="Uri"/> that identifies the XAML included as an Application Resource.</param> /// <returns>An instance of <see cref="ModuleCatalog"/> build from the XAML.</returns> public static ModuleCatalog CreateFromXaml(Uri builderResourceUri) { var streamInfo = System.Windows.Application.GetResourceStream(builderResourceUri); if ((streamInfo != null) && (streamInfo.Stream != null)) { return CreateFromXaml(streamInfo.Stream); } return null; } /// <summary> /// Loads the catalog if necessary. /// </summary> public void Load() { this.isLoaded = true; this.InnerLoad(); } /// <summary> /// Return the list of <see cref="ModuleInfo"/>s that <paramref name="moduleInfo"/> depends on. /// </summary> /// <remarks> /// If the <see cref="ModuleCatalog"/> was not yet validated, this method will call <see cref="Validate"/>. /// </remarks> /// <param name="moduleInfo">The <see cref="ModuleInfo"/> to get the </param> /// <returns>An enumeration of <see cref="ModuleInfo"/> that <paramref name="moduleInfo"/> depends on.</returns> public virtual IEnumerable<ModuleInfo> GetDependentModules(ModuleInfo moduleInfo) { this.EnsureCatalogValidated(); return this.GetDependentModulesInner(moduleInfo); } /// <summary> /// Returns a list of <see cref="ModuleInfo"/>s that contain both the <see cref="ModuleInfo"/>s in /// <paramref name="modules"/>, but also all the modules they depend on. /// </summary> /// <param name="modules">The modules to get the dependencies for.</param> /// <returns> /// A list of <see cref="ModuleInfo"/> that contains both all <see cref="ModuleInfo"/>s in <paramref name="modules"/> /// but also all the <see cref="ModuleInfo"/> they depend on. /// </returns> public virtual IEnumerable<ModuleInfo> CompleteListWithDependencies(IEnumerable<ModuleInfo> modules) { if (modules == null) { throw new ArgumentNullException("modules"); } this.EnsureCatalogValidated(); List<ModuleInfo> completeList = new List<ModuleInfo>(); List<ModuleInfo> pendingList = modules.ToList(); while (pendingList.Count > 0) { ModuleInfo moduleInfo = pendingList[0]; foreach (ModuleInfo dependency in this.GetDependentModules(moduleInfo)) { if (!completeList.Contains(dependency) && !pendingList.Contains(dependency)) { pendingList.Add(dependency); } } pendingList.RemoveAt(0); completeList.Add(moduleInfo); } IEnumerable<ModuleInfo> sortedList = this.Sort(completeList); return sortedList; } /// <summary> /// Validates the <see cref="ModuleCatalog"/>. /// </summary> /// <exception cref="ModularityException">When validation of the <see cref="ModuleCatalog"/> fails.</exception> public virtual void Validate() { this.ValidateUniqueModules(); this.ValidateDependencyGraph(); this.ValidateCrossGroupDependencies(); this.ValidateDependenciesInitializationMode(); this.Validated = true; } /// <summary> /// Adds a <see cref="ModuleInfo"/> to the <see cref="ModuleCatalog"/>. /// </summary> /// <param name="moduleInfo">The <see cref="ModuleInfo"/> to add.</param> /// <returns>The <see cref="ModuleCatalog"/> for easily adding multiple modules.</returns> public virtual void AddModule(ModuleInfo moduleInfo) { this.Items.Add(moduleInfo); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(Type moduleType, params string[] dependsOn) { return this.AddModule(moduleType, InitializationMode.WhenAvailable, dependsOn); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="initializationMode">Stage on which the module to be added will be initialized.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(Type moduleType, InitializationMode initializationMode, params string[] dependsOn) { if (moduleType == null) throw new System.ArgumentNullException("moduleType"); return this.AddModule(moduleType.Name, moduleType.AssemblyQualifiedName, initializationMode, dependsOn); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleName">Name of the module to be added.</param> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(string moduleName, string moduleType, params string[] dependsOn) { return this.AddModule(moduleName, moduleType, InitializationMode.WhenAvailable, dependsOn); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleName">Name of the module to be added.</param> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="initializationMode">Stage on which the module to be added will be initialized.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(string moduleName, string moduleType, InitializationMode initializationMode, params string[] dependsOn) { return this.AddModule(moduleName, moduleType, null, initializationMode, dependsOn); } /// <summary> /// Adds a groupless <see cref="ModuleInfo"/> to the catalog. /// </summary> /// <param name="moduleName">Name of the module to be added.</param> /// <param name="moduleType"><see cref="Type"/> of the module to be added.</param> /// <param name="refValue">Reference to the location of the module to be added assembly.</param> /// <param name="initializationMode">Stage on which the module to be added will be initialized.</param> /// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param> /// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns> public ModuleCatalog AddModule(string moduleName, string moduleType, string refValue, InitializationMode initializationMode, params string[] dependsOn) { if (moduleName == null) { throw new ArgumentNullException("moduleName"); } if (moduleType == null) { throw new ArgumentNullException("moduleType"); } ModuleInfo moduleInfo = new ModuleInfo(moduleName, moduleType); moduleInfo.DependsOn.AddRange(dependsOn); moduleInfo.InitializationMode = initializationMode; moduleInfo.Ref = refValue; this.Items.Add(moduleInfo); return this; } /// <summary> /// Initializes the catalog, which may load and validate the modules. /// </summary> /// <exception cref="ModularityException">When validation of the <see cref="ModuleCatalog"/> fails, because this method calls <see cref="Validate"/>.</exception> public virtual void Initialize() { if (!this.isLoaded) { this.Load(); } this.Validate(); } /// <summary> /// Creates and adds a <see cref="ModuleInfoGroup"/> to the catalog. /// </summary> /// <param name="initializationMode">Stage on which the module group to be added will be initialized.</param> /// <param name="refValue">Reference to the location of the module group to be added.</param> /// <param name="moduleInfos">Collection of <see cref="ModuleInfo"/> included in the group.</param> /// <returns><see cref="ModuleCatalog"/> with the added module group.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")] public virtual ModuleCatalog AddGroup(InitializationMode initializationMode, string refValue, params ModuleInfo[] moduleInfos) { if (moduleInfos == null) throw new System.ArgumentNullException("moduleInfos"); ModuleInfoGroup newGroup = new ModuleInfoGroup(); newGroup.InitializationMode = initializationMode; newGroup.Ref = refValue; foreach (ModuleInfo info in moduleInfos) { newGroup.Add(info); } this.items.Add(newGroup); return this; } /// <summary> /// Checks for cyclic dependencies, by calling the dependencysolver. /// </summary> /// <param name="modules">the.</param> /// <returns></returns> protected static string[] SolveDependencies(IEnumerable<ModuleInfo> modules) { if (modules == null) throw new System.ArgumentNullException("modules"); ModuleDependencySolver solver = new ModuleDependencySolver(); foreach (ModuleInfo data in modules) { solver.AddModule(data.ModuleName); if (data.DependsOn != null) { foreach (string dependency in data.DependsOn) { solver.AddDependency(data.ModuleName, dependency); } } } if (solver.ModuleCount > 0) { return solver.Solve(); } return new string[0]; } /// <summary> /// Ensures that all the dependencies within <paramref name="modules"/> refer to <see cref="ModuleInfo"/>s /// within that list. /// </summary> /// <param name="modules">The modules to validate modules for.</param> /// <exception cref="ModularityException"> /// Throws if a <see cref="ModuleInfo"/> in <paramref name="modules"/> depends on a module that's /// not in <paramref name="modules"/>. /// </exception> /// <exception cref="System.ArgumentNullException">Throws if <paramref name="modules"/> is <see langword="null"/>.</exception> protected static void ValidateDependencies(IEnumerable<ModuleInfo> modules) { if (modules == null) throw new System.ArgumentNullException("modules"); var moduleNames = modules.Select(m => m.ModuleName).ToList(); foreach (ModuleInfo moduleInfo in modules) { if (moduleInfo.DependsOn != null && moduleInfo.DependsOn.Except(moduleNames).Any()) { throw new ModularityException( moduleInfo.ModuleName, String.Format(CultureInfo.CurrentCulture, Resources.ModuleDependenciesNotMetInGroup, moduleInfo.ModuleName)); } } } /// <summary> /// Does the actual work of loading the catalog. The base implementation does nothing. /// </summary> protected virtual void InnerLoad() { } /// <summary> /// Sorts a list of <see cref="ModuleInfo"/>s. This method is called by <see cref="CompleteListWithDependencies"/> /// to return a sorted list. /// </summary> /// <param name="modules">The <see cref="ModuleInfo"/>s to sort.</param> /// <returns>Sorted list of <see cref="ModuleInfo"/>s</returns> protected virtual IEnumerable<ModuleInfo> Sort(IEnumerable<ModuleInfo> modules) { foreach (string moduleName in SolveDependencies(modules)) { yield return modules.First(m => m.ModuleName == moduleName); } } /// <summary> /// Makes sure all modules have an Unique name. /// </summary> /// <exception cref="DuplicateModuleException"> /// Thrown if the names of one or more modules are not unique. /// </exception> protected virtual void ValidateUniqueModules() { List<string> moduleNames = this.Modules.Select(m => m.ModuleName).ToList(); string duplicateModule = moduleNames.FirstOrDefault( m => moduleNames.Count(m2 => m2 == m) > 1); if (duplicateModule != null) { throw new DuplicateModuleException(duplicateModule, String.Format(CultureInfo.CurrentCulture, Resources.DuplicatedModule, duplicateModule)); } } /// <summary> /// Ensures that there are no cyclic dependencies. /// </summary> protected virtual void ValidateDependencyGraph() { SolveDependencies(this.Modules); } /// <summary> /// Ensures that there are no dependencies between modules on different groups. /// </summary> /// <remarks> /// A groupless module can only depend on other groupless modules. /// A module within a group can depend on other modules within the same group and/or on groupless modules. /// </remarks> protected virtual void ValidateCrossGroupDependencies() { ValidateDependencies(this.GrouplessModules); foreach (ModuleInfoGroup group in this.Groups) { ValidateDependencies(this.GrouplessModules.Union(group)); } } /// <summary> /// Ensures that there are no modules marked to be loaded <see cref="InitializationMode.WhenAvailable"/> /// depending on modules loaded <see cref="InitializationMode.OnDemand"/> /// </summary> protected virtual void ValidateDependenciesInitializationMode() { ModuleInfo moduleInfo = this.Modules.FirstOrDefault( m => m.InitializationMode == InitializationMode.WhenAvailable && this.GetDependentModulesInner(m) .Any(dependency => dependency.InitializationMode == InitializationMode.OnDemand)); if (moduleInfo != null) { throw new ModularityException( moduleInfo.ModuleName, String.Format(CultureInfo.CurrentCulture, Resources.StartupModuleDependsOnAnOnDemandModule, moduleInfo.ModuleName)); } } /// <summary> /// Returns the <see cref="ModuleInfo"/> on which the received module dependens on. /// </summary> /// <param name="moduleInfo">Module whose dependant modules are requested.</param> /// <returns>Collection of <see cref="ModuleInfo"/> dependants of <paramref name="moduleInfo"/>.</returns> protected virtual IEnumerable<ModuleInfo> GetDependentModulesInner(ModuleInfo moduleInfo) { return this.Modules.Where(dependantModule => moduleInfo.DependsOn.Contains(dependantModule.ModuleName)); } /// <summary> /// Ensures that the catalog is validated. /// </summary> protected virtual void EnsureCatalogValidated() { if (!this.Validated) { this.Validate(); } } private void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (this.Validated) { this.EnsureCatalogValidated(); } } private class ModuleCatalogItemCollection : Collection<IModuleCatalogItem>, INotifyCollectionChanged { public event NotifyCollectionChangedEventHandler CollectionChanged; protected override void InsertItem(int index, IModuleCatalogItem item) { base.InsertItem(index, item); this.OnNotifyCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); } protected void OnNotifyCollectionChanged(NotifyCollectionChangedEventArgs eventArgs) { if (this.CollectionChanged != null) { this.CollectionChanged(this, eventArgs); } } } } }
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 API_GrupoE.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.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using DotVVM.Framework.ViewModel; using Microsoft.AspNetCore.Mvc; using NJsonSchema; using NJsonSchema.CodeGeneration; using NSwag; using NSwag.CodeGeneration.CSharp; using NSwag.CodeGeneration.OperationNameGenerators; using NSwag.CodeGeneration.TypeScript; using NSwag.Generation.WebApi; namespace DotVVM.Samples.BasicSamples.Api.AspNetCore.ViewModels { public class GeneratorViewModel : DotvvmViewModelBase { public string CSharpPath { get; set; } = "d:\\temp\\SwaggerTest\\ApiClient.cs"; public string TSPath { get; set; } = "d:\\temp\\SwaggerTest\\ApiClient.ts"; public string Namespace { get; set; } = "MyClientNamespace"; public async Task GenerateCSharp() { var document = await GetSwaggerDocument(); var settings = new CSharpClientGeneratorSettings() { GenerateSyncMethods = true, OperationNameGenerator = new CustomNameGenerator(), GenerateOptionalParameters = true, }; settings.CSharpGeneratorSettings.Namespace = Namespace; settings.CSharpGeneratorSettings.PropertyNameGenerator = new MyPropertyNameGenerator(c => ConversionUtilities.ConvertToUpperCamelCase(c, true)); var generator = new CSharpClientGenerator(document, settings); Context.ReturnFile(Encoding.UTF8.GetBytes(generator.GenerateFile()), "ApiClient.cs", "text/plain"); //File.WriteAllText(CSharpPath, generator.GenerateFile()); } public async Task GenerateTS() { var document = await GetSwaggerDocument(); var settings = new TypeScriptClientGeneratorSettings() { Template = TypeScriptTemplate.Fetch, OperationNameGenerator = new CustomNameGenerator() }; settings.TypeScriptGeneratorSettings.PropertyNameGenerator = new MyPropertyNameGenerator(c => ConversionUtilities.ConvertToLowerCamelCase(c, true)); settings.TypeScriptGeneratorSettings.NullValue = NJsonSchema.CodeGeneration.TypeScript.TypeScriptNullValue.Null; var generator = new TypeScriptClientGenerator(document, settings); var ts = generator.GenerateFile(); ts = "namespace " + Namespace + " {\n" + ConversionUtilities.Tab(ts, 1).TrimEnd('\n') + "\n}\n"; Context.ReturnFile(Encoding.UTF8.GetBytes(ts), "ApiClient.ts", "text/plain"); //File.WriteAllText(TSPath, generator.GenerateFile()); } public async Task GenerateSwagger() { var settings = new WebApiOpenApiDocumentGeneratorSettings(); var generator = new WebApiOpenApiDocumentGenerator(settings); var controllers = typeof(GeneratorViewModel) .Assembly.GetTypes() .Where(t => typeof(Controller).IsAssignableFrom(t)); var d = await generator.GenerateForControllersAsync(controllers); Context.ReturnFile(Encoding.UTF8.GetBytes(d.ToJson()), "WebApi.swagger.json", "text/json"); } private async Task<OpenApiDocument> GetSwaggerDocument() { // Workaround: NSwag semm to have a bug in enum handling void editEnumType(JsonSchema type) { if (type.IsEnumeration && type.Type == JsonObjectType.None) type.Type = JsonObjectType.Integer; foreach (var t in type.Properties.Values) editEnumType(t); } // var d = await SwaggerDocument.FromFileAsync("c:/users/exyi/Downloads/github-swagger.json"); var settings = new WebApiOpenApiDocumentGeneratorSettings(); var generator = new WebApiOpenApiDocumentGenerator(settings); var controllers = typeof(GeneratorViewModel) .Assembly.GetTypes() .Where(t => typeof(Controller).IsAssignableFrom(t)); var d = await generator.GenerateForControllersAsync(controllers); this.PopulateOperationIds(d); foreach (var t in d.Definitions.Values) editEnumType(t); return d; } private void PopulateOperationIds(OpenApiDocument d) { // Generate missing IDs foreach (var operation in d.Operations.Where(o => string.IsNullOrEmpty(o.Operation.OperationId))) operation.Operation.OperationId = GetOperationNameFromPath(operation); void consolidateGroup(string name, OpenApiOperationDescription[] operations) { if (operations.Count() == 1) return; // Append "All" if possible if (!name.EndsWith("All") && !d.Operations.Any(n => n.Operation.OperationId == name + "All")) { var arrayResponseOperations = operations.Where( a => a.Operation.Responses.Any(r => HttpUtilities.IsSuccessStatusCode(r.Key) && r.Value.Schema != null && r.Value.Schema.Type == JsonObjectType.Array)).ToArray(); foreach (var op in arrayResponseOperations) { op.Operation.OperationId = name + "All"; } if (arrayResponseOperations.Length > 0) { consolidateGroup(name + "All", arrayResponseOperations); consolidateGroup(name, operations.Except(arrayResponseOperations).ToArray()); return; } } // Add numbers var i = 2; foreach (var operation in operations.Skip(1)) { while (d.Operations.Any(o => o.Operation.OperationId == name + i)) i++; operation.Operation.OperationId = name + i++; } } // Find non-unique operation IDs foreach (var group in d.Operations.GroupBy(o => o.Operation.OperationId)) { var operations = group.ToList(); consolidateGroup(group.Key, group.ToArray()); } } private string GetOperationNameFromPath(OpenApiOperationDescription operation) { var pathSegments = operation.Path.Trim('/').Split('/').Where(s => !s.Contains('{')).ToArray(); var lastPathSegment = pathSegments.LastOrDefault(); var path = string.Concat(pathSegments.Take(pathSegments.Length - 1).Select(s => s + "_")); return path + operation.Method.ToString()[0].ToString().ToUpperInvariant() + operation.Method.ToString().Substring(1).ToLowerInvariant() + ConversionUtilities.ConvertToUpperCamelCase(lastPathSegment.Replace('_', '-'), false); } } public class MyPropertyNameGenerator : IPropertyNameGenerator { private readonly Func<string, string> editCasing; public MyPropertyNameGenerator(Func<string, string> editCasing) { this.editCasing = editCasing; } public string Generate(JsonSchemaProperty property) { if (!property.Name.All(c => char.IsLetterOrDigit(c) || c == '.' || c == '-' || c == '_' || c == '+')) // crazy property name, encode it in hex return editCasing("prop_" + BitConverter.ToString(Encoding.UTF8.GetBytes(property.Name))); else return editCasing( property.Name.Replace("@", "") .Replace(".", "-") .Replace("+", "Plus")) .Replace('-', '_'); } } /// <summary>Generates multiple clients and operation names based on the Swagger operation ID (underscore separated).</summary> public class CustomNameGenerator : IOperationNameGenerator { /// <summary>Gets a value indicating whether the generator supports multiple client classes.</summary> public bool SupportsMultipleClients { get; } = true; /// <summary>Gets the client name for a given operation (may be empty).</summary> /// <param name="document">The Swagger document.</param> /// <param name="path">The HTTP path.</param> /// <param name="operation">The operation.</param> /// <returns>The client name.</returns> public string GetClientName(OpenApiDocument document, string path, string httpMethod, OpenApiOperation operation) { return GetClientName(operation); } /// <summary>Gets the operation name for a given operation.</summary> /// <param name="document">The Swagger document.</param> /// <param name="path">The HTTP path.</param> /// <param name="operation">The operation.</param> /// <returns>The operation name.</returns> public string GetOperationName(OpenApiDocument document, string path, string httpMethod, OpenApiOperation operation) { var clientName = GetClientName(operation); var operationName = GetOperationName(operation); var hasOperationWithSameName = document.Operations .Where(o => o.Operation != operation) .Any(o => GetClientName(o.Operation) == clientName && GetOperationName(o.Operation) == operationName); if (hasOperationWithSameName) { if (operationName.ToLowerInvariant().StartsWith("get")) { var isArrayResponse = operation.Responses.ContainsKey("200") && operation.Responses["200"].Schema != null && operation.Responses["200"].Schema.Type.HasFlag(JsonObjectType.Array); if (isArrayResponse) return "GetAll" + operationName.Substring(3); } } return operationName; } private string GetClientName(OpenApiOperation operation) { var segments = operation.OperationId.Split('_').ToArray(); return segments.Length >= 2 ? segments[0] : string.Empty; } private string GetOperationName(OpenApiOperation operation) { var segments = operation.OperationId.Split('_').ToArray(); if (segments.Length >= 2) segments = segments.Skip(1).ToArray(); return segments.Length > 0 ? ConversionUtilities.ConvertToUpperCamelCase(string.Join("-", segments), true) : "Index"; } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityModel; using IdentityServer4.Events; using IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Services; using IdentityServer4.Stores; using IdentityServer4.Test; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Linq; using System.Threading.Tasks; namespace IdentityServer4.Quickstart.UI { /// <summary> /// This sample controller implements a typical login/logout/provision workflow for local and external accounts. /// The login service encapsulates the interactions with the user data store. This data store is in-memory only and cannot be used for production! /// The interaction service provides a way for the UI to communicate with identityserver for validation and context retrieval /// </summary> [SecurityHeaders] [AllowAnonymous] public class AccountController : Controller { private readonly TestUserStore _users; private readonly IIdentityServerInteractionService _interaction; private readonly IClientStore _clientStore; private readonly IAuthenticationSchemeProvider _schemeProvider; private readonly IEventService _events; public AccountController( IIdentityServerInteractionService interaction, IClientStore clientStore, IAuthenticationSchemeProvider schemeProvider, IEventService events, TestUserStore users = null) { // if the TestUserStore is not in DI, then we'll just use the global users collection // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity) _users = users ?? new TestUserStore(TestUsers.Users); _interaction = interaction; _clientStore = clientStore; _schemeProvider = schemeProvider; _events = events; } /// <summary> /// Entry point into the login workflow /// </summary> [HttpGet] public async Task<IActionResult> Login(string returnUrl) { // build a model so we know what to show on the login page var vm = await BuildLoginViewModelAsync(returnUrl); if (vm.IsExternalLoginOnly) { // we only have one option for logging in and it's an external provider return RedirectToAction("Challenge", "External", new { provider = vm.ExternalLoginScheme, returnUrl }); } return View(vm); } /// <summary> /// Handle postback from username/password login /// </summary> [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginInputModel model, string button) { // check if we are in the context of an authorization request var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl); // the user clicked the "cancel" button if (button != "login") { if (context != null) { // if the user cancels, send a result back into IdentityServer as if they // denied the consent (even if this client does not require consent). // this will send back an access denied OIDC error response to the client. await _interaction.GrantConsentAsync(context, ConsentResponse.Denied); // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl }); } return Redirect(model.ReturnUrl); } else { // since we don't have a valid context, then we just go back to the home page return Redirect("~/"); } } if (ModelState.IsValid) { // validate username/password against in-memory store if (_users.ValidateCredentials(model.Username, model.Password)) { var user = _users.FindByUsername(model.Username); await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username, clientId: context?.ClientId)); // only set explicit expiration here if user chooses "remember me". // otherwise we rely upon expiration configured in cookie middleware. AuthenticationProperties props = null; if (AccountOptions.AllowRememberLogin && model.RememberLogin) { props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration) }; }; // issue authentication cookie with subject ID and username var isUser = new IdentityServerUser(user.SubjectId) { DisplayName = user.Username }; await HttpContext.SignInAsync(isUser, props); if (context != null) { if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl }); } // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null return Redirect(model.ReturnUrl); } // request for a local page if (Url.IsLocalUrl(model.ReturnUrl)) { return Redirect(model.ReturnUrl); } else if (string.IsNullOrEmpty(model.ReturnUrl)) { return Redirect("~/"); } else { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } } await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials", clientId:context?.ClientId)); ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage); } // something went wrong, show form with error var vm = await BuildLoginViewModelAsync(model); return View(vm); } /// <summary> /// Show logout page /// </summary> [HttpGet] public async Task<IActionResult> Logout(string logoutId) { // build a model so the logout page knows what to display var vm = await BuildLogoutViewModelAsync(logoutId); if (vm.ShowLogoutPrompt == false) { // if the request for logout was properly authenticated from IdentityServer, then // we don't need to show the prompt and can just log the user out directly. return await Logout(vm); } return View(vm); } /// <summary> /// Handle logout page postback /// </summary> [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Logout(LogoutInputModel model) { // build a model so the logged out page knows what to display var vm = await BuildLoggedOutViewModelAsync(model.LogoutId); if (User?.Identity.IsAuthenticated == true) { // delete local authentication cookie await HttpContext.SignOutAsync(); // raise the logout event await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName())); } // check if we need to trigger sign-out at an upstream identity provider if (vm.TriggerExternalSignout) { // build a return URL so the upstream provider will redirect back // to us after the user has logged out. this allows us to then // complete our single sign-out processing. string url = Url.Action("Logout", new { logoutId = vm.LogoutId }); // this triggers a redirect to the external provider for sign-out return SignOut(new AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme); } return View("LoggedOut", vm); } [HttpGet] public IActionResult AccessDenied() { return View(); } /*****************************************/ /* helper APIs for the AccountController */ /*****************************************/ private async Task<LoginViewModel> BuildLoginViewModelAsync(string returnUrl) { var context = await _interaction.GetAuthorizationContextAsync(returnUrl); if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null) { var local = context.IdP == IdentityServer4.IdentityServerConstants.LocalIdentityProvider; // this is meant to short circuit the UI and only trigger the one external IdP var vm = new LoginViewModel { EnableLocalLogin = local, ReturnUrl = returnUrl, Username = context?.LoginHint, }; if (!local) { vm.ExternalProviders = new[] { new ExternalProvider { AuthenticationScheme = context.IdP } }; } return vm; } var schemes = await _schemeProvider.GetAllSchemesAsync(); var providers = schemes .Where(x => x.DisplayName != null || (x.Name.Equals(AccountOptions.WindowsAuthenticationSchemeName, StringComparison.OrdinalIgnoreCase)) ) .Select(x => new ExternalProvider { DisplayName = x.DisplayName, AuthenticationScheme = x.Name }).ToList(); var allowLocal = true; if (context?.ClientId != null) { var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId); if (client != null) { allowLocal = client.EnableLocalLogin; if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any()) { providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList(); } } } return new LoginViewModel { AllowRememberLogin = AccountOptions.AllowRememberLogin, EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin, ReturnUrl = returnUrl, Username = context?.LoginHint, ExternalProviders = providers.ToArray() }; } private async Task<LoginViewModel> BuildLoginViewModelAsync(LoginInputModel model) { var vm = await BuildLoginViewModelAsync(model.ReturnUrl); vm.Username = model.Username; vm.RememberLogin = model.RememberLogin; return vm; } private async Task<LogoutViewModel> BuildLogoutViewModelAsync(string logoutId) { var vm = new LogoutViewModel { LogoutId = logoutId, ShowLogoutPrompt = AccountOptions.ShowLogoutPrompt }; if (User?.Identity.IsAuthenticated != true) { // if the user is not authenticated, then just show logged out page vm.ShowLogoutPrompt = false; return vm; } var context = await _interaction.GetLogoutContextAsync(logoutId); if (context?.ShowSignoutPrompt == false) { // it's safe to automatically sign-out vm.ShowLogoutPrompt = false; return vm; } // show the logout prompt. this prevents attacks where the user // is automatically signed out by another malicious web page. return vm; } private async Task<LoggedOutViewModel> BuildLoggedOutViewModelAsync(string logoutId) { // get context information (client name, post logout redirect URI and iframe for federated signout) var logout = await _interaction.GetLogoutContextAsync(logoutId); var vm = new LoggedOutViewModel { AutomaticRedirectAfterSignOut = AccountOptions.AutomaticRedirectAfterSignOut, PostLogoutRedirectUri = logout?.PostLogoutRedirectUri, ClientName = string.IsNullOrEmpty(logout?.ClientName) ? logout?.ClientId : logout?.ClientName, SignOutIframeUrl = logout?.SignOutIFrameUrl, LogoutId = logoutId }; if (User?.Identity.IsAuthenticated == true) { var idp = User.FindFirst(JwtClaimTypes.IdentityProvider)?.Value; if (idp != null && idp != IdentityServer4.IdentityServerConstants.LocalIdentityProvider) { var providerSupportsSignout = await HttpContext.GetSchemeSupportsSignOutAsync(idp); if (providerSupportsSignout) { if (vm.LogoutId == null) { // if there's no current logout context, we need to create one // this captures necessary info from the current logged in user // before we signout and redirect away to the external IdP for signout vm.LogoutId = await _interaction.CreateLogoutContextAsync(); } vm.ExternalAuthenticationScheme = idp; } } } return vm; } } }
#region License /* The MIT License * * Copyright (c) 2011 Red Badger Consulting * * 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 //------------------------------------------------------------------------------------------------- // <auto-generated> // Marked as auto-generated so StyleCop will ignore BDD style tests // </auto-generated> //------------------------------------------------------------------------------------------------- #pragma warning disable 169 // ReSharper disable InconsistentNaming // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local namespace RedBadger.Xpf.Specs.ReactiveObjectSpecs.BindingSpecs.ObjectSpecs { using System; using Machine.Specifications; using Moq; using RedBadger.Xpf.Controls; using RedBadger.Xpf.Data; using RedBadger.Xpf.Graphics; using RedBadger.Xpf.Media; using It = Machine.Specifications.It; public class TestBindingObject { public Brush Brush { get; set; } public string BrushAsString { get; set; } public SolidColorBrush SolidColorBrush { get; set; } } public class TestBindingReactiveObject : ReactiveObject { public static readonly ReactiveProperty<SolidColorBrush> SolidColorBrushProperty = ReactiveProperty<SolidColorBrush>.Register("SolidColorBrush", typeof(TestBindingReactiveObject)); public SolidColorBrush SolidColorBrush { get { return this.GetValue(SolidColorBrushProperty); } set { this.SetValue(SolidColorBrushProperty, value); } } } [Subject(typeof(ReactiveObject), "One Way")] public class when_there_is_a_one_way_binding_to_the_data_context_which_is_an_object { private const double ExpectedWidth = 10d; private static Border target; private Establish context = () => target = new Border { DataContext = ExpectedWidth }; private Because of = () => { IObservable<double> fromSource = BindingFactory.CreateOneWay<double>(); target.Bind(UIElement.WidthProperty, fromSource); target.Measure(Size.Empty); }; private It should_update_the_target = () => target.Width.ShouldEqual(ExpectedWidth); } [Subject(typeof(ReactiveObject), "One Way")] public class when_there_is_a_one_way_binding_to_the_data_context_which_is_an_object_and_type_conversion_is_required { private const string ExpectedWidth = "10.0"; private static Border target; private Establish context = () => target = new Border { DataContext = ExpectedWidth }; private Because of = () => { IObservable<double> fromSource = BindingFactory.CreateOneWay<double>(); target.Bind(UIElement.WidthProperty, fromSource); target.Measure(Size.Empty); }; private It should_update_the_target = () => target.Width.ShouldEqual(Convert.ToDouble(ExpectedWidth)); } [Subject(typeof(ReactiveObject), "One Way")] public class when_there_is_a_one_way_binding_to_a_specified_source_which_is_an_object { private const double ExpectedWidth = 10d; private static Border target; private Establish context = () => target = new Border(); private Because of = () => { IObservable<double> fromSource = BindingFactory.CreateOneWay(ExpectedWidth); target.Bind(UIElement.WidthProperty, fromSource); }; private It should_update_the_target = () => target.Width.ShouldEqual(ExpectedWidth); } [Subject(typeof(ReactiveObject), "One Way")] public class when_there_is_a_one_way_binding_to_a_specified_source_which_is_an_object_and_type_conversion_is_required { private const string ExpectedWidth = "10.0"; private static Border target; private Establish context = () => target = new Border(); private Because of = () => { IObservable<double> fromSource = BindingFactory.CreateOneWay<string, double>(ExpectedWidth); target.Bind(UIElement.WidthProperty, fromSource); }; private It should_update_the_target = () => target.Width.ShouldEqual(Convert.ToDouble(ExpectedWidth)); } [Subject(typeof(ReactiveObject), "One Way")] public class when_there_is_a_one_way_binding_to_a_property_on_the_data_context { private static TestBindingObject bindingObject; private static Border target; private Establish context = () => { bindingObject = new TestBindingObject { Brush = new SolidColorBrush(Colors.Blue) }; target = new Border { DataContext = bindingObject }; }; private Because of = () => { IObservable<Brush> fromSource = BindingFactory.CreateOneWay<TestBindingObject, Brush>(o => o.Brush); target.Bind(Border.BorderBrushProperty, fromSource); target.Measure(Size.Empty); }; private It should_update_the_target = () => target.BorderBrush.ShouldEqual(bindingObject.Brush); } [Subject(typeof(ReactiveObject), "One Way")] public class when_there_is_a_one_way_binding_to_a_property_on_the_data_context_and_type_conversion_is_required { private static TestBindingObject bindingObject; private static TextBlock target; private Establish context = () => { bindingObject = new TestBindingObject { Brush = new SolidColorBrush(Colors.Blue) }; target = new TextBlock(new Mock<ISpriteFont>().Object) { DataContext = bindingObject }; }; private Because of = () => { IObservable<string> fromSource = BindingFactory.CreateOneWay<TestBindingObject, Brush, string>(o => o.Brush); target.Bind(TextBlock.TextProperty, fromSource); target.Measure(Size.Empty); }; private It should_update_the_target = () => target.Text.ShouldEqual(bindingObject.Brush.ToString()); } [Subject(typeof(ReactiveObject), "One Way")] public class when_there_is_a_one_way_binding_to_a_property_on_a_specified_source { private static TestBindingObject bindingObject; private static Border target; private Establish context = () => { bindingObject = new TestBindingObject { Brush = new SolidColorBrush(Colors.Blue) }; target = new Border(); }; private Because of = () => { IObservable<Brush> fromSource = BindingFactory.CreateOneWay(bindingObject, o => o.Brush); target.Bind(Border.BorderBrushProperty, fromSource); }; private It should_update_the_target = () => target.BorderBrush.ShouldEqual(bindingObject.Brush); } [Subject(typeof(ReactiveObject), "One Way")] public class when_there_is_a_one_way_binding_to_a_property_on_a_specified_source_and_type_conversion_is_required { private static TestBindingObject bindingObject; private static TextBlock target; private Establish context = () => { bindingObject = new TestBindingObject { Brush = new SolidColorBrush(Colors.Blue) }; target = new TextBlock(new Mock<ISpriteFont>().Object); }; private Because of = () => { IObservable<string> fromSource = BindingFactory.CreateOneWay<TestBindingObject, Brush, string>(bindingObject, o => o.Brush); target.Bind(TextBlock.TextProperty, fromSource); }; private It should_update_the_target = () => target.Text.ShouldEqual(bindingObject.Brush.ToString()); } [Subject(typeof(ReactiveObject), "One Way")] public class when_there_is_a_one_way_binding_and_the_source_type_is_more_derived { private static readonly SolidColorBrush expectedBrush = new SolidColorBrush(Colors.Brown); private static Border target; private Establish context = () => target = new Border(); private Because of = () => { IObservable<Brush> fromSource = BindingFactory.CreateOneWay(expectedBrush); target.Bind(Border.BorderBrushProperty, fromSource); }; private It should_update_the_target = () => target.BorderBrush.ShouldEqual(expectedBrush); } [Subject(typeof(ReactiveObject), "One Way To Source")] public class when_there_is_a_one_way_to_source_binding_to_a_property_on_the_data_context { private static readonly Brush expectedBrush = new SolidColorBrush(Colors.Brown); private static readonly Brush expectedInitialBrush = new SolidColorBrush(Colors.Blue); private static Brush initialBrush; private static TestBindingObject source; private static Border target; private Establish context = () => { source = new TestBindingObject(); target = new Border { DataContext = source, BorderBrush = expectedInitialBrush }; IObserver<Brush> toSource = BindingFactory.CreateOneWayToSource<TestBindingObject, Brush>(o => o.Brush); target.Bind(Border.BorderBrushProperty, toSource); target.Measure(Size.Empty); }; private Because of = () => { initialBrush = source.Brush; target.BorderBrush = expectedBrush; }; private It should_update_the_source_with_the_initial_value = () => initialBrush.ShouldEqual(expectedInitialBrush); private It should_update_the_source_with_the_updated_value = () => source.Brush.ShouldEqual(expectedBrush); } [Subject(typeof(ReactiveObject), "One Way To Source")] public class when_there_is_a_one_way_to_source_binding_to_a_property_on_the_data_context_and_type_conversion_is_required { private static readonly Brush expectedBrush = new SolidColorBrush(Colors.Brown); private static TestBindingObject source; private static Border target; private Establish context = () => { source = new TestBindingObject(); target = new Border { DataContext = source }; IObserver<Brush> toSource = BindingFactory.CreateOneWayToSource<TestBindingObject, string, Brush>(o => o.BrushAsString); target.Bind(Border.BorderBrushProperty, toSource); target.Measure(Size.Empty); }; private Because of = () => target.BorderBrush = expectedBrush; private It should_update_the_source = () => source.BrushAsString.ShouldEqual(expectedBrush.ToString()); } [Subject(typeof(ReactiveObject), "One Way To Source")] public class when_a_one_way_to_source_binding_to_a_property_on_the_data_context_is_cleared { private static readonly Brush expectedBrush = new SolidColorBrush(Colors.Brown); private static TestBindingObject source; private static Border target; private Establish context = () => { source = new TestBindingObject(); target = new Border { DataContext = source }; IObserver<Brush> toSource = BindingFactory.CreateOneWayToSource<TestBindingObject, Brush>(o => o.Brush); target.Bind(Border.BorderBrushProperty, toSource); target.Measure(Size.Empty); }; private Because of = () => { target.BorderBrush = expectedBrush; target.ClearBinding(Border.BorderBrushProperty); target.BorderBrush = new SolidColorBrush(Colors.Yellow); }; private It should_not_update_the_source = () => source.Brush.ShouldEqual(expectedBrush); } [Subject(typeof(ReactiveObject), "One Way To Source")] public class when_there_is_a_one_way_to_source_binding_to_a_property_on_a_specified_source { private static readonly Brush expectedBrush = new SolidColorBrush(Colors.Brown); private static TestBindingObject source; private static Border target; private Establish context = () => { source = new TestBindingObject(); target = new Border(); IObserver<Brush> toSource = BindingFactory.CreateOneWayToSource(source, o => o.Brush); target.Bind(Border.BorderBrushProperty, toSource); }; private Because of = () => target.BorderBrush = expectedBrush; private It should_update_the_source = () => source.Brush.ShouldEqual(expectedBrush); } [Subject(typeof(ReactiveObject), "One Way To Source")] public class when_there_is_a_one_way_to_source_binding_to_a_property_on_a_specified_source_and_type_conversion_is_required { private static readonly Brush expectedBrush = new SolidColorBrush(Colors.Brown); private static TestBindingObject source; private static Border target; private Establish context = () => { source = new TestBindingObject(); target = new Border(); IObserver<Brush> toSource = BindingFactory.CreateOneWayToSource<TestBindingObject, string, Brush>( source, o => o.BrushAsString); target.Bind(Border.BorderBrushProperty, toSource); }; private Because of = () => target.BorderBrush = expectedBrush; private It should_update_the_source = () => source.BrushAsString.ShouldEqual(expectedBrush.ToString()); } [Subject(typeof(ReactiveObject), "One Way To Source")] public class when_a_one_way_to_source_binding_to_a_property_on_a_specified_source_is_cleared { private static readonly Brush expectedBrush = new SolidColorBrush(Colors.Brown); private static TestBindingObject source; private static Border target; private Establish context = () => { source = new TestBindingObject(); target = new Border(); IObserver<Brush> toSource = BindingFactory.CreateOneWayToSource(source, o => o.Brush); target.Bind(Border.BorderBrushProperty, toSource); }; private Because of = () => { target.BorderBrush = expectedBrush; target.ClearBinding(Border.BorderBrushProperty); target.BorderBrush = new SolidColorBrush(Colors.Yellow); }; private It should_not_update_the_source = () => source.Brush.ShouldEqual(expectedBrush); } [Subject(typeof(ReactiveObject), "One Way To Source")] public class when_there_is_a_one_way_to_source_binding_and_the_type_of_the_target_property_is_more_derived { private static readonly SolidColorBrush expectedBrush = new SolidColorBrush(Colors.Brown); private static TestBindingObject source; private static TestBindingReactiveObject target; private Establish context = () => { source = new TestBindingObject(); target = new TestBindingReactiveObject(); IObserver<Brush> toSource = BindingFactory.CreateOneWayToSource(source, o => o.Brush); target.Bind(TestBindingReactiveObject.SolidColorBrushProperty, toSource); }; private Because of = () => target.SolidColorBrush = expectedBrush; private It should_update_the_source = () => source.Brush.ShouldEqual(expectedBrush); } [Subject(typeof(ReactiveObject), "One Way To Source")] public class when_there_is_a_one_way_to_source_binding_and_the_type_of_the_source_property_is_more_derived { private static readonly SolidColorBrush expectedBrush = new SolidColorBrush(Colors.Brown); private static TestBindingObject source; private static Border target; private Establish context = () => { source = new TestBindingObject(); target = new Border(); IObserver<Brush> toSource = BindingFactory.CreateOneWayToSource<TestBindingObject, Brush>( source, o => o.SolidColorBrush); target.Bind(Border.BorderBrushProperty, toSource); }; private Because of = () => target.BorderBrush = expectedBrush; private It should_update_the_source = () => source.SolidColorBrush.ShouldEqual(expectedBrush); } [Subject(typeof(ReactiveObject))] public class when_the_data_context_is_set_after_the_binding_has_been_created { private const string ExpectedValue = "Value"; private static TextBlock target; private Establish context = () => { target = new TextBlock(new Mock<ISpriteFont>().Object); IObservable<string> fromSource = BindingFactory.CreateOneWay<string>(); target.Bind(TextBlock.TextProperty, fromSource); target.Measure(Size.Empty); }; private Because of = () => { target.DataContext = ExpectedValue; target.Measure(Size.Empty); }; private It should_bind_to_the_data_context = () => target.Text.ShouldEqual(ExpectedValue); } [Subject(typeof(ReactiveObject))] public class when_binding_to_the_data_context_and_the_data_context_is_changed { private const string NewDataContext = "New Data Context"; private static TextBlock target; private Establish context = () => { target = new TextBlock(new Mock<ISpriteFont>().Object) { DataContext = "Old Data Context" }; IObservable<string> fromSource = BindingFactory.CreateOneWay<string>(); target.Bind(TextBlock.TextProperty, fromSource); target.Measure(Size.Empty); }; private Because of = () => { target.DataContext = NewDataContext; target.Measure(Size.Empty); }; private It should_use_the_new_data_context = () => target.Text.ShouldEqual(NewDataContext); } [Subject(typeof(ReactiveObject))] public class when_binding_to_the_data_context_and_the_data_context_is_changed_to_null { private const string NewDataContext = null; private static TextBlock target; private Establish context = () => { target = new TextBlock(new Mock<ISpriteFont>().Object) { DataContext = "Old Data Context" }; IObservable<string> fromSource = BindingFactory.CreateOneWay<string>(); target.Bind(TextBlock.TextProperty, fromSource); target.Measure(Size.Empty); }; private Because of = () => { target.DataContext = NewDataContext; target.Measure(Size.Empty); }; private It should_use_the_new_data_context = () => target.Text.ShouldEqual(NewDataContext); } }
/* ==================================================================== 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. ==================================================================== */ /* ==================================================================== This product Contains an ASLv2 licensed version of the OOXML signer package from the eID Applet project http://code.google.com/p/eid-applet/source/browse/tRunk/README.txt Copyright (C) 2008-2014 FedICT. ================================================================= */ namespace NPOI.POIFS.Crypt.Dsig.Services { using System; using System.Collections.Generic; /** * JSR105 implementation of the RelationshipTransform transformation. * * <p> * Specs: http://openiso.org/Ecma/376/Part2/12.2.4#26 * </p> */ public class RelationshipTransformService : TransformService { public static String TRANSFORM_URI = "http://schemas.Openxmlformats.org/package/2006/RelationshipTransform"; private List<String> sourceIds; //private static POILogger LOG = POILogFactory.GetLogger(typeof(RelationshipTransformService)); /** * Relationship Transform parameter specification class. */ public class RelationshipTransformParameterSpec : TransformParameterSpec { List<String> sourceIds = new List<String>(); public void AddRelationshipReference(String relationshipId) { sourceIds.Add(relationshipId); } public bool HasSourceIds() { return !sourceIds.IsEmpty(); } } public RelationshipTransformService() : base() { //LOG.Log(POILogger.DEBUG, "constructor"); this.sourceIds = new List<String>(); } /** * Register the provider for this TransformService * * @see javax.xml.Crypto.dsig.TransformService */ public static void registerDsigProvider() { // the xml signature classes will try to find a special TransformerService, // which is ofcourse unknown to JCE before ... String dsigProvider = "POIXmlDsigProvider"; if (Security.GetProperty(dsigProvider) == null) { //Provider p = new Provider(dsigProvider, 1.0, dsigProvider){ // static long serialVersionUID = 1L; //}; //p.Put("TransformService." + TRANSFORM_URI, RelationshipTransformService.class.Name); //p.Put("TransformService." + TRANSFORM_URI + " MechanismType", "DOM"); //Security.AddProvider(p); throw new NotImplementedException(); } } public void Init(TransformParameterSpec params1) { //LOG.Log(POILogger.DEBUG, "Init(params)"); if (!(params1 is RelationshipTransformParameterSpec)) { throw new InvalidAlgorithmParameterException(); } RelationshipTransformParameterSpec relParams = (RelationshipTransformParameterSpec)params1; foreach (String sourceId in relParams.sourceIds) { this.sourceIds.Add(sourceId); } } public void Init(XMLStructure parent, XMLCryptoContext context) { LOG.Log(POILogger.DEBUG, "Init(parent,context)"); LOG.Log(POILogger.DEBUG, "parent java type: " + parent.Class.Name); DOMStructure domParent = (DOMStructure)parent; Node parentNode = domParent.Node; try { TransformDocument transDoc = TransformDocument.Factory.Parse(parentNode); XmlObject[] xoList = transDoc.Transform.SelectChildren(RelationshipReferenceDocument.type.DocumentElementName); if (xoList.Length == 0) { //LOG.Log(POILogger.WARN, "no RelationshipReference/@SourceId parameters present"); } foreach (XmlObject xo in xoList) { String sourceId = ((CTRelationshipReference)xo).SourceId; LOG.Log(POILogger.DEBUG, "sourceId: ", sourceId); this.sourceIds.Add(sourceId); } } catch (XmlException e) { throw new InvalidAlgorithmParameterException(e); } } public void marshalParams(XMLStructure parent, XMLCryptoContext context) { //LOG.Log(POILogger.DEBUG, "marshallParams(parent,context)"); DOMStructure domParent = (DOMStructure)parent; Element parentNode = (Element)domParent.Node; // parentNode.AttributeNS=(/*setter*/XML_NS, "xmlns:mdssi", XML_DIGSIG_NS); Document doc = parentNode.OwnerDocument; foreach (String sourceId in sourceIds) { RelationshipReferenceDocument relRef = RelationshipReferenceDocument.Factory.NewInstance(); relRef.AddNewRelationshipReference().SourceId = (/*setter*/sourceId); Node n = relRef.RelationshipReference.DomNode; n = doc.ImportNode(n, true); parentNode.AppendChild(n); } } public AlgorithmParameterSpec GetParameterSpec() { LOG.Log(POILogger.DEBUG, "getParameterSpec"); return null; } public Data transform(Data data, XMLCryptoContext context) { LOG.Log(POILogger.DEBUG, "transform(data,context)"); LOG.Log(POILogger.DEBUG, "data java type: " + data.Class.Name); OctetStreamData octetStreamData = (OctetStreamData)data; LOG.Log(POILogger.DEBUG, "URI: " + octetStreamData.URI); InputStream octetStream = octetStreamData.OctetStream; RelationshipsDocument relDoc; try { relDoc = RelationshipsDocument.Factory.Parse(octetStream); } catch (Exception e) { throw new TransformException(e.Message, e); } LOG.Log(POILogger.DEBUG, "relationships document", relDoc); CTRelationships rels = relDoc.Relationships; List<CTRelationship> relList = rels.RelationshipList; Iterator<CTRelationship> relIter = rels.RelationshipList.Iterator(); while (relIter.HasNext()) { CTRelationship rel = relIter.Next(); /* * See: ISO/IEC 29500-2:2008(E) - 13.2.4.24 Relationships Transform * Algorithm. */ if (!this.sourceIds.Contains(rel.Id)) { LOG.Log(POILogger.DEBUG, "removing element: " + rel.Id); relIter.Remove(); } else { if (!rel.IsSetTargetMode()) { rel.TargetMode = (/*setter*/STTargetMode.INTERNAL); } } } // TODO: remove non element nodes ??? LOG.Log(POILogger.DEBUG, "# Relationship elements", relList.Size()); //XmlSort.Sort(rels, new Comparator<XmlCursor>(){ // public int Compare(XmlCursor c1, XmlCursor c2) { // String id1 = ((CTRelationship)c1.Object).Id; // String id2 = ((CTRelationship)c2.Object).Id; // return id1.CompareTo(id2); // } //}); try { MemoryStream bos = new MemoryStream(); XmlOptions xo = new XmlOptions(); xo.SaveNoXmlDecl; relDoc.Save(bos, xo); return new OctetStreamData(new MemoryStream(bos.ToByteArray())); } catch (IOException e) { throw new TransformException(e.Message, e); } } public Data transform(Data data, XMLCryptoContext context, OutputStream os) { //LOG.Log(POILogger.DEBUG, "transform(data,context,os)"); return null; } public bool IsFeatureSupported(String feature) { //LOG.Log(POILogger.DEBUG, "isFeatureSupported(feature)"); return false; } } }
// // report.cs: report errors and warnings. // // Author: Miguel de Icaza (miguel@ximian.com) // Marek Safar (marek.safar@seznam.cz) // // Copyright 2001 Ximian, Inc. (http://www.ximian.com) // using System; using System.IO; using System.Text; using System.Collections.Generic; using System.Diagnostics; namespace Mono.CSharp { // // Errors and warnings manager // public class Report { /// <summary> /// Whether warnings should be considered errors /// </summary> public bool WarningsAreErrors; List<int> warnings_as_error; List<int> warnings_only; public static int DebugFlags = 0; public const int RuntimeErrorId = 10000; // // Keeps track of the warnings that we are ignoring // HashSet<int> warning_ignore_table; Dictionary<int, WarningRegions> warning_regions_table; int warning_level; ReportPrinter printer; int reporting_disabled; /// <summary> /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported. /// </summary> List<string> extra_information = new List<string> (); // // IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE // public static readonly int[] AllWarnings = new int[] { 28, 67, 78, 105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197, 219, 251, 252, 253, 278, 282, 402, 414, 419, 420, 429, 436, 440, 458, 464, 465, 467, 469, 472, 612, 618, 626, 628, 642, 649, 652, 658, 659, 660, 661, 665, 672, 675, 693, 728, 809, 824, 1030, 1058, 1066, 1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592, 1607, 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692, 1695, 1696, 1699, 1700, 1701, 1702, 1709, 1717, 1718, 1720, 1901, 1981, 2002, 2023, 2029, 3000, 3001, 3002, 3003, 3005, 3006, 3007, 3008, 3009, 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019, 3021, 3022, 3023, 3024, 3026, 3027 }; static HashSet<int> AllWarningsHashSet; public Report (ReportPrinter printer) { if (printer == null) throw new ArgumentNullException ("printer"); this.printer = printer; warning_level = 4; } public void DisableReporting () { ++reporting_disabled; } public void EnableReporting () { --reporting_disabled; } public void FeatureIsNotAvailable (CompilerContext compiler, Location loc, string feature) { string version; switch (compiler.Settings.Version) { case LanguageVersion.ISO_1: version = "1.0"; break; case LanguageVersion.ISO_2: version = "2.0"; break; case LanguageVersion.V_3: version = "3.0"; break; default: throw new InternalErrorException ("Invalid feature version", compiler.Settings.Version); } Error (1644, loc, "Feature `{0}' cannot be used because it is not part of the C# {1} language specification", feature, version); } public void FeatureIsNotSupported (Location loc, string feature) { Error (1644, loc, "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead", feature); } bool IsWarningEnabled (int code, int level, Location loc) { if (WarningLevel < level) return false; if (IsWarningDisabledGlobally (code)) return false; if (warning_regions_table == null || loc.IsNull) return true; WarningRegions regions; if (!warning_regions_table.TryGetValue (loc.File, out regions)) return true; return regions.IsWarningEnabled (code, loc.Row); } public bool IsWarningDisabledGlobally (int code) { return warning_ignore_table != null && warning_ignore_table.Contains (code); } bool IsWarningAsError (int code) { bool is_error = WarningsAreErrors; // Check specific list if (warnings_as_error != null) is_error |= warnings_as_error.Contains (code); // Ignore excluded warnings if (warnings_only != null && warnings_only.Contains (code)) is_error = false; return is_error; } public void RuntimeMissingSupport (Location loc, string feature) { Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature); } /// <summary> /// In most error cases is very useful to have information about symbol that caused the error. /// Call this method before you call Report.Error when it makes sense. /// </summary> public void SymbolRelatedToPreviousError (Location loc, string symbol) { SymbolRelatedToPreviousError (loc.ToString ()); } public void SymbolRelatedToPreviousError (MemberSpec ms) { if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport) return; var mc = ms.MemberDefinition as MemberCore; while (ms is ElementTypeSpec) { ms = ((ElementTypeSpec) ms).Element; mc = ms.MemberDefinition as MemberCore; } if (mc != null) { SymbolRelatedToPreviousError (mc); } else { if (ms.DeclaringType != null) ms = ms.DeclaringType; var imported_type = ms.MemberDefinition as ImportedTypeDefinition; if (imported_type != null) { var iad = imported_type.DeclaringAssembly as ImportedAssemblyDefinition; SymbolRelatedToPreviousError (iad.Location); } } } public void SymbolRelatedToPreviousError (MemberCore mc) { SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ()); } public void SymbolRelatedToPreviousError (string loc) { string msg = String.Format ("{0} (Location of the symbol related to previous ", loc); if (extra_information.Contains (msg)) return; extra_information.Add (msg); } public void AddWarningAsError (string warningId) { int id; try { id = int.Parse (warningId); } catch { CheckWarningCode (warningId, Location.Null); return; } if (!CheckWarningCode (id, Location.Null)) return; if (warnings_as_error == null) warnings_as_error = new List<int> (); warnings_as_error.Add (id); } public void RemoveWarningAsError (string warningId) { int id; try { id = int.Parse (warningId); } catch { CheckWarningCode (warningId, Location.Null); return; } if (!CheckWarningCode (id, Location.Null)) return; if (warnings_only == null) warnings_only = new List<int> (); warnings_only.Add (id); } public bool CheckWarningCode (string code, Location loc) { Warning (1691, 1, loc, "`{0}' is not a valid warning number", code); return false; } public bool CheckWarningCode (int code, Location loc) { if (AllWarningsHashSet == null) AllWarningsHashSet = new HashSet<int> (AllWarnings); if (AllWarningsHashSet.Contains (code)) return true; return CheckWarningCode (code.ToString (), loc); } public void ExtraInformation (Location loc, string msg) { extra_information.Add (String.Format ("{0} {1}", loc, msg)); } public WarningRegions RegisterWarningRegion (Location location) { WarningRegions regions; if (warning_regions_table == null) { regions = null; warning_regions_table = new Dictionary<int, WarningRegions> (); } else { warning_regions_table.TryGetValue (location.File, out regions); } if (regions == null) { regions = new WarningRegions (); warning_regions_table.Add (location.File, regions); } return regions; } public void Warning (int code, int level, Location loc, string message) { if (reporting_disabled > 0) return; if (!IsWarningEnabled (code, level, loc)) return; AbstractMessage msg; if (IsWarningAsError (code)) { message = "Warning as Error: " + message; msg = new ErrorMessage (code, loc, message, extra_information); } else { msg = new WarningMessage (code, loc, message, extra_information); } extra_information.Clear (); printer.Print (msg); } public void Warning (int code, int level, Location loc, string format, string arg) { Warning (code, level, loc, String.Format (format, arg)); } public void Warning (int code, int level, Location loc, string format, string arg1, string arg2) { Warning (code, level, loc, String.Format (format, arg1, arg2)); } public void Warning (int code, int level, Location loc, string format, params object[] args) { Warning (code, level, loc, String.Format (format, args)); } public void Warning (int code, int level, string message) { Warning (code, level, Location.Null, message); } public void Warning (int code, int level, string format, string arg) { Warning (code, level, Location.Null, format, arg); } public void Warning (int code, int level, string format, string arg1, string arg2) { Warning (code, level, Location.Null, format, arg1, arg2); } public void Warning (int code, int level, string format, params string[] args) { Warning (code, level, Location.Null, String.Format (format, args)); } // // Warnings encountered so far // public int Warnings { get { return printer.WarningsCount; } } public void Error (int code, Location loc, string error) { if (reporting_disabled > 0) return; ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information); extra_information.Clear (); printer.Print (msg); } public void Error (int code, Location loc, string format, string arg) { Error (code, loc, String.Format (format, arg)); } public void Error (int code, Location loc, string format, string arg1, string arg2) { Error (code, loc, String.Format (format, arg1, arg2)); } public void Error (int code, Location loc, string format, params string[] args) { Error (code, loc, String.Format (format, args)); } public void Error (int code, string error) { Error (code, Location.Null, error); } public void Error (int code, string format, string arg) { Error (code, Location.Null, format, arg); } public void Error (int code, string format, string arg1, string arg2) { Error (code, Location.Null, format, arg1, arg2); } public void Error (int code, string format, params string[] args) { Error (code, Location.Null, String.Format (format, args)); } // // Errors encountered so far // public int Errors { get { return printer.ErrorsCount; } } public bool IsDisabled { get { return reporting_disabled > 0; } } public ReportPrinter Printer { get { return printer; } } public void SetIgnoreWarning (int code) { if (warning_ignore_table == null) warning_ignore_table = new HashSet<int> (); warning_ignore_table.Add (code); } public ReportPrinter SetPrinter (ReportPrinter printer) { ReportPrinter old = this.printer; this.printer = printer; return old; } public int WarningLevel { get { return warning_level; } set { warning_level = value; } } [Conditional ("MCS_DEBUG")] static public void Debug (string message, params object[] args) { Debug (4, message, args); } [Conditional ("MCS_DEBUG")] static public void Debug (int category, string message, params object[] args) { if ((category & DebugFlags) == 0) return; StringBuilder sb = new StringBuilder (message); if ((args != null) && (args.Length > 0)) { sb.Append (": "); bool first = true; foreach (object arg in args) { if (first) first = false; else sb.Append (", "); if (arg == null) sb.Append ("null"); // else if (arg is ICollection) // sb.Append (PrintCollection ((ICollection) arg)); else sb.Append (arg); } } Console.WriteLine (sb.ToString ()); } /* static public string PrintCollection (ICollection collection) { StringBuilder sb = new StringBuilder (); sb.Append (collection.GetType ()); sb.Append ("("); bool first = true; foreach (object o in collection) { if (first) first = false; else sb.Append (", "); sb.Append (o); } sb.Append (")"); return sb.ToString (); } */ } public abstract class AbstractMessage { readonly string[] extra_info; protected readonly int code; protected readonly Location location; readonly string message; protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo) { this.code = code; if (code < 0) this.code = 8000 - code; this.location = loc; this.message = msg; if (extraInfo.Count != 0) { this.extra_info = extraInfo.ToArray (); } } protected AbstractMessage (AbstractMessage aMsg) { this.code = aMsg.code; this.location = aMsg.location; this.message = aMsg.message; this.extra_info = aMsg.extra_info; } public int Code { get { return code; } } public override bool Equals (object obj) { AbstractMessage msg = obj as AbstractMessage; if (msg == null) return false; return code == msg.code && location.Equals (msg.location) && message == msg.message; } public override int GetHashCode () { return code.GetHashCode (); } public abstract bool IsWarning { get; } public Location Location { get { return location; } } public abstract string MessageType { get; } public string[] RelatedSymbols { get { return extra_info; } } public string Text { get { return message; } } } sealed class WarningMessage : AbstractMessage { public WarningMessage (int code, Location loc, string message, List<string> extra_info) : base (code, loc, message, extra_info) { } public override bool IsWarning { get { return true; } } public override string MessageType { get { return "warning"; } } } sealed class ErrorMessage : AbstractMessage { public ErrorMessage (int code, Location loc, string message, List<string> extraInfo) : base (code, loc, message, extraInfo) { } public ErrorMessage (AbstractMessage aMsg) : base (aMsg) { } public override bool IsWarning { get { return false; } } public override string MessageType { get { return "error"; } } } // // Generic base for any message writer // public abstract class ReportPrinter { #region Properties public int FatalCounter { get; set; } public int ErrorsCount { get; protected set; } public bool ShowFullPaths { get; set; } // // Whether to dump a stack trace on errors. // public bool Stacktrace { get; set; } public int WarningsCount { get; private set; } // // When (symbols related to previous ...) can be used // public virtual bool HasRelatedSymbolSupport { get { return true; } } #endregion protected virtual string FormatText (string txt) { return txt; } public virtual void Print (AbstractMessage msg) { if (msg.IsWarning) { ++WarningsCount; } else { ++ErrorsCount; if (ErrorsCount == FatalCounter) throw new Exception (msg.Text); } } protected void Print (AbstractMessage msg, TextWriter output) { StringBuilder txt = new StringBuilder (); if (!msg.Location.IsNull) { if (ShowFullPaths) txt.Append (msg.Location.ToStringFullName ()); else txt.Append (msg.Location.ToString ()); txt.Append (" "); } txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text); if (!msg.IsWarning) output.WriteLine (FormatText (txt.ToString ())); else output.WriteLine (txt.ToString ()); if (msg.RelatedSymbols != null) { foreach (string s in msg.RelatedSymbols) output.WriteLine (s + msg.MessageType + ")"); } } public void Reset () { // HACK: Temporary hack for broken repl flow ErrorsCount = WarningsCount = 0; } } // // Default message recorder, it uses two types of message groups. // Common messages: messages reported in all sessions. // Merged messages: union of all messages in all sessions. // // Used by the Lambda expressions to compile the code with various // parameter values, or by attribute resolver // class SessionReportPrinter : ReportPrinter { List<AbstractMessage> session_messages; // // A collection of exactly same messages reported in all sessions // List<AbstractMessage> common_messages; // // A collection of unique messages reported in all sessions // List<AbstractMessage> merged_messages; public override void Print (AbstractMessage msg) { // // This line is useful when debugging recorded messages // // Console.WriteLine ("RECORDING: {0}", msg.ToString ()); if (session_messages == null) session_messages = new List<AbstractMessage> (); session_messages.Add (msg); base.Print (msg); } public void EndSession () { if (session_messages == null) return; // // Handles the first session // if (common_messages == null) { common_messages = new List<AbstractMessage> (session_messages); merged_messages = session_messages; session_messages = null; return; } // // Store common messages if any // for (int i = 0; i < common_messages.Count; ++i) { AbstractMessage cmsg = common_messages[i]; bool common_msg_found = false; foreach (AbstractMessage msg in session_messages) { if (cmsg.Equals (msg)) { common_msg_found = true; break; } } if (!common_msg_found) common_messages.RemoveAt (i); } // // Merge session and previous messages // for (int i = 0; i < session_messages.Count; ++i) { AbstractMessage msg = session_messages[i]; bool msg_found = false; for (int ii = 0; ii < merged_messages.Count; ++ii) { if (msg.Equals (merged_messages[ii])) { msg_found = true; break; } } if (!msg_found) merged_messages.Add (msg); } } public bool IsEmpty { get { return merged_messages == null && common_messages == null; } } // // Prints collected messages, common messages have a priority // public bool Merge (ReportPrinter dest) { var messages_to_print = merged_messages; if (common_messages != null && common_messages.Count > 0) { messages_to_print = common_messages; } if (messages_to_print == null) return false; bool error_msg = false; foreach (AbstractMessage msg in messages_to_print) { dest.Print (msg); error_msg |= !msg.IsWarning; } return error_msg; } } public class StreamReportPrinter : ReportPrinter { readonly TextWriter writer; public StreamReportPrinter (TextWriter writer) { this.writer = writer; } public override void Print (AbstractMessage msg) { Print (msg, writer); base.Print (msg); } } public class ConsoleReportPrinter : StreamReportPrinter { static readonly string prefix, postfix; static ConsoleReportPrinter () { string term = null; bool xterm_colors = false; switch (term){ case "xterm": case "rxvt": case "rxvt-unicode": break; case "xterm-color": xterm_colors = true; break; } if (!xterm_colors) return; if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2))) return; string config = null; if (config == null){ config = "errors=red"; //config = "brightwhite,red"; } if (config == "disable") return; if (!config.StartsWith ("errors=")) return; config = config.Substring (7); int p = config.IndexOf (","); if (p == -1) prefix = GetForeground (config); else prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p)); postfix = "\x001b[0m"; } public ConsoleReportPrinter () : base (Console.Error) { } public ConsoleReportPrinter (TextWriter writer) : base (writer) { } static int NameToCode (string s) { switch (s) { case "black": return 0; case "red": return 1; case "green": return 2; case "yellow": return 3; case "blue": return 4; case "magenta": return 5; case "cyan": return 6; case "grey": case "white": return 7; } return 7; } // // maps a color name to its xterm color code // static string GetForeground (string s) { string highcode; if (s.StartsWith ("bright")) { highcode = "1;"; s = s.Substring (6); } else highcode = ""; return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m"; } static string GetBackground (string s) { return "\x001b[" + (40 + NameToCode (s)).ToString () + "m"; } protected override string FormatText (string txt) { if (prefix != null) return prefix + txt + postfix; return txt; } static string FriendlyStackTrace (StackTrace t) { StringBuilder sb = new StringBuilder (); bool foundUserCode = false; for (int i = 0; i < t.FrameCount; i++) { StackFrame f = t.GetFrame (i); var mb = f.GetMethod (); if (!foundUserCode && mb.ReflectedType == typeof (Report)) continue; foundUserCode = true; sb.Append ("\tin "); if (f.GetFileLineNumber () > 0) sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ()); sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name); bool first = true; foreach (var pi in mb.GetParameters ()) { if (!first) sb.Append (", "); first = false; sb.Append (pi.ParameterType.FullName); } sb.Append (")\n"); } return sb.ToString (); } public override void Print (AbstractMessage msg) { base.Print (msg); if (Stacktrace) Console.WriteLine (FriendlyStackTrace (new StackTrace (true))); } public static string FriendlyStackTrace (Exception e) { return FriendlyStackTrace (new StackTrace (e, true)); } public static void StackTrace () { Console.WriteLine (FriendlyStackTrace (new StackTrace (true))); } } class TimeReporter { public enum TimerType { ParseTotal, AssemblyBuilderSetup, CreateTypeTotal, ReferencesLoading, ReferencesImporting, PredefinedTypesInit, ModuleDefinitionTotal, UsingVerification, EmitTotal, CloseTypes, Resouces, OutputSave, DebugSave, } readonly Stopwatch[] timers; Stopwatch total; public TimeReporter (bool enabled) { if (!enabled) return; timers = new Stopwatch[13]; } public void Start (TimerType type) { if (timers != null) { var sw = new Stopwatch (); timers[(int) type] = sw; sw.Start (); } } public void StartTotal () { total = new Stopwatch (); total.Start (); } public void Stop (TimerType type) { if (timers != null) { timers[(int) type].Stop (); } } public void StopTotal () { total.Stop (); } public void ShowStats () { if (timers == null) return; Dictionary<TimerType, string> timer_names = new Dictionary<TimerType,string> () { { TimerType.ParseTotal, "Parsing source files" }, { TimerType.AssemblyBuilderSetup, "Assembly builder setup" }, { TimerType.CreateTypeTotal, "Compiled types created" }, { TimerType.ReferencesLoading, "Referenced assemblies loading" }, { TimerType.ReferencesImporting, "Referenced assemblies importing" }, { TimerType.PredefinedTypesInit, "Predefined types initialization" }, { TimerType.ModuleDefinitionTotal, "Module definition" }, { TimerType.UsingVerification, "Usings verification" }, { TimerType.EmitTotal, "Resolving and emitting members blocks" }, { TimerType.CloseTypes, "Module types closed" }, { TimerType.Resouces, "Embedding resources" }, { TimerType.OutputSave, "Writing output file" }, { TimerType.DebugSave, "Writing debug symbols file" }, }; int counter = 0; double percentage = total.ElapsedMilliseconds / 100; long subtotal = total.ElapsedMilliseconds; foreach (var timer in timers) { string msg = timer_names[(TimerType) counter++]; var ms = timer == null ? 0 : timer.ElapsedMilliseconds; Console.WriteLine ("{0,4:0.0}% {1,5}ms {2}", ms / percentage, ms, msg); subtotal -= ms; } Console.WriteLine ("{0,4:0.0}% {1,5}ms Other tasks", subtotal / percentage, subtotal); Console.WriteLine (); Console.WriteLine ("Total elapsed time: {0}", total.Elapsed); } } public class InternalErrorException : Exception { public InternalErrorException (MemberCore mc, Exception e) : base (mc.Location + " " + mc.GetSignatureForError (), e) { } public InternalErrorException () : base ("Internal error") { } public InternalErrorException (string message) : base (message) { } public InternalErrorException (string message, params object[] args) : base (String.Format (message, args)) { } public InternalErrorException (Exception exception, string message, params object[] args) : base (String.Format (message, args), exception) { } public InternalErrorException (Exception e, Location loc) : base (loc.ToString (), e) { } } /// <summary> /// Handles #pragma warning /// </summary> public class WarningRegions { abstract class PragmaCmd { public int Line; protected PragmaCmd (int line) { Line = line; } public abstract bool IsEnabled (int code, bool previous); } class Disable : PragmaCmd { int code; public Disable (int line, int code) : base (line) { this.code = code; } public override bool IsEnabled (int code, bool previous) { return this.code == code ? false : previous; } } class DisableAll : PragmaCmd { public DisableAll (int line) : base (line) {} public override bool IsEnabled(int code, bool previous) { return false; } } class Enable : PragmaCmd { int code; public Enable (int line, int code) : base (line) { this.code = code; } public override bool IsEnabled(int code, bool previous) { return this.code == code ? true : previous; } } class EnableAll : PragmaCmd { public EnableAll (int line) : base (line) {} public override bool IsEnabled(int code, bool previous) { return true; } } List<PragmaCmd> regions = new List<PragmaCmd> (); public void WarningDisable (int line) { regions.Add (new DisableAll (line)); } public void WarningDisable (Location location, int code, Report Report) { if (Report.CheckWarningCode (code, location)) regions.Add (new Disable (location.Row, code)); } public void WarningEnable (int line) { regions.Add (new EnableAll (line)); } public void WarningEnable (Location location, int code, Report Report) { if (!Report.CheckWarningCode (code, location)) return; if (Report.IsWarningDisabledGlobally (code)) Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code); regions.Add (new Enable (location.Row, code)); } public bool IsWarningEnabled (int code, int src_line) { bool result = true; foreach (PragmaCmd pragma in regions) { if (src_line < pragma.Line) break; result = pragma.IsEnabled (code, result); } return result; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.Generic; using System.Management.Automation.Runspaces; using Dbg = System.Management.Automation; namespace System.Management.Automation { /// <summary> /// Holds the state of a Monad Shell session /// </summary> internal sealed partial class SessionStateInternal { #region aliases /// <summary> /// Add a new alias entry to this session state object... /// </summary> /// <param name="entry">The entry to add</param> /// <param name="scopeID"> /// A scope identifier that is either one of the "special" scopes like /// "global", "script", "local", or "private, or a numeric ID of a relative scope /// to the current scope. /// </param> internal void AddSessionStateEntry(SessionStateAliasEntry entry, string scopeID) { AliasInfo alias = new AliasInfo(entry.Name, entry.Definition, this.ExecutionContext, entry.Options) { Visibility = entry.Visibility, Module = entry.Module, Description = entry.Description }; // Create alias in the global scope... this.SetAliasItemAtScope(alias, scopeID, true, CommandOrigin.Internal); } /// <summary> /// Gets an IEnumerable for the alias table /// </summary> /// internal IDictionary<string, AliasInfo> GetAliasTable() { Dictionary<string, AliasInfo> result = new Dictionary<string, AliasInfo>(StringComparer.OrdinalIgnoreCase); SessionStateScopeEnumerator scopeEnumerator = new SessionStateScopeEnumerator(_currentScope); foreach (SessionStateScope scope in scopeEnumerator) { foreach (AliasInfo entry in scope.AliasTable) { if (!result.ContainsKey(entry.Name)) { // Make sure the alias isn't private or if it is that the current // scope is the same scope the alias was retrieved from. if ((entry.Options & ScopedItemOptions.Private) == 0 || scope == _currentScope) { result.Add(entry.Name, entry); } } } } return result; } // GetAliasTable /// <summary> /// Gets an IEnumerable for the alias table for a given scope /// </summary> /// /// <param name="scopeID"> /// A scope identifier that is either one of the "special" scopes like /// "global", "script", "local", or "private, or a numeric ID of a relative scope /// to the current scope. /// </param> /// /// <exception cref="ArgumentException"> /// If <paramref name="scopeID"/> is less than zero, or not /// a number and not "script", "global", "local", or "private" /// </exception> /// /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently /// active scopes. /// </exception> /// internal IDictionary<string, AliasInfo> GetAliasTableAtScope(string scopeID) { Dictionary<string, AliasInfo> result = new Dictionary<string, AliasInfo>(StringComparer.OrdinalIgnoreCase); SessionStateScope scope = GetScopeByID(scopeID); foreach (AliasInfo entry in scope.AliasTable) { // Make sure the alias isn't private or if it is that the current // scope is the same scope the alias was retrieved from. if ((entry.Options & ScopedItemOptions.Private) == 0 || scope == _currentScope) { result.Add(entry.Name, entry); } } return result; } // GetAliasTableAtScope /// <summary> /// List of aliases to export from this session state object... /// </summary> internal List<AliasInfo> ExportedAliases { get; } = new List<AliasInfo>(); /// <summary> /// Gets the value of the specified alias from the alias table. /// </summary> /// /// <param name="aliasName"> /// The name of the alias value to retrieve. /// </param> /// /// <param name="origin"> /// The origin of the command calling this API. /// </param> /// <returns> /// The AliasInfo representing the alias. /// </returns> /// internal AliasInfo GetAlias(string aliasName, CommandOrigin origin) { AliasInfo result = null; if (String.IsNullOrEmpty(aliasName)) { return null; } // Use the scope enumerator to find the alias using the // appropriate scoping rules SessionStateScopeEnumerator scopeEnumerator = new SessionStateScopeEnumerator(_currentScope); foreach (SessionStateScope scope in scopeEnumerator) { result = scope.GetAlias(aliasName); if (result != null) { // Now check the visibility of the variable... SessionState.ThrowIfNotVisible(origin, result); // Make sure the alias isn't private or if it is that the current // scope is the same scope the alias was retrieved from. if ((result.Options & ScopedItemOptions.Private) != 0 && scope != _currentScope) { result = null; } else { break; } } } return result; } // GetAlias /// <summary> /// Gets the value of the specified alias from the alias table. /// </summary> /// /// <param name="aliasName"> /// The name of the alias value to retrieve. /// </param> /// /// <returns> /// The AliasInfo representing the alias. /// </returns> /// internal AliasInfo GetAlias(string aliasName) { return GetAlias(aliasName, CommandOrigin.Internal); } /// <summary> /// Gets the value of the specified alias from the alias table. /// </summary> /// /// <param name="aliasName"> /// The name of the alias value to retrieve. /// </param> /// /// <param name="scopeID"> /// A scope identifier that is either one of the "special" scopes like /// "global", "script", "local", or "private, or a numeric ID of a relative scope /// to the current scope. /// </param> /// /// <returns> /// The AliasInfo representing the alias. /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="scopeID"/> is less than zero, or not /// a number and not "script", "global", "local", or "private" /// </exception> /// /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently /// active scopes. /// </exception> /// internal AliasInfo GetAliasAtScope(string aliasName, string scopeID) { AliasInfo result = null; if (String.IsNullOrEmpty(aliasName)) { return null; } SessionStateScope scope = GetScopeByID(scopeID); result = scope.GetAlias(aliasName); // Make sure the alias isn't private or if it is that the current // scope is the same scope the alias was retrieved from. if (result != null && (result.Options & ScopedItemOptions.Private) != 0 && scope != _currentScope) { result = null; } return result; } // GetAliasAtScope /// <summary> /// Sets the alias with specified name to the specified value in the current scope. /// </summary> /// /// <param name="aliasName"> /// The name of the alias to set. /// </param> /// /// <param name="value"> /// The value to set the alias to. /// </param> /// /// <param name="force"> /// If true, the value will be set even if the alias is ReadOnly. /// </param> /// /// <param name="origin"> /// THe origin of the caller of this API /// </param> /// /// <returns> /// The resulting AliasInfo for the alias that was set. /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="aliasName"/> or <paramref name="value"/> is null or empty. /// </exception> /// /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the alias is read-only or constant. /// </exception> /// /// <exception cref="SessionStateOverflowException"> /// If the maximum number of aliases has been reached for this scope. /// </exception> /// internal AliasInfo SetAliasValue(string aliasName, string value, bool force, CommandOrigin origin) { if (String.IsNullOrEmpty(aliasName)) { throw PSTraceSource.NewArgumentException("aliasName"); } if (String.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentException("value"); } AliasInfo info = _currentScope.SetAliasValue(aliasName, value, this.ExecutionContext, force, origin); return info; } // SetAliasValue /// <summary> /// Sets the alias with specified name to the specified value in the current scope. /// BUGBUG: this overload only exists for the test suites. They should be cleaned up /// and this overload removed. /// </summary> /// /// <param name="aliasName"> /// The name of the alias to set. /// </param> /// /// <param name="value"> /// The value to set the alias to. /// </param> /// /// <param name="force"> /// If true, the value will be set even if the alias is ReadOnly. /// </param> /// /// <returns> /// The resulting AliasInfo for the alias that was set. /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="aliasName"/> or <paramref name="value"/> is null or empty. /// </exception> /// /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the alias is read-only or constant. /// </exception> /// /// <exception cref="SessionStateOverflowException"> /// If the maximum number of aliases has been reached for this scope. /// </exception> /// internal AliasInfo SetAliasValue(string aliasName, string value, bool force) { return SetAliasValue(aliasName, value, force, CommandOrigin.Internal); } /// <summary> /// Sets the alias with specified name to the specified value in the current scope. /// </summary> /// /// <param name="aliasName"> /// The name of the alias to set. /// </param> /// /// <param name="value"> /// The value to set the alias to. /// </param> /// /// <param name="options"> /// The options to set on the alias. /// </param> /// /// <param name="force"> /// If true, the value will be set even if the alias is ReadOnly. /// </param> /// /// <param name="origin"> /// The origin of the caller of this API /// </param> /// /// <returns> /// The resulting AliasInfo for the alias that was set. /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="aliasName"/> or <paramref name="value"/> is null or empty. /// </exception> /// /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the alias is read-only or constant. /// </exception> /// /// <exception cref="SessionStateOverflowException"> /// If the maximum number of aliases has been reached for this scope. /// </exception> /// internal AliasInfo SetAliasValue( string aliasName, string value, ScopedItemOptions options, bool force, CommandOrigin origin) { if (String.IsNullOrEmpty(aliasName)) { throw PSTraceSource.NewArgumentException("aliasName"); } if (String.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentException("value"); } AliasInfo info = _currentScope.SetAliasValue(aliasName, value, options, this.ExecutionContext, force, origin); return info; } // SetAliasValue /// <summary> /// Sets the alias with specified name to the specified value in the current scope. /// BUGBUG: this api only exists for the test suites. They should be fixed and it should be removed. /// </summary> /// /// <param name="aliasName"> /// The name of the alias to set. /// </param> /// /// <param name="value"> /// The value to set the alias to. /// </param> /// /// <param name="options"> /// The options to set on the alias. /// </param> /// /// <param name="force"> /// If true, the value will be set even if the alias is ReadOnly. /// </param> /// /// <returns> /// The resulting AliasInfo for the alias that was set. /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="aliasName"/> or <paramref name="value"/> is null or empty. /// </exception> /// /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the alias is read-only or constant. /// </exception> /// /// <exception cref="SessionStateOverflowException"> /// If the maximum number of aliases has been reached for this scope. /// </exception> /// internal AliasInfo SetAliasValue( string aliasName, string value, ScopedItemOptions options, bool force) { return SetAliasValue(aliasName, value, options, force, CommandOrigin.Internal); } /// <summary> /// Sets the alias with specified name to the specified value in the current scope. /// </summary> /// /// <param name="alias"> /// The AliasInfo representing the alias. /// </param> /// /// <param name="force"> /// If true, the alias will be set even if there is an existing ReadOnly /// alias. /// </param> /// /// <param name="origin"> /// Specifies the origin of the comannd setting the alias. /// </param> /// /// <returns> /// The resulting AliasInfo for the alias that was set. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="alias"/> is null. /// </exception> /// /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the alias is read-only or constant. /// </exception> /// /// <exception cref="SessionStateOverflowException"> /// If the maximum number of aliases has been reached for this scope. /// </exception> /// internal AliasInfo SetAliasItem(AliasInfo alias, bool force, CommandOrigin origin) { if (alias == null) { throw PSTraceSource.NewArgumentNullException("alias"); } AliasInfo info = _currentScope.SetAliasItem(alias, force, origin); return info; } // SetAliasItem /// <summary> /// Sets the alias with specified name to the specified value in the current scope. /// </summary> /// /// <param name="alias"> /// The AliasInfo representing the alias. /// </param> /// /// <param name="scopeID"> /// A scope identifier that is either one of the "special" scopes like /// "global", "script", "local", or "private, or a numeric ID of a relative scope /// to the current scope. /// </param> /// /// <param name="force"> /// If true, the alias will be set even if there is an existing ReadOnly /// alias. /// </param> /// /// <param name="origin"> /// Specifies the command origin of the calling command. /// </param> /// /// <returns> /// The resulting AliasInfo for the alias that was set. /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="scopeID"/> is less than zero, or not /// a number and not "script", "global", "local", or "private" /// </exception> /// /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently /// active scopes. /// </exception> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="alias"/> is null. /// </exception> /// /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the alias is read-only or constant. /// </exception> /// /// <exception cref="SessionStateOverflowException"> /// If the maximum number of aliases has been reached for this scope. /// </exception> /// internal AliasInfo SetAliasItemAtScope(AliasInfo alias, string scopeID, bool force, CommandOrigin origin) { if (alias == null) { throw PSTraceSource.NewArgumentNullException("alias"); } // If the "private" scope was specified, make sure the options contain // the Private flag if (String.Equals(scopeID, StringLiterals.Private, StringComparison.OrdinalIgnoreCase)) { alias.Options |= ScopedItemOptions.Private; } SessionStateScope scope = GetScopeByID(scopeID); AliasInfo info = scope.SetAliasItem(alias, force, origin); return info; } // SetAliasItemAtScope /// <summary> /// Sets the alias with specified name to the specified value in the current scope. /// </summary> /// /// <param name="alias"> /// The AliasInfo representing the alias. /// </param> /// /// <param name="scopeID"> /// A scope identifier that is either one of the "special" scopes like /// "global", "script", "local", or "private, or a numeric ID of a relative scope /// to the current scope. /// </param> /// /// <param name="force"> /// If true, the alias will be set even if there is an existing ReadOnly /// alias. /// </param> /// /// <returns> /// The resulting AliasInfo for the alias that was set. /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="scopeID"/> is less than zero, or not /// a number and not "script", "global", "local", or "private" /// </exception> /// /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently /// active scopes. /// </exception> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="alias"/> is null. /// </exception> /// /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the alias is read-only or constant. /// </exception> /// /// <exception cref="SessionStateOverflowException"> /// If the maximum number of aliases has been reached for this scope. /// </exception> /// internal AliasInfo SetAliasItemAtScope(AliasInfo alias, string scopeID, bool force) { return SetAliasItemAtScope(alias, scopeID, force, CommandOrigin.Internal); } /// <summary> /// Removes the specified alias. /// </summary> /// /// <param name="aliasName"> /// The name of the alias to remove. /// </param> /// /// <param name="force"> /// If true the alias will be removed even if its ReadOnly. /// </param> /// /// <exception cref="ArgumentException"> /// If <paramref name="aliasName"/> is null or empty. /// </exception> /// /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the alias is constant. /// </exception> /// internal void RemoveAlias(string aliasName, bool force) { if (String.IsNullOrEmpty(aliasName)) { throw PSTraceSource.NewArgumentException("aliasName"); } // Use the scope enumerator to find an existing function SessionStateScopeEnumerator scopeEnumerator = new SessionStateScopeEnumerator(_currentScope); foreach (SessionStateScope scope in scopeEnumerator) { AliasInfo alias = scope.GetAlias(aliasName); if (alias != null) { // Make sure the alias isn't private or if it is that the current // scope is the same scope the alias was retrieved from. if ((alias.Options & ScopedItemOptions.Private) != 0 && scope != _currentScope) { alias = null; } else { scope.RemoveAlias(aliasName, force); break; } } } } // RemoveAlias /// <summary> /// Gets the alises by command name (used by metadata-driven help) /// </summary> /// <param name="command"></param> /// <returns></returns> internal IEnumerable<string> GetAliasesByCommandName(string command) { SessionStateScopeEnumerator scopeEnumerator = new SessionStateScopeEnumerator(_currentScope); foreach (SessionStateScope scope in scopeEnumerator) { foreach (string alias in scope.GetAliasesByCommandName(command)) { yield return alias; } } yield break; } #endregion aliases } // SessionStateInternal class }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Threading.Tasks; using Encog.Engine.Network.Activation; using Encog.MathUtil; using Encog.ML; using Encog.ML.Data; using Encog.ML.Train; using Encog.Neural.Flat; using Encog.Util; using Encog.Util.Logging; using Encog.Neural.Error; using Encog.Util.Concurrency; namespace Encog.Neural.Networks.Training.Propagation { /// <summary> /// Implements basic functionality that is needed by each of the propagation /// methods. The specifics of each of the propagation methods is implemented /// inside of the PropagationMethod interface implementors. /// </summary> /// public abstract class Propagation : BasicTraining, ITrain, IMultiThreadable, IBatchSize { /// <summary> /// The network in indexable form. /// </summary> /// private readonly IMLDataSet _indexable; /// <summary> /// The last gradients, from the last training iteration. /// </summary> /// private readonly double[] _lastGradient; /// <summary> /// The network to train. /// </summary> private IContainsFlat _network; /// <summary> /// The network to train. /// </summary> /// private readonly FlatNetwork _flat; /// <summary> /// The training data. /// </summary> /// private readonly IMLDataSet _training; /// <summary> /// The gradients. /// </summary> /// protected internal double[] Gradients; /// <summary> /// The iteration. /// </summary> /// private int _iteration; /// <summary> /// The number of threads to use. /// </summary> /// private int _numThreads; /// <summary> /// Reported exception from the threads. /// </summary> /// private Exception _reportedException; /// <summary> /// The total error. Used to take the average of. /// </summary> /// private double _totalError; /// <summary> /// The workers. /// </summary> /// private GradientWorker[] _workers; /// <summary> /// True (default) if we should fix flatspots on supported activation functions. /// </summary> public bool FixFlatSpot { get; set; } /// <summary> /// The flat spot constants. /// </summary> private double[] _flatSpot; /// <summary> /// The error function. /// </summary> public IErrorFunction ErrorFunction { get; set; } /// <summary> /// Construct a propagation object. /// </summary> /// /// <param name="network">The network.</param> /// <param name="training">The training set.</param> protected Propagation(IContainsFlat network, IMLDataSet training) : base(TrainingImplementationType.Iterative) { _network = network; _flat = network.Flat; _training = training; Gradients = new double[_flat.Weights.Length]; _lastGradient = new double[_flat.Weights.Length]; _indexable = training; _numThreads = 0; _reportedException = null; FixFlatSpot = true; ErrorFunction = new LinearErrorFunction(); } /// <summary> /// Set the number of threads. Specify zero to tell Encog to automatically /// determine the best number of threads for the processor. If OpenCL is used /// as the target device, then this value is not used. /// </summary> public int ThreadCount { get { return _numThreads; } set { _numThreads = value; } } /// <summary> /// Increase the iteration count by one. /// </summary> public void RollIteration() { _iteration++; } #region Train Members /// <inheritdoc/> public override IMLMethod Method { get { return _network; } } /// <summary> /// Perform the specified number of training iterations. This can be more /// efficient than single training iterations. This is particularly true if /// you are training with a GPU. /// </summary> public override void Iteration() { try { PreIteration(); RollIteration(); if (BatchSize == 0) { ProcessPureBatch(); } else { ProcessBatches(); } foreach (GradientWorker worker in _workers) { EngineArray.ArrayCopy(_flat.Weights, 0, worker.Weights, 0, _flat.Weights.Length); } if (_flat.HasContext) { CopyContexts(); } if (_reportedException != null) { throw (new EncogError(_reportedException)); } PostIteration(); EncogLogging.Log(EncogLogging.LevelInfo, "Training iterations done, error: " + Error); } catch (IndexOutOfRangeException ex) { EncogValidate.ValidateNetworkForTraining(_network, Training); throw new EncogError(ex); } } /// <value>The gradients from the last iteration;</value> public double[] LastGradient { get { return _lastGradient; } } #region TrainFlatNetwork Members /// <inheritdoc/> public virtual void FinishTraining() { // nothing to do } /// <inheritdoc/> public override int IterationNumber { get { return _iteration; } set { _iteration = value; } } /// <inheritdoc/> public IContainsFlat Network { get { return _network; } } /// <inheritdoc/> public int NumThreads { get { return _numThreads; } set { _numThreads = value; } } /// <inheritdoc/> public IMLDataSet Training { get { return _training; } } #endregion /// <summary> /// Calculate the gradients. /// </summary> /// public virtual void CalculateGradients() { if (_workers == null) { Init(); } if (_flat.HasContext) { _workers[0].Network.ClearContext(); } _totalError = 0; Parallel.ForEach(_workers, worker => worker.Run()); Error = _totalError / _workers.Length; } /// <summary> /// Copy the contexts to keep them consistent with multithreaded training. /// </summary> /// private void CopyContexts() { // copy the contexts(layer outputO from each group to the next group for (int i = 0; i < (_workers.Length - 1); i++) { double[] src = _workers[i].Network.LayerOutput; double[] dst = _workers[i + 1].Network.LayerOutput; EngineArray.ArrayCopy(src, dst); } // copy the contexts from the final group to the real network EngineArray.ArrayCopy(_workers[_workers.Length - 1].Network.LayerOutput, _flat.LayerOutput); } /// <summary> /// Init the process. /// </summary> /// private void Init() { // fix flat spot, if needed _flatSpot = new double[_flat.ActivationFunctions.Length]; if (FixFlatSpot) { for (int i = 0; i < _flat.ActivationFunctions.Length; i++) { IActivationFunction af = _flat.ActivationFunctions[i]; if( af is ActivationSigmoid ) { _flatSpot[i] = 0.1; } else { _flatSpot[i] = 0.0; } } } else { EngineArray.Fill(_flatSpot, 0.0); } var determine = new DetermineWorkload( _numThreads, (int)_indexable.Count); _workers = new GradientWorker[determine.ThreadCount]; int index = 0; // handle CPU foreach (IntRange r in determine.CalculateWorkers()) { _workers[index++] = new GradientWorker(((FlatNetwork)_network.Flat.Clone()), this, _indexable.OpenAdditional(), r.Low, r.High, _flatSpot, ErrorFunction); } InitOthers(); } /// <summary> /// Apply and learn. /// </summary> /// protected internal void Learn() { double[] weights = _flat.Weights; // Parallel.For(0, Gradients.Length, i => for (int i = 0; i < Gradients.Length; i++) { weights[i] += UpdateWeight(Gradients, _lastGradient, i); Gradients[i] = 0; } // ); } /// <summary> /// Apply and learn. This is the same as learn, but it checks to see if any /// of the weights are below the limit threshold. In this case, these weights /// are zeroed out. Having two methods allows the regular learn method, which /// is what is usually use, to be as fast as possible. /// </summary> /// protected internal void LearnLimited() { double limit = _flat.ConnectionLimit; double[] weights = _flat.Weights; for (int i = 0; i < Gradients.Length; i++) { if (Math.Abs(weights[i]) < limit) { weights[i] = 0; } else { weights[i] += UpdateWeight(Gradients, _lastGradient, i); } Gradients[i] = 0; } } /// <summary> /// Called by the worker threads to report the progress at each step. /// </summary> /// /// <param name="gradients">The gradients from that worker.</param> /// <param name="error">The error for that worker.</param> /// <param name="ex">The exception.</param> public void Report(double[] gradients, double error, Exception ex) { lock (this) { if (ex == null) { for (int i = 0; i < gradients.Length; i++) { Gradients[i] += gradients[i]; } _totalError += error; } else { _reportedException = ex; } } } /// <summary> /// Update a weight, the means by which weights are updated vary depending on /// the training. /// </summary> /// /// <param name="gradients">The gradients.</param> /// <param name="lastGradient">The last gradients.</param> /// <param name="index">The index.</param> /// <returns>The update value.</returns> public abstract double UpdateWeight(double[] gradients, double[] lastGradient, int index); /// <summary> /// Allow other training methods to init. /// </summary> public abstract void InitOthers(); #endregion /// <summary> /// Process as pure batch (size 0). Batch size equal to training set size. /// </summary> private void ProcessPureBatch() { CalculateGradients(); if (_flat.Limited) { LearnLimited(); } else { Learn(); } } private void ProcessBatches() { if (_workers == null) { Init(); } if (_flat.HasContext) { _workers[0].Network.ClearContext(); } _workers[0].CalculateError.Reset(); int lastLearn = 0; for (int i = 0; i < Training.Count; i++) { _workers[0].Run(i); lastLearn++; if (lastLearn++ >= BatchSize) { if (_flat.Limited) { LearnLimited(); } else { Learn(); lastLearn = 0; } } } // handle any remaining learning if (lastLearn > 0) { Learn(); } this.Error = _workers[0].CalculateError.Calculate(); } /// <summary> /// The batch size. Specify 1 for pure online training. Specify 0 for pure /// batch training (complete training set in one batch). Otherwise specify /// the batch size for batch training. /// </summary> public int BatchSize { get; set; } } }
using System; using System.Linq; using System.Messaging; using Rhino.Queues; using Rhino.ServiceBus.Actions; using Rhino.ServiceBus.Config; using Rhino.ServiceBus.Convertors; using Rhino.ServiceBus.DataStructures; using Rhino.ServiceBus.Impl; using Rhino.ServiceBus.Internal; using Rhino.ServiceBus.LoadBalancer; using Rhino.ServiceBus.MessageModules; using Rhino.ServiceBus.Msmq; using Rhino.ServiceBus.Msmq.TransportActions; using Rhino.ServiceBus.RhinoQueues; using Spring.Context; using ErrorAction = Rhino.ServiceBus.Msmq.TransportActions.ErrorAction; using LoadBalancerConfiguration = Rhino.ServiceBus.LoadBalancer.LoadBalancerConfiguration; namespace Rhino.ServiceBus.Spring { [CLSCompliant(false)] public class SpringBuilder : IBusContainerBuilder { private readonly AbstractRhinoServiceBusConfiguration config; private readonly IConfigurableApplicationContext applicationContext; public SpringBuilder(AbstractRhinoServiceBusConfiguration config, IConfigurableApplicationContext applicationContext) { this.config = config; this.applicationContext = applicationContext; config.BuildWith(this); } public void WithInterceptor(IConsumerInterceptor interceptor) { applicationContext.ObjectFactory.AddObjectPostProcessor(new ConsumerInterceptor(interceptor, applicationContext)); } public void RegisterDefaultServices() { applicationContext.RegisterSingleton<IServiceLocator>(() => new SpringServiceLocator(applicationContext)); applicationContext.RegisterSingletons<IBusConfigurationAware>(typeof(IServiceBus).Assembly); foreach (var busConfigurationAware in applicationContext.GetAll<IBusConfigurationAware>()) { busConfigurationAware.Configure(config, this); } foreach (var module in config.MessageModules) { applicationContext.RegisterSingleton(module, module.FullName); } applicationContext.RegisterSingleton<IReflection>(() => new DefaultReflection()); applicationContext.RegisterSingleton(config.SerializerType); applicationContext.RegisterSingleton<IEndpointRouter>(() => new EndpointRouter()); } public void RegisterBus() { var busConfig = (RhinoServiceBusConfiguration) config; applicationContext.RegisterSingleton<IStartableServiceBus>(() => new DefaultServiceBus(applicationContext.Get<IServiceLocator>(), applicationContext.Get<ITransport>(), applicationContext.Get<ISubscriptionStorage>(), applicationContext.Get<IReflection>(), applicationContext.GetAll<IMessageModule>().ToArray(), busConfig.MessageOwners.ToArray(), applicationContext.Get<IEndpointRouter>())); applicationContext.RegisterSingleton(() => new CreateQueuesAction(applicationContext.Get<IQueueStrategy>(), applicationContext.Get<IServiceBus>())); } public void RegisterPrimaryLoadBalancer() { var loadBalancerConfig = (LoadBalancerConfiguration) config; applicationContext.RegisterSingleton(() => { MsmqLoadBalancer balancer = new MsmqLoadBalancer(applicationContext.Get<IMessageSerializer>(), applicationContext.Get<IQueueStrategy>(), applicationContext.Get<IEndpointRouter>(), loadBalancerConfig.Endpoint, loadBalancerConfig.ThreadCount, loadBalancerConfig.Transactional, applicationContext.Get<IMessageBuilder<Message>>()); balancer.ReadyForWorkListener = applicationContext.Get<MsmqReadyForWorkListener>(); return balancer; }); applicationContext.RegisterSingleton<IDeploymentAction>(() => new CreateLoadBalancerQueuesAction(applicationContext.Get<IQueueStrategy>(), applicationContext.Get<MsmqLoadBalancer>())); } public void RegisterSecondaryLoadBalancer() { var loadBalancerConfig = (LoadBalancerConfiguration) config; applicationContext.RegisterSingleton<MsmqLoadBalancer>(() => { MsmqSecondaryLoadBalancer balancer = new MsmqSecondaryLoadBalancer(applicationContext.Get<IMessageSerializer>(), applicationContext.Get<IQueueStrategy>(), applicationContext.Get<IEndpointRouter>(), loadBalancerConfig.Endpoint, loadBalancerConfig.PrimaryLoadBalancer, loadBalancerConfig.ThreadCount, loadBalancerConfig.Transactional, applicationContext.Get<IMessageBuilder<Message>>()); balancer.ReadyForWorkListener = applicationContext.Get<MsmqReadyForWorkListener>(); return balancer; }); applicationContext.RegisterSingleton<IDeploymentAction>(() => new CreateLoadBalancerQueuesAction(applicationContext.Get<IQueueStrategy>(), applicationContext.Get<MsmqLoadBalancer>())); } public void RegisterReadyForWork() { var loadBalancerConfig = (LoadBalancerConfiguration) config; applicationContext.RegisterSingleton(() => new MsmqReadyForWorkListener(applicationContext.Get<IQueueStrategy>(), loadBalancerConfig.ReadyForWork, loadBalancerConfig.ThreadCount, applicationContext.Get<IMessageSerializer>(), applicationContext.Get<IEndpointRouter>(), loadBalancerConfig.Transactional, applicationContext.Get<IMessageBuilder<Message>>())); applicationContext.RegisterSingleton<IDeploymentAction>(() => new CreateReadyForWorkQueuesAction(applicationContext.Get<IQueueStrategy>(), applicationContext.Get<MsmqReadyForWorkListener>())); } public void RegisterLoadBalancerEndpoint(Uri loadBalancerEndpoint) { applicationContext.RegisterSingleton(typeof (LoadBalancerMessageModule).FullName, () => new LoadBalancerMessageModule( loadBalancerEndpoint, applicationContext.Get<IEndpointRouter>())); } public void RegisterLoggingEndpoint(Uri logEndpoint) { applicationContext.RegisterSingleton(typeof (MessageLoggingModule).FullName, () => new MessageLoggingModule(applicationContext.Get<IEndpointRouter>(), logEndpoint)); applicationContext.RegisterSingleton<IDeploymentAction>(() => new CreateLogQueueAction(applicationContext.Get<MessageLoggingModule>(), applicationContext.Get<ITransport>())); } public void RegisterMsmqTransport(Type queueStrategyType) { if (queueStrategyType.GetConstructor(new[] {typeof (IQueueStrategy), typeof (Uri)}) != null) { applicationContext.RegisterSingleton(queueStrategyType, typeof (IQueueStrategy).FullName, applicationContext.Get<IEndpointRouter>(), config.Endpoint); } else { // use default applicationContext.RegisterSingleton(queueStrategyType); } applicationContext.RegisterSingleton<IMessageBuilder<Message>>(() => new MsmqMessageBuilder( applicationContext.Get<IMessageSerializer>(), applicationContext.Get<IServiceLocator>())); applicationContext.RegisterSingleton<IMsmqTransportAction>(() => new ErrorAction( config.NumberOfRetries, applicationContext.Get<IQueueStrategy>())); applicationContext.RegisterSingleton<ISubscriptionStorage>(() => new MsmqSubscriptionStorage( applicationContext.Get<IReflection>(), applicationContext.Get<IMessageSerializer>(), config.Endpoint, applicationContext.Get<IEndpointRouter>(), applicationContext.Get<IQueueStrategy>())); applicationContext.RegisterSingleton<ITransport>(typeof (MsmqTransport).FullName, () => new MsmqTransport( applicationContext.Get<IMessageSerializer>(), applicationContext.Get<IQueueStrategy>(), config.Endpoint, config.ThreadCount, applicationContext.GetAll<IMsmqTransportAction>().ToArray(), applicationContext.Get<IEndpointRouter>(), config.IsolationLevel, config.Transactional, config.ConsumeInTransaction, applicationContext.Get<IMessageBuilder<Message>>())); typeof (IMsmqTransportAction).Assembly.GetTypes() .Where(x => typeof (IMsmqTransportAction).IsAssignableFrom(x) && x != typeof (ErrorAction) && !x.IsAbstract && !x.IsInterface) .ToList() .ForEach(x => applicationContext.RegisterSingleton(x, x.FullName)); } public void RegisterQueueCreation() { applicationContext.RegisterSingleton(() => new QueueCreationModule(applicationContext.Get<IQueueStrategy>())); } public void RegisterMsmqOneWay() { var oneWayConfig = (OnewayRhinoServiceBusConfiguration) config; applicationContext.RegisterSingleton<IMessageBuilder<Message>>(() => new MsmqMessageBuilder(applicationContext.Get<IMessageSerializer>(), applicationContext.Get<IServiceLocator>())); applicationContext.RegisterSingleton<IOnewayBus>(() => new MsmqOnewayBus(oneWayConfig.MessageOwners, applicationContext.Get<IMessageBuilder<Message>>())); } public void RegisterRhinoQueuesTransport() { var busConfig = config.ConfigurationSection.Bus; applicationContext.RegisterSingleton<ISubscriptionStorage>(() => new PhtSubscriptionStorage(busConfig.SubscriptionPath, applicationContext.Get<IMessageSerializer>(), applicationContext.Get<IReflection>())); applicationContext.RegisterSingleton<ITransport>(typeof (RhinoQueuesTransport).FullName, () => new RhinoQueuesTransport(config.Endpoint, applicationContext.Get<IEndpointRouter>(), applicationContext.Get<IMessageSerializer>(), config.ThreadCount, busConfig.QueuePath, config.IsolationLevel, config.NumberOfRetries, busConfig.EnablePerformanceCounters, applicationContext.Get<IMessageBuilder<MessagePayload>>())); applicationContext.RegisterSingleton<IMessageBuilder<MessagePayload>>(() => new RhinoQueuesMessageBuilder(applicationContext.Get<IMessageSerializer>())); } public void RegisterRhinoQueuesOneWay() { var oneWayConfig = (OnewayRhinoServiceBusConfiguration) config; var busConfig = config.ConfigurationSection.Bus; applicationContext.RegisterSingleton<IMessageBuilder<MessagePayload>>(() => new RhinoQueuesMessageBuilder(applicationContext.Get<IMessageSerializer>())); applicationContext.RegisterSingleton<IOnewayBus>(() => new RhinoQueuesOneWayBus(oneWayConfig.MessageOwners, applicationContext.Get<IMessageSerializer>(), busConfig.QueuePath, busConfig.EnablePerformanceCounters, applicationContext.Get<IMessageBuilder<MessagePayload>>())); } public void RegisterSecurity(byte[] key) { applicationContext.RegisterSingleton<IEncryptionService>(() => new RijndaelEncryptionService(key)); applicationContext.RegisterSingleton<IValueConvertor<WireEcryptedString>>(() => new WireEcryptedStringConvertor(applicationContext.Get<IEncryptionService>())); applicationContext.RegisterSingleton<IElementSerializationBehavior>(() => new WireEncryptedMessageConvertor(applicationContext.Get<IEncryptionService>())); } public void RegisterNoSecurity() { applicationContext.RegisterSingleton<IValueConvertor<WireEcryptedString>>(() => new ThrowingWireEcryptedStringConvertor()); applicationContext.RegisterSingleton<IElementSerializationBehavior>(() => new ThrowingWireEncryptedMessageConvertor()); } } }
/* * 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. */ // There are 3 #defines that have an impact on performance / features of this ByteBuffer implementation // // UNSAFE_BYTEBUFFER // This will use unsafe code to manipulate the underlying byte array. This // can yield a reasonable performance increase. // // BYTEBUFFER_NO_BOUNDS_CHECK // This will disable the bounds check asserts to the byte array. This can // yield a small performance gain in normal code.. // // ENABLE_SPAN_T // This will enable reading and writing blocks of memory with a Span<T> instead if just // T[]. You can also enable writing directly to shared memory or other types of memory // by providing a custom implementation of ByteBufferAllocator. // ENABLE_SPAN_T also requires UNSAFE_BYTEBUFFER to be defined // // Using UNSAFE_BYTEBUFFER and BYTEBUFFER_NO_BOUNDS_CHECK together can yield a // performance gain of ~15% for some operations, however doing so is potentially // dangerous. Do so at your own risk! // using System; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; #if ENABLE_SPAN_T using System.Buffers.Binary; #endif #if ENABLE_SPAN_T && !UNSAFE_BYTEBUFFER #error ENABLE_SPAN_T requires UNSAFE_BYTEBUFFER to also be defined #endif namespace FlatBuffers { internal abstract class ByteBufferAllocator { #if ENABLE_SPAN_T public abstract Span<byte> Span { get; } public abstract ReadOnlySpan<byte> ReadOnlySpan { get; } public abstract Memory<byte> Memory { get; } public abstract ReadOnlyMemory<byte> ReadOnlyMemory { get; } #else public byte[] Buffer { get; protected set; } #endif public int Length { get; protected set; } public abstract void GrowFront(int newSize); } internal sealed class ByteArrayAllocator : ByteBufferAllocator { private byte[] _buffer; public ByteArrayAllocator(byte[] buffer) { _buffer = buffer; InitBuffer(); } public override void GrowFront(int newSize) { if ((Length & 0xC0000000) != 0) throw new Exception( "ByteBuffer: cannot grow buffer beyond 2 gigabytes."); if (newSize < Length) throw new Exception("ByteBuffer: cannot truncate buffer."); byte[] newBuffer = new byte[newSize]; System.Buffer.BlockCopy(_buffer, 0, newBuffer, newSize - Length, Length); _buffer = newBuffer; InitBuffer(); } #if ENABLE_SPAN_T public override Span<byte> Span => _buffer; public override ReadOnlySpan<byte> ReadOnlySpan => _buffer; public override Memory<byte> Memory => _buffer; public override ReadOnlyMemory<byte> ReadOnlyMemory => _buffer; #endif private void InitBuffer() { Length = _buffer.Length; #if !ENABLE_SPAN_T Buffer = _buffer; #endif } } /// <summary> /// Class to mimic Java's ByteBuffer which is used heavily in Flatbuffers. /// </summary> internal class ByteBuffer { private ByteBufferAllocator _buffer; private int _pos; // Must track start of the buffer. public ByteBuffer(ByteBufferAllocator allocator, int position) { _buffer = allocator; _pos = position; } public ByteBuffer(int size) : this(new byte[size]) { } public ByteBuffer(byte[] buffer) : this(buffer, 0) { } public ByteBuffer(byte[] buffer, int pos) { _buffer = new ByteArrayAllocator(buffer); _pos = pos; } public int Position { get { return _pos; } set { _pos = value; } } public int Length { get { return _buffer.Length; } } public void Reset() { _pos = 0; } // Create a new ByteBuffer on the same underlying data. // The new ByteBuffer's position will be same as this buffer's. public ByteBuffer Duplicate() { return new ByteBuffer(_buffer, Position); } // Increases the size of the ByteBuffer, and copies the old data towards // the end of the new buffer. public void GrowFront(int newSize) { _buffer.GrowFront(newSize); } public byte[] ToArray(int pos, int len) { return ToArray<byte>(pos, len); } /// <summary> /// A lookup of type sizes. Used instead of Marshal.SizeOf() which has additional /// overhead, but also is compatible with generic functions for simplified code. /// </summary> private static Dictionary<Type, int> genericSizes = new Dictionary<Type, int>() { { typeof(bool), sizeof(bool) }, { typeof(float), sizeof(float) }, { typeof(double), sizeof(double) }, { typeof(sbyte), sizeof(sbyte) }, { typeof(byte), sizeof(byte) }, { typeof(short), sizeof(short) }, { typeof(ushort), sizeof(ushort) }, { typeof(int), sizeof(int) }, { typeof(uint), sizeof(uint) }, { typeof(ulong), sizeof(ulong) }, { typeof(long), sizeof(long) }, }; /// <summary> /// Get the wire-size (in bytes) of a type supported by flatbuffers. /// </summary> /// <param name="t">The type to get the wire size of</param> /// <returns></returns> public static int SizeOf<T>() { return genericSizes[typeof(T)]; } /// <summary> /// Checks if the Type provided is supported as scalar value /// </summary> /// <typeparam name="T">The Type to check</typeparam> /// <returns>True if the type is a scalar type that is supported, falsed otherwise</returns> public static bool IsSupportedType<T>() { return genericSizes.ContainsKey(typeof(T)); } /// <summary> /// Get the wire-size (in bytes) of a typed array /// </summary> /// <typeparam name="T">The type of the array</typeparam> /// <param name="x">The array to get the size of</param> /// <returns>The number of bytes the array takes on wire</returns> public static int ArraySize<T>(T[] x) { return SizeOf<T>() * x.Length; } #if ENABLE_SPAN_T public static int ArraySize<T>(Span<T> x) { return SizeOf<T>() * x.Length; } #endif // Get a portion of the buffer casted into an array of type T, given // the buffer position and length. #if ENABLE_SPAN_T public T[] ToArray<T>(int pos, int len) where T : struct { AssertOffsetAndLength(pos, len); return MemoryMarshal.Cast<byte, T>(_buffer.ReadOnlySpan.Slice(pos)).Slice(0, len).ToArray(); } #else public T[] ToArray<T>(int pos, int len) where T : struct { AssertOffsetAndLength(pos, len); T[] arr = new T[len]; Buffer.BlockCopy(_buffer.Buffer, pos, arr, 0, ArraySize(arr)); return arr; } #endif public byte[] ToSizedArray() { return ToArray<byte>(Position, Length - Position); } public byte[] ToFullArray() { return ToArray<byte>(0, Length); } #if ENABLE_SPAN_T public ReadOnlyMemory<byte> ToReadOnlyMemory(int pos, int len) { return _buffer.ReadOnlyMemory.Slice(pos, len); } public Memory<byte> ToMemory(int pos, int len) { return _buffer.Memory.Slice(pos, len); } public Span<byte> ToSpan(int pos, int len) { return _buffer.Span.Slice(pos, len); } #else public ArraySegment<byte> ToArraySegment(int pos, int len) { return new ArraySegment<byte>(_buffer.Buffer, pos, len); } public MemoryStream ToMemoryStream(int pos, int len) { return new MemoryStream(_buffer.Buffer, pos, len); } #endif #if !UNSAFE_BYTEBUFFER // Pre-allocated helper arrays for conversion. private float[] floathelper = new[] { 0.0f }; private int[] inthelper = new[] { 0 }; private double[] doublehelper = new[] { 0.0 }; private ulong[] ulonghelper = new[] { 0UL }; #endif // !UNSAFE_BYTEBUFFER // Helper functions for the unsafe version. static public ushort ReverseBytes(ushort input) { return (ushort)(((input & 0x00FFU) << 8) | ((input & 0xFF00U) >> 8)); } static public uint ReverseBytes(uint input) { return ((input & 0x000000FFU) << 24) | ((input & 0x0000FF00U) << 8) | ((input & 0x00FF0000U) >> 8) | ((input & 0xFF000000U) >> 24); } static public ulong ReverseBytes(ulong input) { return (((input & 0x00000000000000FFUL) << 56) | ((input & 0x000000000000FF00UL) << 40) | ((input & 0x0000000000FF0000UL) << 24) | ((input & 0x00000000FF000000UL) << 8) | ((input & 0x000000FF00000000UL) >> 8) | ((input & 0x0000FF0000000000UL) >> 24) | ((input & 0x00FF000000000000UL) >> 40) | ((input & 0xFF00000000000000UL) >> 56)); } #if !UNSAFE_BYTEBUFFER // Helper functions for the safe (but slower) version. protected void WriteLittleEndian(int offset, int count, ulong data) { if (BitConverter.IsLittleEndian) { for (int i = 0; i < count; i++) { _buffer.Buffer[offset + i] = (byte)(data >> i * 8); } } else { for (int i = 0; i < count; i++) { _buffer.Buffer[offset + count - 1 - i] = (byte)(data >> i * 8); } } } protected ulong ReadLittleEndian(int offset, int count) { AssertOffsetAndLength(offset, count); ulong r = 0; if (BitConverter.IsLittleEndian) { for (int i = 0; i < count; i++) { r |= (ulong)_buffer.Buffer[offset + i] << i * 8; } } else { for (int i = 0; i < count; i++) { r |= (ulong)_buffer.Buffer[offset + count - 1 - i] << i * 8; } } return r; } #endif // !UNSAFE_BYTEBUFFER private void AssertOffsetAndLength(int offset, int length) { #if !BYTEBUFFER_NO_BOUNDS_CHECK if (offset < 0 || offset > _buffer.Length - length) throw new ArgumentOutOfRangeException(); #endif } #if ENABLE_SPAN_T public void PutSbyte(int offset, sbyte value) { AssertOffsetAndLength(offset, sizeof(sbyte)); _buffer.Span[offset] = (byte)value; } public void PutByte(int offset, byte value) { AssertOffsetAndLength(offset, sizeof(byte)); _buffer.Span[offset] = value; } public void PutByte(int offset, byte value, int count) { AssertOffsetAndLength(offset, sizeof(byte) * count); Span<byte> span = _buffer.Span.Slice(offset, count); for (var i = 0; i < span.Length; ++i) span[i] = value; } #else public void PutSbyte(int offset, sbyte value) { AssertOffsetAndLength(offset, sizeof(sbyte)); _buffer.Buffer[offset] = (byte)value; } public void PutByte(int offset, byte value) { AssertOffsetAndLength(offset, sizeof(byte)); _buffer.Buffer[offset] = value; } public void PutByte(int offset, byte value, int count) { AssertOffsetAndLength(offset, sizeof(byte) * count); for (var i = 0; i < count; ++i) _buffer.Buffer[offset + i] = value; } #endif // this method exists in order to conform with Java ByteBuffer standards public void Put(int offset, byte value) { PutByte(offset, value); } #if ENABLE_SPAN_T public unsafe void PutStringUTF8(int offset, string value) { AssertOffsetAndLength(offset, value.Length); fixed (char* s = value) { fixed (byte* buffer = &MemoryMarshal.GetReference(_buffer.Span)) { Encoding.UTF8.GetBytes(s, value.Length, buffer + offset, Length - offset); } } } #else public void PutStringUTF8(int offset, string value) { AssertOffsetAndLength(offset, value.Length); Encoding.UTF8.GetBytes(value, 0, value.Length, _buffer.Buffer, offset); } #endif #if UNSAFE_BYTEBUFFER // Unsafe but more efficient versions of Put*. public void PutShort(int offset, short value) { PutUshort(offset, (ushort)value); } public unsafe void PutUshort(int offset, ushort value) { AssertOffsetAndLength(offset, sizeof(ushort)); #if ENABLE_SPAN_T Span<byte> span = _buffer.Span.Slice(offset); BinaryPrimitives.WriteUInt16LittleEndian(span, value); #else fixed (byte* ptr = _buffer.Buffer) { *(ushort*)(ptr + offset) = BitConverter.IsLittleEndian ? value : ReverseBytes(value); } #endif } public void PutInt(int offset, int value) { PutUint(offset, (uint)value); } public unsafe void PutUint(int offset, uint value) { AssertOffsetAndLength(offset, sizeof(uint)); #if ENABLE_SPAN_T Span<byte> span = _buffer.Span.Slice(offset); BinaryPrimitives.WriteUInt32LittleEndian(span, value); #else fixed (byte* ptr = _buffer.Buffer) { *(uint*)(ptr + offset) = BitConverter.IsLittleEndian ? value : ReverseBytes(value); } #endif } public unsafe void PutLong(int offset, long value) { PutUlong(offset, (ulong)value); } public unsafe void PutUlong(int offset, ulong value) { AssertOffsetAndLength(offset, sizeof(ulong)); #if ENABLE_SPAN_T Span<byte> span = _buffer.Span.Slice(offset); BinaryPrimitives.WriteUInt64LittleEndian(span, value); #else fixed (byte* ptr = _buffer.Buffer) { *(ulong*)(ptr + offset) = BitConverter.IsLittleEndian ? value : ReverseBytes(value); } #endif } public unsafe void PutFloat(int offset, float value) { AssertOffsetAndLength(offset, sizeof(float)); #if ENABLE_SPAN_T fixed (byte* ptr = &MemoryMarshal.GetReference(_buffer.Span)) #else fixed (byte* ptr = _buffer.Buffer) #endif { if (BitConverter.IsLittleEndian) { *(float*)(ptr + offset) = value; } else { *(uint*)(ptr + offset) = ReverseBytes(*(uint*)(&value)); } } } public unsafe void PutDouble(int offset, double value) { AssertOffsetAndLength(offset, sizeof(double)); #if ENABLE_SPAN_T fixed (byte* ptr = &MemoryMarshal.GetReference(_buffer.Span)) #else fixed (byte* ptr = _buffer.Buffer) #endif { if (BitConverter.IsLittleEndian) { *(double*)(ptr + offset) = value; } else { *(ulong*)(ptr + offset) = ReverseBytes(*(ulong*)(&value)); } } } #else // !UNSAFE_BYTEBUFFER // Slower versions of Put* for when unsafe code is not allowed. public void PutShort(int offset, short value) { AssertOffsetAndLength(offset, sizeof(short)); WriteLittleEndian(offset, sizeof(short), (ulong)value); } public void PutUshort(int offset, ushort value) { AssertOffsetAndLength(offset, sizeof(ushort)); WriteLittleEndian(offset, sizeof(ushort), (ulong)value); } public void PutInt(int offset, int value) { AssertOffsetAndLength(offset, sizeof(int)); WriteLittleEndian(offset, sizeof(int), (ulong)value); } public void PutUint(int offset, uint value) { AssertOffsetAndLength(offset, sizeof(uint)); WriteLittleEndian(offset, sizeof(uint), (ulong)value); } public void PutLong(int offset, long value) { AssertOffsetAndLength(offset, sizeof(long)); WriteLittleEndian(offset, sizeof(long), (ulong)value); } public void PutUlong(int offset, ulong value) { AssertOffsetAndLength(offset, sizeof(ulong)); WriteLittleEndian(offset, sizeof(ulong), value); } public void PutFloat(int offset, float value) { AssertOffsetAndLength(offset, sizeof(float)); floathelper[0] = value; Buffer.BlockCopy(floathelper, 0, inthelper, 0, sizeof(float)); WriteLittleEndian(offset, sizeof(float), (ulong)inthelper[0]); } public void PutDouble(int offset, double value) { AssertOffsetAndLength(offset, sizeof(double)); doublehelper[0] = value; Buffer.BlockCopy(doublehelper, 0, ulonghelper, 0, sizeof(double)); WriteLittleEndian(offset, sizeof(double), ulonghelper[0]); } #endif // UNSAFE_BYTEBUFFER #if ENABLE_SPAN_T public sbyte GetSbyte(int index) { AssertOffsetAndLength(index, sizeof(sbyte)); return (sbyte)_buffer.ReadOnlySpan[index]; } public byte Get(int index) { AssertOffsetAndLength(index, sizeof(byte)); return _buffer.ReadOnlySpan[index]; } #else public sbyte GetSbyte(int index) { AssertOffsetAndLength(index, sizeof(sbyte)); return (sbyte)_buffer.Buffer[index]; } public byte Get(int index) { AssertOffsetAndLength(index, sizeof(byte)); return _buffer.Buffer[index]; } #endif #if ENABLE_SPAN_T public unsafe string GetStringUTF8(int startPos, int len) { fixed (byte* buffer = &MemoryMarshal.GetReference(_buffer.ReadOnlySpan.Slice(startPos))) { return Encoding.UTF8.GetString(buffer, len); } } #else public string GetStringUTF8(int startPos, int len) { return Encoding.UTF8.GetString(_buffer.Buffer, startPos, len); } #endif #if UNSAFE_BYTEBUFFER // Unsafe but more efficient versions of Get*. public short GetShort(int offset) { return (short)GetUshort(offset); } public unsafe ushort GetUshort(int offset) { AssertOffsetAndLength(offset, sizeof(ushort)); #if ENABLE_SPAN_T ReadOnlySpan<byte> span = _buffer.ReadOnlySpan.Slice(offset); return BinaryPrimitives.ReadUInt16LittleEndian(span); #else fixed (byte* ptr = _buffer.Buffer) { return BitConverter.IsLittleEndian ? *(ushort*)(ptr + offset) : ReverseBytes(*(ushort*)(ptr + offset)); } #endif } public int GetInt(int offset) { return (int)GetUint(offset); } public unsafe uint GetUint(int offset) { AssertOffsetAndLength(offset, sizeof(uint)); #if ENABLE_SPAN_T ReadOnlySpan<byte> span = _buffer.ReadOnlySpan.Slice(offset); return BinaryPrimitives.ReadUInt32LittleEndian(span); #else fixed (byte* ptr = _buffer.Buffer) { return BitConverter.IsLittleEndian ? *(uint*)(ptr + offset) : ReverseBytes(*(uint*)(ptr + offset)); } #endif } public long GetLong(int offset) { return (long)GetUlong(offset); } public unsafe ulong GetUlong(int offset) { AssertOffsetAndLength(offset, sizeof(ulong)); #if ENABLE_SPAN_T ReadOnlySpan<byte> span = _buffer.ReadOnlySpan.Slice(offset); return BinaryPrimitives.ReadUInt64LittleEndian(span); #else fixed (byte* ptr = _buffer.Buffer) { return BitConverter.IsLittleEndian ? *(ulong*)(ptr + offset) : ReverseBytes(*(ulong*)(ptr + offset)); } #endif } public unsafe float GetFloat(int offset) { AssertOffsetAndLength(offset, sizeof(float)); #if ENABLE_SPAN_T fixed (byte* ptr = &MemoryMarshal.GetReference(_buffer.ReadOnlySpan)) #else fixed (byte* ptr = _buffer.Buffer) #endif { if (BitConverter.IsLittleEndian) { return *(float*)(ptr + offset); } else { uint uvalue = ReverseBytes(*(uint*)(ptr + offset)); return *(float*)(&uvalue); } } } public unsafe double GetDouble(int offset) { AssertOffsetAndLength(offset, sizeof(double)); #if ENABLE_SPAN_T fixed (byte* ptr = &MemoryMarshal.GetReference(_buffer.ReadOnlySpan)) #else fixed (byte* ptr = _buffer.Buffer) #endif { if (BitConverter.IsLittleEndian) { return *(double*)(ptr + offset); } else { ulong uvalue = ReverseBytes(*(ulong*)(ptr + offset)); return *(double*)(&uvalue); } } } #else // !UNSAFE_BYTEBUFFER // Slower versions of Get* for when unsafe code is not allowed. public short GetShort(int index) { return (short)ReadLittleEndian(index, sizeof(short)); } public ushort GetUshort(int index) { return (ushort)ReadLittleEndian(index, sizeof(ushort)); } public int GetInt(int index) { return (int)ReadLittleEndian(index, sizeof(int)); } public uint GetUint(int index) { return (uint)ReadLittleEndian(index, sizeof(uint)); } public long GetLong(int index) { return (long)ReadLittleEndian(index, sizeof(long)); } public ulong GetUlong(int index) { return ReadLittleEndian(index, sizeof(ulong)); } public float GetFloat(int index) { int i = (int)ReadLittleEndian(index, sizeof(float)); inthelper[0] = i; Buffer.BlockCopy(inthelper, 0, floathelper, 0, sizeof(float)); return floathelper[0]; } public double GetDouble(int index) { ulong i = ReadLittleEndian(index, sizeof(double)); // There's Int64BitsToDouble but it uses unsafe code internally. ulonghelper[0] = i; Buffer.BlockCopy(ulonghelper, 0, doublehelper, 0, sizeof(double)); return doublehelper[0]; } #endif // UNSAFE_BYTEBUFFER /// <summary> /// Copies an array of type T into this buffer, ending at the given /// offset into this buffer. The starting offset is calculated based on the length /// of the array and is the value returned. /// </summary> /// <typeparam name="T">The type of the input data (must be a struct)</typeparam> /// <param name="offset">The offset into this buffer where the copy will end</param> /// <param name="x">The array to copy data from</param> /// <returns>The 'start' location of this buffer now, after the copy completed</returns> public int Put<T>(int offset, T[] x) where T : struct { if (x == null) { throw new ArgumentNullException("Cannot put a null array"); } if (x.Length == 0) { throw new ArgumentException("Cannot put an empty array"); } if (!IsSupportedType<T>()) { throw new ArgumentException("Cannot put an array of type " + typeof(T) + " into this buffer"); } if (BitConverter.IsLittleEndian) { int numBytes = ByteBuffer.ArraySize(x); offset -= numBytes; AssertOffsetAndLength(offset, numBytes); // if we are LE, just do a block copy #if ENABLE_SPAN_T MemoryMarshal.Cast<T, byte>(x).CopyTo(_buffer.Span.Slice(offset, numBytes)); #else Buffer.BlockCopy(x, 0, _buffer.Buffer, offset, numBytes); #endif } else { throw new NotImplementedException("Big Endian Support not implemented yet " + "for putting typed arrays"); // if we are BE, we have to swap each element by itself //for(int i = x.Length - 1; i >= 0; i--) //{ // todo: low priority, but need to genericize the Put<T>() functions //} } return offset; } #if ENABLE_SPAN_T public int Put<T>(int offset, Span<T> x) where T : struct { if (x.Length == 0) { throw new ArgumentException("Cannot put an empty array"); } if (!IsSupportedType<T>()) { throw new ArgumentException("Cannot put an array of type " + typeof(T) + " into this buffer"); } if (BitConverter.IsLittleEndian) { int numBytes = ByteBuffer.ArraySize(x); offset -= numBytes; AssertOffsetAndLength(offset, numBytes); // if we are LE, just do a block copy MemoryMarshal.Cast<T, byte>(x).CopyTo(_buffer.Span.Slice(offset, numBytes)); } else { throw new NotImplementedException("Big Endian Support not implemented yet " + "for putting typed arrays"); // if we are BE, we have to swap each element by itself //for(int i = x.Length - 1; i >= 0; i--) //{ // todo: low priority, but need to genericize the Put<T>() functions //} } return offset; } #endif } }
using System; using Csla; using SelfLoadSoftDelete.DataAccess; using SelfLoadSoftDelete.DataAccess.ERLevel; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G12_CityRoad (editable child object).<br/> /// This is a generated base class of <see cref="G12_CityRoad"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="G11_CityRoadColl"/> collection. /// </remarks> [Serializable] public partial class G12_CityRoad : BusinessBase<G12_CityRoad> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="CityRoad_ID"/> property. /// </summary> public static readonly PropertyInfo<int> CityRoad_IDProperty = RegisterProperty<int>(p => p.CityRoad_ID, "CityRoads ID"); /// <summary> /// Gets the CityRoads ID. /// </summary> /// <value>The CityRoads ID.</value> public int CityRoad_ID { get { return GetProperty(CityRoad_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="CityRoad_Name"/> property. /// </summary> public static readonly PropertyInfo<string> CityRoad_NameProperty = RegisterProperty<string>(p => p.CityRoad_Name, "CityRoads Name"); /// <summary> /// Gets or sets the CityRoads Name. /// </summary> /// <value>The CityRoads Name.</value> public string CityRoad_Name { get { return GetProperty(CityRoad_NameProperty); } set { SetProperty(CityRoad_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G12_CityRoad"/> object. /// </summary> /// <returns>A reference to the created <see cref="G12_CityRoad"/> object.</returns> internal static G12_CityRoad NewG12_CityRoad() { return DataPortal.CreateChild<G12_CityRoad>(); } /// <summary> /// Factory method. Loads a <see cref="G12_CityRoad"/> object from the given G12_CityRoadDto. /// </summary> /// <param name="data">The <see cref="G12_CityRoadDto"/>.</param> /// <returns>A reference to the fetched <see cref="G12_CityRoad"/> object.</returns> internal static G12_CityRoad GetG12_CityRoad(G12_CityRoadDto data) { G12_CityRoad obj = new G12_CityRoad(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G12_CityRoad"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public G12_CityRoad() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="G12_CityRoad"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(CityRoad_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G12_CityRoad"/> object from the given <see cref="G12_CityRoadDto"/>. /// </summary> /// <param name="data">The G12_CityRoadDto to use.</param> private void Fetch(G12_CityRoadDto data) { // Value properties LoadProperty(CityRoad_IDProperty, data.CityRoad_ID); LoadProperty(CityRoad_NameProperty, data.CityRoad_Name); var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="G12_CityRoad"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G10_City parent) { var dto = new G12_CityRoadDto(); dto.Parent_City_ID = parent.City_ID; dto.CityRoad_Name = CityRoad_Name; using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IG12_CityRoadDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); LoadProperty(CityRoad_IDProperty, resultDto.CityRoad_ID); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="G12_CityRoad"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; var dto = new G12_CityRoadDto(); dto.CityRoad_ID = CityRoad_ID; dto.CityRoad_Name = CityRoad_Name; using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IG12_CityRoadDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="G12_CityRoad"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IG12_CityRoadDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(CityRoad_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.Asn1; using System.Security.Cryptography.Pkcs.Asn1; using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.Xml; using Internal.Cryptography; namespace System.Security.Cryptography.Pkcs { public sealed class SignerInfo { public int Version { get; } public SubjectIdentifier SignerIdentifier { get; } private readonly Oid _digestAlgorithm; private readonly AttributeAsn[] _signedAttributes; private readonly Oid _signatureAlgorithm; private readonly ReadOnlyMemory<byte>? _signatureAlgorithmParameters; private readonly ReadOnlyMemory<byte> _signature; private readonly AttributeAsn[] _unsignedAttributes; private readonly SignedCms _document; private X509Certificate2 _signerCertificate; private SignerInfo _parentSignerInfo; private CryptographicAttributeObjectCollection _parsedSignedAttrs; private CryptographicAttributeObjectCollection _parsedUnsignedAttrs; internal SignerInfo(ref SignerInfoAsn parsedData, SignedCms ownerDocument) { Version = parsedData.Version; SignerIdentifier = new SubjectIdentifier(parsedData.Sid); _digestAlgorithm = parsedData.DigestAlgorithm.Algorithm; _signedAttributes = parsedData.SignedAttributes; _signatureAlgorithm = parsedData.SignatureAlgorithm.Algorithm; _signatureAlgorithmParameters = parsedData.SignatureAlgorithm.Parameters; _signature = parsedData.SignatureValue; _unsignedAttributes = parsedData.UnsignedAttributes; _document = ownerDocument; } public CryptographicAttributeObjectCollection SignedAttributes { get { if (_parsedSignedAttrs == null) { _parsedSignedAttrs = MakeAttributeCollection(_signedAttributes); } return _parsedSignedAttrs; } } public CryptographicAttributeObjectCollection UnsignedAttributes { get { if (_parsedUnsignedAttrs == null) { _parsedUnsignedAttrs = MakeAttributeCollection(_unsignedAttributes); } return _parsedUnsignedAttrs; } } public byte[] GetSignature() => _signature.ToArray(); public X509Certificate2 Certificate { get { if (_signerCertificate == null) { _signerCertificate = FindSignerCertificate(); } return _signerCertificate; } } public SignerInfoCollection CounterSignerInfos { get { // We only support one level of counter signing. if (_parentSignerInfo != null || _unsignedAttributes == null || _unsignedAttributes.Length == 0) { return new SignerInfoCollection(); } return GetCounterSigners(_unsignedAttributes); } } public Oid DigestAlgorithm => new Oid(_digestAlgorithm); public Oid SignatureAlgorithm => new Oid(_signatureAlgorithm); private SignerInfoCollection GetCounterSigners(AttributeAsn[] unsignedAttrs) { // Since each "attribute" can have multiple "attribute values" there's no real // correlation to a predictive size here. List<SignerInfo> signerInfos = new List<SignerInfo>(); foreach (AttributeAsn attributeAsn in unsignedAttrs) { if (attributeAsn.AttrType.Value == Oids.CounterSigner) { AsnReader reader = new AsnReader(attributeAsn.AttrValues, AsnEncodingRules.BER); AsnReader collReader = reader.ReadSetOf(); if (reader.HasData) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } while (collReader.HasData) { SignerInfoAsn parsedData = AsnSerializer.Deserialize<SignerInfoAsn>(collReader.GetEncodedValue(), AsnEncodingRules.BER); SignerInfo signerInfo = new SignerInfo(ref parsedData, _document) { _parentSignerInfo = this }; signerInfos.Add(signerInfo); } } } return new SignerInfoCollection(signerInfos.ToArray()); } public void ComputeCounterSignature() { throw new PlatformNotSupportedException(SR.Cryptography_Cms_NoSignerCert); } public void ComputeCounterSignature(CmsSigner signer) { if (_parentSignerInfo != null) throw new CryptographicException(SR.Cryptography_Cms_NoCounterCounterSigner); if (signer == null) throw new ArgumentNullException(nameof(signer)); signer.CheckCertificateValue(); int myIdx = _document.SignerInfos.FindIndexForSigner(this); if (myIdx < 0) { throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound); } // Make sure that we're using the most up-to-date version of this that we can. SignerInfo effectiveThis = _document.SignerInfos[myIdx]; X509Certificate2Collection chain; SignerInfoAsn newSignerInfo = signer.Sign(effectiveThis._signature, null, false, out chain); AttributeAsn newUnsignedAttr; using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { writer.PushSetOf(); AsnSerializer.Serialize(newSignerInfo, writer); writer.PopSetOf(); newUnsignedAttr = new AttributeAsn { AttrType = new Oid(Oids.CounterSigner, Oids.CounterSigner), AttrValues = writer.Encode(), }; } ref SignedDataAsn signedData = ref _document.GetRawData(); ref SignerInfoAsn mySigner = ref signedData.SignerInfos[myIdx]; int newExtensionIdx; if (mySigner.UnsignedAttributes == null) { mySigner.UnsignedAttributes = new AttributeAsn[1]; newExtensionIdx = 0; } else { newExtensionIdx = mySigner.UnsignedAttributes.Length; Array.Resize(ref mySigner.UnsignedAttributes, newExtensionIdx + 1); } mySigner.UnsignedAttributes[newExtensionIdx] = newUnsignedAttr; _document.UpdateCertificatesFromAddition(chain); // Re-normalize the document _document.Reencode(); } public void RemoveCounterSignature(int index) { if (index < 0) { // In NetFx RemoveCounterSignature doesn't bounds check, but the helper it calls does. // In the helper the argument is called "childIndex". throw new ArgumentOutOfRangeException("childIndex"); } // The SignerInfo class is a projection of data contained within the SignedCms. // The projection is applied at construction time, and is not live. // So RemoveCounterSignature modifies _document, not this. // (Because that's what NetFx does) int myIdx = _document.SignerInfos.FindIndexForSigner(this); // We've been removed. if (myIdx < 0) { throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound); } ref SignedDataAsn parentData = ref _document.GetRawData(); ref SignerInfoAsn myData = ref parentData.SignerInfos[myIdx]; if (myData.UnsignedAttributes == null) { throw new CryptographicException(SR.Cryptography_Cms_NoSignerAtIndex); } int removeAttrIdx = -1; int removeValueIndex = -1; bool removeWholeAttr = false; int csIndex = 0; AttributeAsn[] unsignedAttrs = myData.UnsignedAttributes; for (var i = 0; i < unsignedAttrs.Length; i++) { AttributeAsn attributeAsn = unsignedAttrs[i]; if (attributeAsn.AttrType.Value == Oids.CounterSigner) { AsnReader reader = new AsnReader(attributeAsn.AttrValues, AsnEncodingRules.BER); AsnReader collReader = reader.ReadSetOf(); if (reader.HasData) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } int j = 0; while (collReader.HasData) { collReader.GetEncodedValue(); if (csIndex == index) { removeAttrIdx = i; removeValueIndex = j; } csIndex++; j++; } if (removeValueIndex == 0 && j == 1) { removeWholeAttr = true; } if (removeAttrIdx >= 0) { break; } } } if (removeAttrIdx < 0) { throw new CryptographicException(SR.Cryptography_Cms_NoSignerAtIndex); } // The easy path: if (removeWholeAttr) { // Empty needs to normalize to null. if (unsignedAttrs.Length == 1) { myData.UnsignedAttributes = null; } else { Helpers.RemoveAt(ref myData.UnsignedAttributes, removeAttrIdx); } } else { ref AttributeAsn modifiedAttr = ref unsignedAttrs[removeAttrIdx]; using (AsnWriter writer = new AsnWriter(AsnEncodingRules.BER)) { writer.PushSetOf(); AsnReader reader = new AsnReader(modifiedAttr.AttrValues, writer.RuleSet); int i = 0; while (reader.HasData) { ReadOnlyMemory<byte> encodedValue = reader.GetEncodedValue(); if (i != removeValueIndex) { writer.WriteEncodedValue(encodedValue); } i++; } writer.PopSetOf(); modifiedAttr.AttrValues = writer.Encode(); } } } public void RemoveCounterSignature(SignerInfo counterSignerInfo) { if (counterSignerInfo == null) throw new ArgumentNullException(nameof(counterSignerInfo)); SignerInfoCollection docSigners = _document.SignerInfos; int index = docSigners.FindIndexForSigner(this); if (index < 0) { throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound); } SignerInfo liveThis = docSigners[index]; index = liveThis.CounterSignerInfos.FindIndexForSigner(counterSignerInfo); if (index < 0) { throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound); } RemoveCounterSignature(index); } public void CheckSignature(bool verifySignatureOnly) => CheckSignature(new X509Certificate2Collection(), verifySignatureOnly); public void CheckSignature(X509Certificate2Collection extraStore, bool verifySignatureOnly) { if (extraStore == null) throw new ArgumentNullException(nameof(extraStore)); X509Certificate2 certificate = Certificate; if (certificate == null) { certificate = FindSignerCertificate(SignerIdentifier, extraStore); if (certificate == null) { throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound); } } Verify(extraStore, certificate, verifySignatureOnly); } public void CheckHash() { IncrementalHash hasher = PrepareDigest(); byte[] expectedSignature = hasher.GetHashAndReset(); if (!_signature.Span.SequenceEqual(expectedSignature)) { throw new CryptographicException(SR.Cryptography_BadSignature); } } private X509Certificate2 FindSignerCertificate() { return FindSignerCertificate(SignerIdentifier, _document.Certificates); } private static X509Certificate2 FindSignerCertificate( SubjectIdentifier signerIdentifier, X509Certificate2Collection extraStore) { if (extraStore == null || extraStore.Count == 0) { return null; } X509Certificate2Collection filtered = null; X509Certificate2 match = null; switch (signerIdentifier.Type) { case SubjectIdentifierType.IssuerAndSerialNumber: { X509IssuerSerial issuerSerial = (X509IssuerSerial)signerIdentifier.Value; filtered = extraStore.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false); foreach (X509Certificate2 cert in filtered) { if (cert.IssuerName.Name == issuerSerial.IssuerName) { match = cert; break; } } break; } case SubjectIdentifierType.SubjectKeyIdentifier: { filtered = extraStore.Find(X509FindType.FindBySubjectKeyIdentifier, signerIdentifier.Value, false); if (filtered.Count > 0) { match = filtered[0]; } break; } } if (filtered != null) { foreach (X509Certificate2 cert in filtered) { if (!ReferenceEquals(cert, match)) { cert.Dispose(); } } } return match; } private IncrementalHash PrepareDigest() { HashAlgorithmName hashAlgorithmName = GetDigestAlgorithm(); IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithmName); if (_parentSignerInfo == null) { // Windows compatibility: If a document was loaded in detached mode, // but had content, hash both parts of the content. if (_document.Detached) { ref SignedDataAsn documentData = ref _document.GetRawData(); ReadOnlyMemory<byte>? embeddedContent = documentData.EncapContentInfo.Content; if (embeddedContent != null) { hasher.AppendData(embeddedContent.Value.Span); } } hasher.AppendData(_document.GetContentSpan()); } else { hasher.AppendData(_parentSignerInfo._signature.Span); } // A Counter-Signer always requires signed attributes. // If any signed attributes are present, message-digest is required. bool invalid = _parentSignerInfo != null || _signedAttributes != null; if (_signedAttributes != null) { byte[] contentDigest = hasher.GetHashAndReset(); using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { writer.PushSetOf(); foreach (AttributeAsn attr in _signedAttributes) { AsnSerializer.Serialize(attr, writer); // .NET Framework doesn't seem to validate the content type attribute, // so we won't, either. if (attr.AttrType.Value == Oids.MessageDigest) { CryptographicAttributeObject obj = MakeAttribute(attr); if (obj.Values.Count != 1) { throw new CryptographicException(SR.Cryptography_BadHashValue); } var digestAttr = (Pkcs9MessageDigest)obj.Values[0]; if (!contentDigest.AsSpan().SequenceEqual(digestAttr.MessageDigest.AsReadOnlySpan())) { throw new CryptographicException(SR.Cryptography_BadHashValue); } invalid = false; } } writer.PopSetOf(); Helpers.DigestWriter(hasher, writer); } } if (invalid) { throw new CryptographicException(SR.Cryptography_Cms_MissingAuthenticatedAttribute); } return hasher; } private void Verify( X509Certificate2Collection extraStore, X509Certificate2 certificate, bool verifySignatureOnly) { IncrementalHash hasher = PrepareDigest(); CmsSignature signatureProcessor = CmsSignature.Resolve(SignatureAlgorithm.Value); if (signatureProcessor == null) { throw new CryptographicException(SR.Cryptography_Cms_UnknownAlgorithm, SignatureAlgorithm.Value); } #if netcoreapp // SHA-2-512 is the biggest digest type we know about. Span<byte> digestValue = stackalloc byte[512 / 8]; ReadOnlySpan<byte> digest = digestValue; ReadOnlyMemory<byte> signature = _signature; if (hasher.TryGetHashAndReset(digestValue, out int bytesWritten)) { digest = digestValue.Slice(0, bytesWritten); } else { digest = hasher.GetHashAndReset(); } #else byte[] digest = hasher.GetHashAndReset(); byte[] signature = _signature.ToArray(); #endif bool signatureValid = signatureProcessor.VerifySignature( digest, signature, DigestAlgorithm.Value, hasher.AlgorithmName, _signatureAlgorithmParameters, certificate); if (!signatureValid) { throw new CryptographicException(SR.Cryptography_BadSignature); } if (!verifySignatureOnly) { X509Chain chain = new X509Chain(); chain.ChainPolicy.ExtraStore.AddRange(extraStore); chain.ChainPolicy.RevocationMode = X509RevocationMode.Online; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; if (!chain.Build(certificate)) { X509ChainStatus status = chain.ChainStatus.FirstOrDefault(); throw new CryptographicException(SR.Cryptography_Cms_TrustFailure, status.StatusInformation); } // NetFx checks for either of these const X509KeyUsageFlags SufficientFlags = X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.NonRepudiation; foreach (X509Extension ext in certificate.Extensions) { if (ext.Oid.Value == Oids.KeyUsage) { if (!(ext is X509KeyUsageExtension keyUsage)) { keyUsage = new X509KeyUsageExtension(); keyUsage.CopyFrom(ext); } if ((keyUsage.KeyUsages & SufficientFlags) == 0) { throw new CryptographicException(SR.Cryptography_Cms_WrongKeyUsage); } } } } } private HashAlgorithmName GetDigestAlgorithm() { return Helpers.GetDigestAlgorithm(DigestAlgorithm.Value); } private static CryptographicAttributeObjectCollection MakeAttributeCollection(AttributeAsn[] attributes) { var coll = new CryptographicAttributeObjectCollection(); if (attributes == null) return coll; foreach (AttributeAsn attribute in attributes) { coll.AddWithoutMerge(MakeAttribute(attribute)); } return coll; } private static CryptographicAttributeObject MakeAttribute(AttributeAsn attribute) { Oid type = new Oid(attribute.AttrType); ReadOnlyMemory<byte> attrSetBytes = attribute.AttrValues; AsnReader reader = new AsnReader(attrSetBytes, AsnEncodingRules.BER); AsnReader collReader = reader.ReadSetOf(); if (reader.HasData) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } AsnEncodedDataCollection valueColl = new AsnEncodedDataCollection(); while (collReader.HasData) { byte[] attrBytes = collReader.GetEncodedValue().ToArray(); valueColl.Add(Helpers.CreateBestPkcs9AttributeObjectAvailable(type, attrBytes)); } return new CryptographicAttributeObject(type, valueColl); } } }
using System; using System.IO; using System.Linq; using System.Collections.Generic; using MooGet; using NUnit.Framework; namespace MooGet.Specs { [TestFixture] public class DependenciesSpec : MooGetSpec { static List<LocalPackage> packages = LocalPackage.FromDirectory(PathToContent("unpacked_packages")); static List<RemotePackage> morePackages = new OldSource(PathToContent("example-feed.xml")).AllPackages; Package PackageWithDependencies(params string[] dependencyStrings) { return NamedPackageWithDependencies("MyPackage", dependencyStrings); } Package NamedPackageWithDependencies(string name, params string[] dependencyStrings) { var nameParts = name.Split(' '); var package = (nameParts.Length == 2) ? new Package { Id = nameParts[0], VersionText = nameParts[1] } : new Package { Id = nameParts[0], VersionText = "1.0" }; foreach (var dependencyString in dependencyStrings) package.Dependencies.Add(new PackageDependency(dependencyString)); return package; } [TearDown] public void Before() { Feed.Domain = "mooget.net"; // reset to default } [Test] public void can_return_dependencies_for_a_package_with_no_dependencies() { var antiXss = packages.First(pkg => pkg.Id == "AntiXSS"); // this package's defined dependencies antiXss.Dependencies.Should(Be.Empty); // all dependencies for this package (requires access to other packages to figure this out) // this returns RemotePackages that we can install. antiXss.FindDependencies(morePackages).Should(Be.Empty); } [Test] public void can_return_dependencies_for_a_package_with_1_dependency_with_no_subdependencies() { var castleCore = packages.First(pkg => pkg.IdAndVersion == "Castle.Core-1.1.0"); // this package's defined dependencies castleCore.Dependencies.Count.ShouldEqual(1); castleCore.Dependencies.First().Id.ShouldEqual("log4net"); // all dependencies for this package (requires access to other packages to figure this out) var found = castleCore.FindDependencies(morePackages); found.Count.ShouldEqual(1); found.First().IdAndVersion.ShouldEqual("log4net-1.2.10"); } [Test][Ignore] public void can_return_all_PackageDependency_for_a_package_with_1_dependency_with_subdependencies_that_have_subdependencies() { var castleCore = morePackages.First(pkg => pkg.IdAndVersion == "NHibernate.Core-2.1.2.4000"); var dependencies = castleCore.FindPackageDependencies(morePackages); dependencies.Count.ShouldEqual(12345); // ?? need to implement this later ... ? } [Test][Ignore] public void can_get_all_PackageDependency_for_a_list_of_packages_that_each_have_lots_of_subdependencies() { } [Test] public void can_return_dependencies_for_a_package_with_1_dependency_with_subdependencies_that_have_subdependencies() { var castleCore = morePackages.First(pkg => pkg.IdAndVersion == "NHibernate.Core-2.1.2.4000"); // this package's defined dependencies castleCore.Dependencies.Count.ShouldEqual(4); castleCore.Dependencies.Select(d => d.ToString()).ShouldContain("log4net = 1.2.10"); castleCore.Dependencies.Select(d => d.ToString()).ShouldContain("Iesi.Collections = 1.0.1"); castleCore.Dependencies.Select(d => d.ToString()).ShouldContain("Antlr = 3.1.1"); castleCore.Dependencies.Select(d => d.ToString()).ShouldContain("Castle.DynamicProxy = 2.1.0"); // all dependencies for this package (requires access to other packages to figure this out) var found = castleCore.FindDependencies(morePackages); found.Count.ShouldEqual(5); found.Select(p => p.IdAndVersion).ShouldContain("log4net-1.2.10"); found.Select(p => p.IdAndVersion).ShouldContain("Iesi.Collections-1.0.1"); found.Select(p => p.IdAndVersion).ShouldContain("Antlr-3.1.1"); found.Select(p => p.IdAndVersion).ShouldContain("Castle.DynamicProxy-2.1.0"); found.Select(p => p.IdAndVersion).ShouldContain("Castle.Core-1.1.0"); } [Test][Ignore] public void can_return_latest_matching_dependencies_from_2_packages() { } [Test][Ignore] public void exception_is_raised_if_conflicting_dependencies_are_found() { } [Test][Ignore] public void exception_is_raised_if_not_all_dependencies_are_found() { } [Test] public void can_return_dependencies_for_package_that_has_dependencies_which_have_subdependencies_which_have_subdependencies() { /* * Package overview. * * Package1 * P1Sub * P1SubSub1 * P1SubSub2 * P1SubSubSub * * Package2 * P2Sub1 * P2Sub2 * P2Sub3 = 1.0 * P2Sub3Sub * P2Sub3SubSub ~> 1.5 * P2Sub3SubSubSub * * P2Sub3SubSub 1.5.0, 1.5.9, 1.6.0, 2.0.0 * * P2Sub3 0.9 (no deps) * P2Sub3 1.0 (has the dependencies above) */ var packages = new List<Package>(); // TODO if we remove one of these, it could be a good example for a MISSING dependency packages.Add(NamedPackageWithDependencies("Package1", "P1Sub")); packages.Add(NamedPackageWithDependencies("P1Sub", "P1SubSub1", "P1SubSub2")); packages.Add(NamedPackageWithDependencies("P1SubSub1")); packages.Add(NamedPackageWithDependencies("P1SubSub2", "P1SubSubSub")); packages.Add(NamedPackageWithDependencies("P1SubSubSub")); packages.Add(NamedPackageWithDependencies("Package2", "P2Sub1", "P2Sub2", "P2Sub3 1.0")); packages.Add(NamedPackageWithDependencies("P2Sub1")); packages.Add(NamedPackageWithDependencies("P2Sub2")); packages.Add(NamedPackageWithDependencies("P2Sub3 0.9")); packages.Add(NamedPackageWithDependencies("P2Sub3 1.0", "P2Sub3Sub")); packages.Add(NamedPackageWithDependencies("P2Sub3Sub", "P2Sub3SubSub ~> 1.5")); packages.Add(NamedPackageWithDependencies("P2Sub3SubSub 1.5.0", "P2Sub3SubSubSub")); packages.Add(NamedPackageWithDependencies("P2Sub3SubSub 1.5.9", "P2Sub3SubSubSub")); packages.Add(NamedPackageWithDependencies("P2Sub3SubSub 1.6.0")); packages.Add(NamedPackageWithDependencies("P2Sub3SubSub 2.0.0")); packages.Add(NamedPackageWithDependencies("P2Sub3SubSubSub")); var source = OldSource.FromXml(Feed.GenerateFeed(packages)); var package1 = packages.First(p => p.Id == "Package1"); var package2 = packages.First(p => p.Id == "Package2"); // check that a few things are setup correctly ... source.AllPackages.First(p => p.Id == "P2Sub3Sub").Dependencies.First().ToString().ShouldEqual("P2Sub3SubSub ~> 1.5"); /* get Package1's dependencies * * Package1 * P1Sub * P1SubSub1 * P1SubSub2 * P1SubSubSub */ var found = package1.FindDependencies(source.AllPackages); found.Count.ShouldEqual(4); found.Select(p => p.Id).ShouldContain("P1Sub"); found.Select(p => p.Id).ShouldContain("P1SubSub1"); found.Select(p => p.Id).ShouldContain("P1SubSub2"); found.Select(p => p.Id).ShouldContain("P1SubSubSub"); // get Package2's dependencies /* * Package2 * P2Sub1 * P2Sub2 * P2Sub3 = 1.0 * P2Sub3Sub * P2Sub3SubSub ~> 1.5 * P2Sub3SubSubSub */ found = package2.FindDependencies(source.AllPackages); found.Count.ShouldEqual(6); found.Select(p => p.IdAndVersion).ShouldContain("P2Sub1-1.0"); found.Select(p => p.IdAndVersion).ShouldContain("P2Sub2-1.0"); found.Select(p => p.IdAndVersion).ShouldContain("P2Sub3-1.0"); found.Select(p => p.IdAndVersion).ShouldContain("P2Sub3Sub-1.0"); found.Select(p => p.IdAndVersion).ShouldContain("P2Sub3SubSub-1.5.9"); found.Select(p => p.IdAndVersion).ShouldContain("P2Sub3SubSubSub-1.0"); // get Package1 and Package2's dependencies found = Package.FindDependencies(new Package[] { package1, package2 }, source.AllPackages); found.Count.ShouldEqual(10); found.Select(p => p.Id).ShouldContain("P1Sub"); found.Select(p => p.Id).ShouldContain("P1SubSub1"); found.Select(p => p.Id).ShouldContain("P1SubSub2"); found.Select(p => p.Id).ShouldContain("P1SubSubSub"); found.Select(p => p.IdAndVersion).ShouldContain("P2Sub1-1.0"); found.Select(p => p.IdAndVersion).ShouldContain("P2Sub2-1.0"); found.Select(p => p.IdAndVersion).ShouldContain("P2Sub3-1.0"); found.Select(p => p.IdAndVersion).ShouldContain("P2Sub3Sub-1.0"); found.Select(p => p.IdAndVersion).ShouldContain("P2Sub3SubSub-1.5.9"); found.Select(p => p.IdAndVersion).ShouldContain("P2Sub3SubSubSub-1.0"); // while we have all of this loaded up, let's test missing dependencies ... // let's remove P2Sub3SubSub 1.5.* so P2Sub3SubSub ~> 1.5 fails packages.Where(p => p.IdAndVersion.StartsWith("P2Sub3SubSub-1.5.")).ToList().ForEach(p => packages.Remove(p)); source = OldSource.FromXml(Feed.GenerateFeed(packages)); Console.WriteLine("---------------- LOOKING FOR MISSING ---------------"); try { Package.FindDependencies(new Package[] { package1, package2 }, source.AllPackages); Assert.Fail("Expected MissingDependencyException to be thrown"); } catch (MooGet.MissingDependencyException ex) { ex.Dependencies.Count.ShouldEqual(1); ex.Dependencies.First().ToString().ShouldEqual("P2Sub3SubSub ~> 1.5"); } } [Test] public void can_return_latest_matching_dependencies_from_2_sources_with_a_package_that_has_overlapping_dependencies() { // our package depends on HelloWorld and FooBar ~> 1.5. var myPackage = PackageWithDependencies("HelloWorld", "FooBar ~> 1.5"); // HelloWorld depends on FooBar var helloWorld = new Package { Id = "HelloWorld", VersionText = "1.0" }; helloWorld.Dependencies.Add(new PackageDependency("FooBar")); // source1 has versions 1.0, 1.5.0, 1.5.2, and 2.0 of FooBar and it has HelloWorld, which also depends on FooBar var source1Packages = new List<Package>(); new List<string> { "1.0", "1.5.0", "1.5.2", "2.0" }.ForEach(version => source1Packages.Add(new Package { Id = "FooBar", VersionText = version })); source1Packages.Add(helloWorld); Feed.Domain = "source1.com"; var source1 = OldSource.FromXml(Feed.GenerateFeed(source1Packages)); // source2 has versions 1.5.1, 1.5.2, 1.5.3, 1.6, 1.9.0, 2.0, and 2.0.1 of FooBar var source2Packages = new List<Package>(); new List<string> { "1.5.1", "1.5.2", "1.5.3", "1.6", "1.9.0", "2.0", "2.0.1" }.ForEach(version => source2Packages.Add(new Package { Id = "FooBar", VersionText = version })); Feed.Domain = "source2.net"; var source2 = OldSource.FromXml(Feed.GenerateFeed(source2Packages)); // By itself, HelloWorld would find the *latest* version of FooBar to use var found = helloWorld.FindDependencies(source1.AllPackages, source2.AllPackages); found.Count.ShouldEqual(1); found.First().DownloadUrl.ShouldEqual("http://source2.net/packages/download?p=FooBar-2.0.1.nupkg"); // When combined with our package, the latest ~> 1.5 version of FooBar is used (to meet ALL dependencies) found = Package.FindDependencies(new Package[] { helloWorld, myPackage }, source1.AllPackages, source2.AllPackages); found.Count.ShouldEqual(1); found.First().DownloadUrl.ShouldEqual("http://source2.net/packages/download?p=FooBar-1.5.3.nupkg"); // Just to be sure, if we re-arrange the order of the packages, it should give us the same results found = Package.FindDependencies(new Package[] { myPackage, helloWorld }, source1.AllPackages, source2.AllPackages); found.Count.ShouldEqual(1); found.First().DownloadUrl.ShouldEqual("http://source2.net/packages/download?p=FooBar-1.5.3.nupkg"); // If there are duplicate packages, we end up with the same results found = Package.FindDependencies(new Package[] { myPackage, helloWorld, myPackage, helloWorld }, source1.AllPackages, source2.AllPackages); found.Count.ShouldEqual(1); found.First().DownloadUrl.ShouldEqual("http://source2.net/packages/download?p=FooBar-1.5.3.nupkg"); } [Test] public void can_return_latest_matching_dependencies_from_2_sources() { // source1 has versions 1.0, 1.5.0, 1.5.2, and 2.0 of FooBar var source1Packages = new List<Package>(); new List<string> { "1.0", "1.5.0", "1.5.2", "2.0" }.ForEach(version => source1Packages.Add(new Package { Id = "FooBar", VersionText = version })); Feed.Domain = "source1.com"; var source1 = OldSource.FromXml(Feed.GenerateFeed(source1Packages)); // source2 has versions 1.5.1, 1.5.2, 1.5.3, 1.6, 1.9.0, 2.0, and 2.0.1 of FooBar var source2Packages = new List<Package>(); new List<string> { "1.5.1", "1.5.2", "1.5.3", "1.6", "1.9.0", "2.0", "2.0.1" }.ForEach(version => source2Packages.Add(new Package { Id = "FooBar", VersionText = version })); Feed.Domain = "source2.net"; var source2 = OldSource.FromXml(Feed.GenerateFeed(source2Packages)); // let's try getting FooBar = 1.6 var found = PackageWithDependencies("FooBar = 1.6").FindDependencies(source1.AllPackages, source2.AllPackages); found.Count.ShouldEqual(1); found.First().DownloadUrl.ShouldEqual("http://source2.net/packages/download?p=FooBar-1.6.nupkg"); // if no version is specified, get the latest found = PackageWithDependencies("FooBar").FindDependencies(source1.AllPackages, source2.AllPackages); found.Count.ShouldEqual(1); found.First().DownloadUrl.ShouldEqual("http://source2.net/packages/download?p=FooBar-2.0.1.nupkg"); // let's try getting FooBar ~> 1.5.0 found = PackageWithDependencies("FooBar ~> 1.5.0").FindDependencies(source1.AllPackages, source2.AllPackages); found.Count.ShouldEqual(1); found.First().DownloadUrl.ShouldEqual("http://source2.net/packages/download?p=FooBar-1.5.3.nupkg"); // let's try getting FooBar > 1.5.2 found = PackageWithDependencies("FooBar > 1.5.2").FindDependencies(source1.AllPackages, source2.AllPackages); found.Count.ShouldEqual(1); found.First().DownloadUrl.ShouldEqual("http://source2.net/packages/download?p=FooBar-2.0.1.nupkg"); // let's try getting FooBar >= 1.5.2 found = PackageWithDependencies("FooBar >= 1.5.2").FindDependencies(source1.AllPackages, source2.AllPackages); found.Count.ShouldEqual(1); found.First().DownloadUrl.ShouldEqual("http://source2.net/packages/download?p=FooBar-2.0.1.nupkg"); // let's try getting FooBar > 1.5.9 < 2.0 found = PackageWithDependencies("FooBar > 1.5.9 < 2.0").FindDependencies(source1.AllPackages, source2.AllPackages); found.Count.ShouldEqual(1); found.First().DownloadUrl.ShouldEqual("http://source2.net/packages/download?p=FooBar-1.9.0.nupkg"); // let's try getting FooBar < 2.0 found = PackageWithDependencies("FooBar < 2.0").FindDependencies(source1.AllPackages, source2.AllPackages); found.Count.ShouldEqual(1); found.First().DownloadUrl.ShouldEqual("http://source2.net/packages/download?p=FooBar-1.9.0.nupkg"); // let's try getting FooBar <= 2.0 found = PackageWithDependencies("FooBar <= 2.0").FindDependencies(source1.AllPackages, source2.AllPackages); found.Count.ShouldEqual(1); found.First().DownloadUrl.ShouldEqual("http://source1.com/packages/download?p=FooBar-2.0.nupkg"); // let's try <= 2.0 but reverse the order that we provide the sources, so source2 gets priority found = PackageWithDependencies("FooBar <= 2.0").FindDependencies(source2.AllPackages, source1.AllPackages); found.Count.ShouldEqual(1); found.First().DownloadUrl.ShouldEqual("http://source2.net/packages/download?p=FooBar-2.0.nupkg"); } [Test][Ignore] public void can_return_ALL_possible_packages_that_could_be_used_to_resolve_dependencies() { } [Test][Ignore] public void an_exception_with_information_about_ALL_dependent_packages_that_could_not_be_found() { } [Test][Ignore] public void can_return_dependencies_for_a_package_with_no_2_dependencies_with_no_subdependencies() { } [Test][Ignore] public void can_return_dependencies_for_a_package_with_no_1_dependency_with_subdependencies() { } [Test][Ignore] public void can_return_dependencies_for_a_package_with_no_1_dependency_with_subdependencies_and_one_without() { } } }
using System; using System.Diagnostics; using System.Text; using Bitmask = System.UInt64; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2009 November 25 ** ** 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 code used to insert the values of host parameters ** (aka "wildcards") into the SQL text output by sqlite3_trace(). ************************************************************************* ** 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: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ //#include "sqliteInt.h" //#include "vdbeInt.h" #if !SQLITE_OMIT_TRACE /* ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of ** bytes in this text up to but excluding the first character in ** a host parameter. If the text contains no host parameters, return ** the total number of bytes in the text. */ static int findNextHostParameter( string zSql, int iOffset, ref int pnToken ) { int tokenType = 0; int nTotal = 0; int n; pnToken = 0; while ( iOffset < zSql.Length ) { n = sqlite3GetToken( zSql, iOffset, ref tokenType ); Debug.Assert( n > 0 && tokenType != TK_ILLEGAL ); if ( tokenType == TK_VARIABLE ) { pnToken = n; break; } nTotal += n; iOffset += n;// zSql += n; } return nTotal; } /* ** This function returns a pointer to a nul-terminated string in memory ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the ** string contains a copy of zRawSql but with host parameters expanded to ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1, ** then the returned string holds a copy of zRawSql with "-- " prepended ** to each line of text. ** ** The calling function is responsible for making sure the memory returned ** is eventually freed. ** ** ALGORITHM: Scan the input string looking for host parameters in any of ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within ** string literals, quoted identifier names, and comments. For text forms, ** the host parameter index is found by scanning the perpared ** statement for the corresponding OP_Variable opcode. Once the host ** parameter index is known, locate the value in p->aVar[]. Then render ** the value as a literal in place of the host parameter name. */ static string sqlite3VdbeExpandSql( Vdbe p, /* The prepared statement being evaluated */ string zRawSql /* Raw text of the SQL statement */ ) { sqlite3 db; /* The database connection */ int idx = 0; /* Index of a host parameter */ int nextIndex = 1; /* Index of next ? host parameter */ int n; /* Length of a token prefix */ int nToken = 0; /* Length of the parameter token */ int i; /* Loop counter */ Mem pVar; /* Value of a host parameter */ StrAccum _out = new StrAccum( 1000 ); /* Accumulate the _output here */ StringBuilder zBase = new StringBuilder( 100 ); /* Initial working space */ int izRawSql = 0; db = p.db; sqlite3StrAccumInit( _out, null, 100, db.aLimit[SQLITE_LIMIT_LENGTH] ); _out.db = db; if ( db.vdbeExecCnt > 1 ) { while ( izRawSql < zRawSql.Length ) { //string zStart = zRawSql; while ( zRawSql[izRawSql++] != '\n' && izRawSql < zRawSql.Length ) ; sqlite3StrAccumAppend( _out, "-- ", 3 ); sqlite3StrAccumAppend( _out, zRawSql, (int)izRawSql );//zRawSql - zStart ); } } else { while ( izRawSql < zRawSql.Length ) { n = findNextHostParameter( zRawSql, izRawSql, ref nToken ); Debug.Assert( n > 0 ); sqlite3StrAccumAppend( _out, zRawSql.Substring( izRawSql, n ), n ); izRawSql += n; Debug.Assert( izRawSql < zRawSql.Length || nToken == 0 ); if ( nToken == 0 ) break; if ( zRawSql[izRawSql] == '?' ) { if ( nToken > 1 ) { Debug.Assert( sqlite3Isdigit( zRawSql[izRawSql + 1] ) ); sqlite3GetInt32( zRawSql, izRawSql + 1, ref idx ); } else { idx = nextIndex; } } else { Debug.Assert( zRawSql[izRawSql] == ':' || zRawSql[izRawSql] == '$' || zRawSql[izRawSql] == '@' ); testcase( zRawSql[izRawSql] == ':' ); testcase( zRawSql[izRawSql] == '$' ); testcase( zRawSql[izRawSql] == '@' ); idx = sqlite3VdbeParameterIndex( p, zRawSql.Substring( izRawSql, nToken ), nToken ); Debug.Assert( idx > 0 ); } izRawSql += nToken; nextIndex = idx + 1; Debug.Assert( idx > 0 && idx <= p.nVar ); pVar = p.aVar[idx - 1]; if ( ( pVar.flags & MEM_Null ) != 0 ) { sqlite3StrAccumAppend( _out, "NULL", 4 ); } else if ( ( pVar.flags & MEM_Int ) != 0 ) { sqlite3XPrintf( _out, "%lld", pVar.u.i ); } else if ( ( pVar.flags & MEM_Real ) != 0 ) { sqlite3XPrintf( _out, "%!.15g", pVar.r ); } else if ( ( pVar.flags & MEM_Str ) != 0 ) { #if !SQLITE_OMIT_UTF16 u8 enc = ENC(db); if( enc!=SQLITE_UTF8 ){ Mem utf8; memset(&utf8, 0, sizeof(utf8)); utf8.db = db; sqlite3VdbeMemSetStr(&utf8, pVar.z, pVar.n, enc, SQLITE_STATIC); sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8); sqlite3XPrintf(_out, "'%.*q'", utf8.n, utf8.z); sqlite3VdbeMemRelease(&utf8); }else #endif { sqlite3XPrintf( _out, "'%.*q'", pVar.n, pVar.z ); } } else if ( ( pVar.flags & MEM_Zero ) != 0 ) { sqlite3XPrintf( _out, "zeroblob(%d)", pVar.u.nZero ); } else { Debug.Assert( ( pVar.flags & MEM_Blob ) != 0 ); sqlite3StrAccumAppend( _out, "x'", 2 ); for ( i = 0; i < pVar.n; i++ ) { sqlite3XPrintf( _out, "%02x", pVar.zBLOB[i] & 0xff ); } sqlite3StrAccumAppend( _out, "'", 1 ); } } } return sqlite3StrAccumFinish( _out ); } #endif //* #if !SQLITE_OMIT_TRACE */ } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Linq.Expressions; using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.Scripting; using Microsoft.Scripting.Ast; using Microsoft.Scripting.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; using IronPython.Runtime.Binding; namespace IronPython.Runtime { /// <summary> /// Python module. Stores classes, functions, and data. Usually a module /// is created by importing a file or package from disk. But a module can also /// be directly created by calling the module type and providing a name or /// optionally a documentation string. /// </summary> [PythonType("module"), DebuggerTypeProxy(typeof(PythonModule.DebugProxy)), DebuggerDisplay("module: {GetName()}")] public class PythonModule : IDynamicMetaObjectProvider, IPythonMembersList { private readonly PythonDictionary _dict; private Scope _scope; public PythonModule() { _dict = new PythonDictionary(); if (GetType() != typeof(PythonModule) && this is IPythonObject) { // we should share the user dict w/ our dict. ((IPythonObject)this).ReplaceDict(_dict); } } /// <summary> /// Creates a new module backed by a Scope. Used for creating modules for foreign Scope's. /// </summary> internal PythonModule(PythonContext context, Scope scope) { _dict = new PythonDictionary(new ScopeDictionaryStorage(context, scope)); _scope = scope; } /// <summary> /// Creates a new PythonModule with the specified dictionary. /// /// Used for creating modules for builtin modules which don't have any code associated with them. /// </summary> internal PythonModule(PythonDictionary dict) { _dict = dict; } public static PythonModule/*!*/ __new__(CodeContext/*!*/ context, PythonType/*!*/ cls, params object[]/*!*/ args\u00F8) { PythonModule res; if (cls == TypeCache.Module) { res = new PythonModule(); } else if (cls.IsSubclassOf(TypeCache.Module)) { res = (PythonModule)cls.CreateInstance(context); } else { throw PythonOps.TypeError("{0} is not a subtype of module", cls.Name); } return res; } [StaticExtensionMethod] public static PythonModule/*!*/ __new__(CodeContext/*!*/ context, PythonType/*!*/ cls, [ParamDictionary]IDictionary<object, object> kwDict0, params object[]/*!*/ args\u00F8) { return __new__(context, cls, args\u00F8); } public void __init__(string name) { __init__(name, null); } public void __init__(string name, string doc) { _dict["__name__"] = name; _dict["__doc__"] = doc; } public object __getattribute__(CodeContext/*!*/ context, string name) { PythonTypeSlot slot; object res; if (GetType() != typeof(PythonModule) && DynamicHelpers.GetPythonType(this).TryResolveMixedSlot(context, name, out slot) && slot.TryGetValue(context, this, DynamicHelpers.GetPythonType(this), out res)) { return res; } switch (name) { // never look in the dict for these... case "__dict__": return __dict__; case "__class__": return DynamicHelpers.GetPythonType(this); } if (_dict.TryGetValue(name, out res)) { return res; } // fall back to object to provide all of our other attributes (e.g. __setattr__, etc...) return ObjectOps.__getattribute__(context, this, name); } internal object GetAttributeNoThrow(CodeContext/*!*/ context, string name) { PythonTypeSlot slot; object res; if (GetType() != typeof(PythonModule) && DynamicHelpers.GetPythonType(this).TryResolveMixedSlot(context, name, out slot) && slot.TryGetValue(context, this, DynamicHelpers.GetPythonType(this), out res)) { return res; } switch (name) { // never look in the dict for these... case "__dict__": return __dict__; case "__class__": return DynamicHelpers.GetPythonType(this); } if (_dict.TryGetValue(name, out res)) { return res; } else if (DynamicHelpers.GetPythonType(this).TryGetNonCustomMember(context, this, name, out res)) { return res; } else if (DynamicHelpers.GetPythonType(this).TryResolveMixedSlot(context, "__getattr__", out slot) && slot.TryGetValue(context, this, DynamicHelpers.GetPythonType(this), out res)) { return PythonCalls.Call(context, res, name); } return OperationFailed.Value; } public void __setattr__(CodeContext/*!*/ context, string name, object value) { PythonTypeSlot slot; if (GetType() != typeof(PythonModule) && DynamicHelpers.GetPythonType(this).TryResolveMixedSlot(context, name, out slot) && slot.TrySetValue(context, this, DynamicHelpers.GetPythonType(this), value)) { return; } switch (name) { case "__dict__": throw PythonOps.TypeError("readonly attribute"); case "__class__": throw PythonOps.TypeError("__class__ assignment: only for heap types"); } Debug.Assert(value != Uninitialized.Instance); _dict[name] = value; } public void __delattr__(CodeContext/*!*/ context, string name) { PythonTypeSlot slot; if (GetType() != typeof(PythonModule) && DynamicHelpers.GetPythonType(this).TryResolveMixedSlot(context, name, out slot) && slot.TryDeleteValue(context, this, DynamicHelpers.GetPythonType(this))) { return; } switch (name) { case "__dict__": throw PythonOps.TypeError("readonly attribute"); case "__class__": throw PythonOps.TypeError("can't delete __class__ attribute"); } object value; if (!_dict.TryRemoveValue(name, out value)) { throw PythonOps.AttributeErrorForMissingAttribute("module", name); } } public string/*!*/ __repr__() { return __str__(); } public string/*!*/ __str__() { object fileObj, nameObj; if (!_dict.TryGetValue("__file__", out fileObj)) { fileObj = null; } if (!_dict._storage.TryGetName(out nameObj)) { nameObj = null; } string file = fileObj as string; string name = nameObj as string ?? "?"; if (file == null) { return String.Format("<module '{0}' (built-in)>", name); } return String.Format("<module '{0}' from '{1}'>", name, file); } internal PythonDictionary __dict__ { get { return _dict; } } [SpecialName, PropertyMethod] public PythonDictionary Get__dict__() { return _dict; } [SpecialName, PropertyMethod] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public void Set__dict__(object value) { throw PythonOps.TypeError("readonly attribute"); } [SpecialName, PropertyMethod] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public void Delete__dict__() { throw PythonOps.TypeError("readonly attribute"); } public Scope Scope { get { if (_scope == null) { Interlocked.CompareExchange(ref _scope, new Scope(new ObjectDictionaryExpando(_dict)), null); } return _scope; } } #region IDynamicMetaObjectProvider Members [PythonHidden] // needs to be public so that we can override it. public DynamicMetaObject GetMetaObject(Expression parameter) { return new MetaModule(this, parameter); } #endregion class MetaModule : MetaPythonObject, IPythonGetable { public MetaModule(PythonModule module, Expression self) : base(self, BindingRestrictions.Empty, module) { } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { return GetMemberWorker(binder, PythonContext.GetCodeContextMO(binder)); } #region IPythonGetable Members public DynamicMetaObject GetMember(PythonGetMemberBinder member, DynamicMetaObject codeContext) { return GetMemberWorker(member, codeContext); } #endregion private DynamicMetaObject GetMemberWorker(DynamicMetaObjectBinder binder, DynamicMetaObject codeContext) { string name = GetGetMemberName(binder); var tmp = Expression.Variable(typeof(object), "res"); return new DynamicMetaObject( Expression.Block( new[] { tmp }, Expression.Condition( Expression.Call( typeof(PythonOps).GetMethod(nameof(PythonOps.ModuleTryGetMember)), PythonContext.GetCodeContext(binder), Utils.Convert(Expression, typeof(PythonModule)), Expression.Constant(name), tmp ), tmp, Expression.Convert(GetMemberFallback(this, binder, codeContext).Expression, typeof(object)) ) ), BindingRestrictions.GetTypeRestriction(Expression, Value.GetType()) ); } public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) { return BindingHelpers.GenericInvokeMember(action, null, this, args); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { Debug.Assert(value.Value != Uninitialized.Instance); return new DynamicMetaObject( Expression.Block( Expression.Call( Utils.Convert(Expression, typeof(PythonModule)), typeof(PythonModule).GetMethod("__setattr__"), PythonContext.GetCodeContext(binder), Expression.Constant(binder.Name), Expression.Convert(value.Expression, typeof(object)) ), Expression.Convert(value.Expression, typeof(object)) ), BindingRestrictions.GetTypeRestriction(Expression, Value.GetType()) ); } public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) { return new DynamicMetaObject( Expression.Call( Utils.Convert(Expression, typeof(PythonModule)), typeof(PythonModule).GetMethod("__delattr__"), PythonContext.GetCodeContext(binder), Expression.Constant(binder.Name) ), BindingRestrictions.GetTypeRestriction(Expression, Value.GetType()) ); } public override IEnumerable<string> GetDynamicMemberNames() { foreach (object o in ((PythonModule)Value).__dict__.Keys) { if (o is string str) { yield return str; } } } } internal string GetFile() { object res; if (_dict.TryGetValue("__file__", out res)) { return res as string; } return null; } internal string GetName() { object res; if (_dict._storage.TryGetName(out res)) { return res as string; } return null; } #region IPythonMembersList Members IList<object> IPythonMembersList.GetMemberNames(CodeContext context) { return new List<object>(__dict__.Keys); } #endregion #region IMembersList Members IList<string> IMembersList.GetMemberNames() { List<string> res = new List<string>(__dict__.Keys.Count); foreach (object o in __dict__.Keys) { if (o is string strKey) { res.Add(strKey); } } return res; } #endregion internal class DebugProxy { private readonly PythonModule _module; public DebugProxy(PythonModule module) { _module = module; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public List<ObjectDebugView> Members { get { var res = new List<ObjectDebugView>(); foreach (var v in _module._dict) { res.Add(new ObjectDebugView(v.Key, v.Value)); } return res; } } } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ----------------------------------------------------------------------------- // The following code is a port of MakeSpriteFont from DirectXTk // http://go.microsoft.com/fwlink/?LinkId=248929 // ----------------------------------------------------------------------------- // Microsoft Public License (Ms-PL) // // This license governs use of the accompanying software. If you use the // software, you accept this license. If you do not accept the license, do not // use the software. // // 1. Definitions // The terms "reproduce," "reproduction," "derivative works," and // "distribution" have the same meaning here as under U.S. copyright law. // A "contribution" is the original software, or any additions or changes to // the software. // A "contributor" is any person that distributes its contribution under this // license. // "Licensed patents" are a contributor's patent claims that read directly on // its contribution. // // 2. Grant of Rights // (A) Copyright Grant- Subject to the terms of this license, including the // license conditions and limitations in section 3, each contributor grants // you a non-exclusive, worldwide, royalty-free copyright license to reproduce // its contribution, prepare derivative works of its contribution, and // distribute its contribution or any derivative works that you create. // (B) Patent Grant- Subject to the terms of this license, including the license // conditions and limitations in section 3, each contributor grants you a // non-exclusive, worldwide, royalty-free license under its licensed patents to // make, have made, use, sell, offer for sale, import, and/or otherwise dispose // of its contribution in the software or derivative works of the contribution // in the software. // // 3. Conditions and Limitations // (A) No Trademark License- This license does not grant you rights to use any // contributors' name, logo, or trademarks. // (B) If you bring a patent claim against any contributor over patents that // you claim are infringed by the software, your patent license from such // contributor to the software ends automatically. // (C) If you distribute any portion of the software, you must retain all // copyright, patent, trademark, and attribution notices that are present in the // software. // (D) If you distribute any portion of the software in source code form, you // may do so only under this license by including a complete copy of this // license with your distribution. If you distribute any portion of the software // in compiled or object code form, you may only do so under a license that // complies with this license. // (E) The software is licensed "as-is." You bear the risk of using it. The // contributors give no express warranties, guarantees or conditions. You may // have additional consumer rights under your local laws which this license // cannot change. To the extent permitted under your local laws, the // contributors exclude the implied warranties of merchantability, fitness for a // particular purpose and non-infringement. //-------------------------------------------------------------------- using System; using System.Collections.Generic; namespace SharpDX.Toolkit.Graphics { using System.Drawing; using System.Drawing.Imaging; // Helper for arranging many small bitmaps onto a single larger surface. internal static class GlyphPacker { public static Bitmap ArrangeGlyphs(Glyph[] sourceGlyphs) { // Build up a list of all the glyphs needing to be arranged. List<ArrangedGlyph> glyphs = new List<ArrangedGlyph>(); for (int i = 0; i < sourceGlyphs.Length; i++) { ArrangedGlyph glyph = new ArrangedGlyph(); glyph.Source = sourceGlyphs[i]; // Leave a one pixel border around every glyph in the output bitmap. glyph.Width = sourceGlyphs[i].Subrect.Width + 2; glyph.Height = sourceGlyphs[i].Subrect.Height + 2; glyphs.Add(glyph); } // Sort so the largest glyphs get arranged first. glyphs.Sort(CompareGlyphSizes); // Work out how big the output bitmap should be. int outputWidth = GuessOutputWidth(sourceGlyphs); int outputHeight = 0; // Choose positions for each glyph, one at a time. for (int i = 0; i < glyphs.Count; i++) { PositionGlyph(glyphs, i, outputWidth); outputHeight = Math.Max(outputHeight, glyphs[i].Y + glyphs[i].Height); } // Create the merged output bitmap. outputHeight = MakeValidTextureSize(outputHeight, false); return CopyGlyphsToOutput(glyphs, outputWidth, outputHeight); } // Once arranging is complete, copies each glyph to its chosen position in the single larger output bitmap. static Bitmap CopyGlyphsToOutput(List<ArrangedGlyph> glyphs, int width, int height) { Bitmap output = new Bitmap(width, height, PixelFormat.Format32bppArgb); foreach (ArrangedGlyph glyph in glyphs) { Glyph sourceGlyph = glyph.Source; Rectangle sourceRegion = sourceGlyph.Subrect; Rectangle destinationRegion = new Rectangle(glyph.X + 1, glyph.Y + 1, sourceRegion.Width, sourceRegion.Height); BitmapUtils.CopyRect(sourceGlyph.Bitmap, sourceRegion, output, destinationRegion); BitmapUtils.PadBorderPixels(output, destinationRegion); sourceGlyph.Bitmap = output; sourceGlyph.Subrect = destinationRegion; } return output; } // Internal helper class keeps track of a glyph while it is being arranged. class ArrangedGlyph { public Glyph Source; public int X; public int Y; public int Width; public int Height; } // Works out where to position a single glyph. static void PositionGlyph(List<ArrangedGlyph> glyphs, int index, int outputWidth) { int x = 0; int y = 0; while (true) { // Is this position free for us to use? int intersects = FindIntersectingGlyph(glyphs, index, x, y); if (intersects < 0) { glyphs[index].X = x; glyphs[index].Y = y; return; } // Skip past the existing glyph that we collided with. x = glyphs[intersects].X + glyphs[intersects].Width; // If we ran out of room to move to the right, try the next line down instead. if (x + glyphs[index].Width > outputWidth) { x = 0; y++; } } } // Checks if a proposed glyph position collides with anything that we already arranged. static int FindIntersectingGlyph(List<ArrangedGlyph> glyphs, int index, int x, int y) { int w = glyphs[index].Width; int h = glyphs[index].Height; for (int i = 0; i < index; i++) { if (glyphs[i].X >= x + w) continue; if (glyphs[i].X + glyphs[i].Width <= x) continue; if (glyphs[i].Y >= y + h) continue; if (glyphs[i].Y + glyphs[i].Height <= y) continue; return i; } return -1; } // Comparison function for sorting glyphs by size. static int CompareGlyphSizes(ArrangedGlyph a, ArrangedGlyph b) { const int heightWeight = 1024; int aSize = a.Height * heightWeight + a.Width; int bSize = b.Height * heightWeight + b.Width; if (aSize != bSize) return bSize.CompareTo(aSize); else return a.Source.Character.CompareTo(b.Source.Character); } // Heuristic guesses what might be a good output width for a list of glyphs. static int GuessOutputWidth(Glyph[] sourceGlyphs) { int maxWidth = 0; int totalSize = 0; foreach (Glyph glyph in sourceGlyphs) { maxWidth = Math.Max(maxWidth, glyph.Subrect.Width); totalSize += glyph.Subrect.Width * glyph.Subrect.Height; } int width = Math.Max((int)Math.Sqrt(totalSize), maxWidth); return MakeValidTextureSize(width, true); } // Rounds a value up to the next larger valid texture size. static int MakeValidTextureSize(int value, bool requirePowerOfTwo) { // In case we want to DXT compress, make sure the size is a multiple of 4. const int blockSize = 4; if (requirePowerOfTwo) { // Round up to a power of two. int powerOfTwo = blockSize; while (powerOfTwo < value) powerOfTwo <<= 1; return powerOfTwo; } else { // Round up to the specified block size. return (value + blockSize - 1) & ~(blockSize - 1); } } } }
/* This file is part of SevenZipSharp. SevenZipSharp is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SevenZipSharp 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with SevenZipSharp. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; #if DOTNET20 using System.Threading; #else using System.Linq; #endif using SevenZip.Sdk.Compression.Lzma; #if MONO using SevenZip.Mono.COM; #endif namespace SevenZip { /// <summary> /// Class to unpack data from archives supported by 7-Zip. /// </summary> /// <example> /// using (var extr = new SevenZipExtractor(@"C:\Test.7z")) /// { /// extr.ExtractArchive(@"C:\TestDirectory"); /// } /// </example> public sealed partial class SevenZipExtractor #if UNMANAGED : SevenZipBase, IDisposable #endif { #if UNMANAGED private List<ArchiveFileInfo> _archiveFileData; private IInArchive _archive; private IInStream _archiveStream; private int _offset; private ArchiveOpenCallback _openCallback; private string _fileName; private Stream _inStream; private long? _packedSize; private long? _unpackedSize; private uint? _filesCount; private bool? _isSolid; private bool _opened; private bool _disposed; private InArchiveFormat _format = (InArchiveFormat)(-1); private ReadOnlyCollection<ArchiveFileInfo> _archiveFileInfoCollection; private ReadOnlyCollection<ArchiveProperty> _archiveProperties; private ReadOnlyCollection<string> _volumeFileNames; /// <summary> /// This is used to lock possible Dispose() calls. /// </summary> private bool _asynchronousDisposeLock; #region Constructors /// <summary> /// General initialization function. /// </summary> /// <param name="archiveFullName">The archive file name.</param> private void Init(string archiveFullName) { _fileName = archiveFullName; bool isExecutable = false; if ((int)_format == -1) { _format = FileChecker.CheckSignature(archiveFullName, out _offset, out isExecutable); } PreserveDirectoryStructure = true; SevenZipLibraryManager.LoadLibrary(this, _format); try { _archive = SevenZipLibraryManager.InArchive(_format, this); } catch (SevenZipLibraryException) { SevenZipLibraryManager.FreeLibrary(this, _format); throw; } if (isExecutable && _format != InArchiveFormat.PE) { if (!Check()) { CommonDispose(); _format = InArchiveFormat.PE; SevenZipLibraryManager.LoadLibrary(this, _format); try { _archive = SevenZipLibraryManager.InArchive(_format, this); } catch (SevenZipLibraryException) { SevenZipLibraryManager.FreeLibrary(this, _format); throw; } } } } /// <summary> /// General initialization function. /// </summary> /// <param name="stream">The stream to read the archive from.</param> private void Init(Stream stream) { ValidateStream(stream); bool isExecutable = false; if ((int)_format == -1) { _format = FileChecker.CheckSignature(stream, out _offset, out isExecutable); } PreserveDirectoryStructure = true; SevenZipLibraryManager.LoadLibrary(this, _format); try { _inStream = new ArchiveEmulationStreamProxy(stream, _offset); _packedSize = stream.Length; _archive = SevenZipLibraryManager.InArchive(_format, this); } catch (SevenZipLibraryException) { SevenZipLibraryManager.FreeLibrary(this, _format); throw; } if (isExecutable && _format != InArchiveFormat.PE) { if (!Check()) { CommonDispose(); _format = InArchiveFormat.PE; try { _inStream = new ArchiveEmulationStreamProxy(stream, _offset); _packedSize = stream.Length; _archive = SevenZipLibraryManager.InArchive(_format, this); } catch (SevenZipLibraryException) { SevenZipLibraryManager.FreeLibrary(this, _format); throw; } } } } /// <summary> /// Initializes a new instance of SevenZipExtractor class. /// </summary> /// <param name="archiveStream">The stream to read the archive from. /// Use SevenZipExtractor(string) to extract from disk, though it is not necessary.</param> /// <remarks>The archive format is guessed by the signature.</remarks> public SevenZipExtractor(Stream archiveStream) { Init(archiveStream); } /// <summary> /// Initializes a new instance of SevenZipExtractor class. /// </summary> /// <param name="archiveStream">The stream to read the archive from. /// Use SevenZipExtractor(string) to extract from disk, though it is not necessary.</param> /// <param name="format">Manual archive format setup. You SHOULD NOT normally specify it this way. /// Instead, use SevenZipExtractor(Stream archiveStream), that constructor /// automatically detects the archive format.</param> public SevenZipExtractor(Stream archiveStream, InArchiveFormat format) { _format = format; Init(archiveStream); } /// <summary> /// Initializes a new instance of SevenZipExtractor class. /// </summary> /// <param name="archiveFullName">The archive full file name.</param> public SevenZipExtractor(string archiveFullName) { Init(archiveFullName); } /// <summary> /// Initializes a new instance of SevenZipExtractor class. /// </summary> /// <param name="archiveFullName">The archive full file name.</param> /// <param name="format">Manual archive format setup. You SHOULD NOT normally specify it this way. /// Instead, use SevenZipExtractor(string archiveFullName), that constructor /// automatically detects the archive format.</param> public SevenZipExtractor(string archiveFullName, InArchiveFormat format) { _format = format; Init(archiveFullName); } /// <summary> /// Initializes a new instance of SevenZipExtractor class. /// </summary> /// <param name="archiveFullName">The archive full file name.</param> /// <param name="password">Password for an encrypted archive.</param> public SevenZipExtractor(string archiveFullName, string password) : base(password) { Init(archiveFullName); } /// <summary> /// Initializes a new instance of SevenZipExtractor class. /// </summary> /// <param name="archiveFullName">The archive full file name.</param> /// <param name="password">Password for an encrypted archive.</param> /// <param name="format">Manual archive format setup. You SHOULD NOT normally specify it this way. /// Instead, use SevenZipExtractor(string archiveFullName, string password), that constructor /// automatically detects the archive format.</param> public SevenZipExtractor(string archiveFullName, string password, InArchiveFormat format) : base(password) { _format = format; Init(archiveFullName); } /// <summary> /// Initializes a new instance of SevenZipExtractor class. /// </summary> /// <param name="archiveStream">The stream to read the archive from.</param> /// <param name="password">Password for an encrypted archive.</param> /// <remarks>The archive format is guessed by the signature.</remarks> public SevenZipExtractor(Stream archiveStream, string password) : base(password) { Init(archiveStream); } /// <summary> /// Initializes a new instance of SevenZipExtractor class. /// </summary> /// <param name="archiveStream">The stream to read the archive from.</param> /// <param name="password">Password for an encrypted archive.</param> /// <param name="format">Manual archive format setup. You SHOULD NOT normally specify it this way. /// Instead, use SevenZipExtractor(Stream archiveStream, string password), that constructor /// automatically detects the archive format.</param> public SevenZipExtractor(Stream archiveStream, string password, InArchiveFormat format) : base(password) { _format = format; Init(archiveStream); } #endregion #region Properties /// <summary> /// Gets or sets archive full file name /// </summary> public string FileName { get { DisposedCheck(); return _fileName; } } /// <summary> /// Gets the size of the archive file /// </summary> public long PackedSize { get { DisposedCheck(); return _packedSize.HasValue ? _packedSize.Value : _fileName != null ? (new FileInfo(_fileName)).Length : -1; } } /// <summary> /// Gets the size of unpacked archive data /// </summary> public long UnpackedSize { get { DisposedCheck(); if (!_unpackedSize.HasValue) { return -1; } return _unpackedSize.Value; } } /// <summary> /// Gets a value indicating whether the archive is solid /// </summary> public bool IsSolid { get { DisposedCheck(); if (!_isSolid.HasValue) { GetArchiveInfo(true); } Debug.Assert(_isSolid != null); return _isSolid.Value; } } /// <summary> /// Gets the number of files in the archive /// </summary> public uint FilesCount { get { DisposedCheck(); if (!_filesCount.HasValue) { GetArchiveInfo(true); } Debug.Assert(_filesCount != null); return _filesCount.Value; } } /// <summary> /// Gets archive format /// </summary> public InArchiveFormat Format { get { DisposedCheck(); return _format; } } /// <summary> /// Gets or sets the value indicating whether to preserve the directory structure of extracted files. /// </summary> public bool PreserveDirectoryStructure { get; set; } #endregion /// <summary> /// Checked whether the class was disposed. /// </summary> /// <exception cref="System.ObjectDisposedException" /> private void DisposedCheck() { if (_disposed) { throw new ObjectDisposedException("SevenZipExtractor"); } #if !WINCE RecreateInstanceIfNeeded(); #endif } #region Core private functions private ArchiveOpenCallback GetArchiveOpenCallback() { return _openCallback ?? (_openCallback = String.IsNullOrEmpty(Password) ? new ArchiveOpenCallback(_fileName) : new ArchiveOpenCallback(_fileName, Password)); } /// <summary> /// Gets the archive input stream. /// </summary> /// <returns>The archive input wrapper stream.</returns> private IInStream GetArchiveStream(bool dispose) { if (_archiveStream != null) { if (_archiveStream is DisposeVariableWrapper) { (_archiveStream as DisposeVariableWrapper).DisposeStream = dispose; } return _archiveStream; } if (_inStream != null) { _inStream.Seek(0, SeekOrigin.Begin); _archiveStream = new InStreamWrapper(_inStream, false); } else { if (!_fileName.EndsWith(".001", StringComparison.OrdinalIgnoreCase) || (_volumeFileNames.Count == 1)) { _archiveStream = new InStreamWrapper( new ArchiveEmulationStreamProxy(new FileStream( _fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), _offset), dispose); } else { _archiveStream = new InMultiStreamWrapper(_fileName, dispose); _packedSize = (_archiveStream as InMultiStreamWrapper).Length; } } return _archiveStream; } /// <summary> /// Opens the archive and throws exceptions or returns OperationResult.DataError if any error occurs. /// </summary> /// <param name="archiveStream">The IInStream compliant class instance, that is, the input stream.</param> /// <param name="openCallback">The ArchiveOpenCallback instance.</param> /// <returns>OperationResult.Ok if Open() succeeds.</returns> private OperationResult OpenArchiveInner(IInStream archiveStream, IArchiveOpenCallback openCallback) { ulong checkPos = 1 << 15; int res = _archive.Open(archiveStream, ref checkPos, openCallback); return (OperationResult)res; } /// <summary> /// Opens the archive and throws exceptions or returns OperationResult.DataError if any error occurs. /// </summary> /// <param name="archiveStream">The IInStream compliant class instance, that is, the input stream.</param> /// <param name="openCallback">The ArchiveOpenCallback instance.</param> /// <returns>True if Open() succeeds; otherwise, false.</returns> private bool OpenArchive(IInStream archiveStream, ArchiveOpenCallback openCallback) { if (!_opened) { if (OpenArchiveInner(archiveStream, openCallback) != OperationResult.Ok) { if (!ThrowException(null, new SevenZipArchiveException())) { return false; } } _volumeFileNames = new ReadOnlyCollection<string>(openCallback.VolumeFileNames); _opened = true; } return true; } /// <summary> /// Retrieves all information about the archive. /// </summary> /// <exception cref="SevenZip.SevenZipArchiveException"/> private void GetArchiveInfo(bool disposeStream) { if (_archive == null) { if (!ThrowException(null, new SevenZipArchiveException())) { return; } } else { IInStream archiveStream; using ((archiveStream = GetArchiveStream(disposeStream)) as IDisposable) { var openCallback = GetArchiveOpenCallback(); if (!_opened) { if (!OpenArchive(archiveStream, openCallback)) { return; } _opened = !disposeStream; } _filesCount = _archive.GetNumberOfItems(); _archiveFileData = new List<ArchiveFileInfo>((int)_filesCount); if (_filesCount != 0) { var data = new PropVariant(); try { #region Getting archive items data for (uint i = 0; i < _filesCount; i++) { try { var fileInfo = new ArchiveFileInfo { Index = (int)i }; _archive.GetProperty(i, ItemPropId.Path, ref data); fileInfo.FileName = NativeMethods.SafeCast(data, "[no name]"); _archive.GetProperty(i, ItemPropId.LastWriteTime, ref data); fileInfo.LastWriteTime = NativeMethods.SafeCast(data, DateTime.Now); _archive.GetProperty(i, ItemPropId.CreationTime, ref data); fileInfo.CreationTime = NativeMethods.SafeCast(data, DateTime.Now); _archive.GetProperty(i, ItemPropId.LastAccessTime, ref data); fileInfo.LastAccessTime = NativeMethods.SafeCast(data, DateTime.Now); _archive.GetProperty(i, ItemPropId.Size, ref data); fileInfo.Size = NativeMethods.SafeCast<ulong>(data, 0); if (fileInfo.Size == 0) { fileInfo.Size = NativeMethods.SafeCast<uint>(data, 0); } _archive.GetProperty(i, ItemPropId.Attributes, ref data); fileInfo.Attributes = NativeMethods.SafeCast<uint>(data, 0); _archive.GetProperty(i, ItemPropId.IsDirectory, ref data); fileInfo.IsDirectory = NativeMethods.SafeCast(data, false); _archive.GetProperty(i, ItemPropId.Encrypted, ref data); fileInfo.Encrypted = NativeMethods.SafeCast(data, false); _archive.GetProperty(i, ItemPropId.Crc, ref data); fileInfo.Crc = NativeMethods.SafeCast<uint>(data, 0); _archive.GetProperty(i, ItemPropId.Comment, ref data); fileInfo.Comment = NativeMethods.SafeCast(data, ""); _archiveFileData.Add(fileInfo); } catch (InvalidCastException) { ThrowException(null, new SevenZipArchiveException("probably archive is corrupted.")); } } #endregion #region Getting archive properties uint numProps = _archive.GetNumberOfArchiveProperties(); var archProps = new List<ArchiveProperty>((int)numProps); for (uint i = 0; i < numProps; i++) { string propName; ItemPropId propId; ushort varType; _archive.GetArchivePropertyInfo(i, out propName, out propId, out varType); _archive.GetArchiveProperty(propId, ref data); if (propId == ItemPropId.Solid) { _isSolid = NativeMethods.SafeCast(data, true); } // TODO Add more archive properties if (PropIdToName.PropIdNames.ContainsKey(propId)) { archProps.Add(new ArchiveProperty { Name = PropIdToName.PropIdNames[propId], Value = data.Object }); } else { Debug.WriteLine( "An unknown archive property encountered (code " + ((int)propId).ToString(CultureInfo.InvariantCulture) + ')'); } } _archiveProperties = new ReadOnlyCollection<ArchiveProperty>(archProps); if (!_isSolid.HasValue && _format == InArchiveFormat.Zip) { _isSolid = false; } if (!_isSolid.HasValue) { _isSolid = true; } #endregion } catch (Exception) { if (openCallback.ThrowException()) { throw; } } } } if (disposeStream) { _archive.Close(); _archiveStream = null; } _archiveFileInfoCollection = new ReadOnlyCollection<ArchiveFileInfo>(_archiveFileData); } } /// <summary> /// Ensure that _archiveFileData is loaded. /// </summary> /// <param name="disposeStream">Dispose the archive stream after this operation.</param> private void InitArchiveFileData(bool disposeStream) { if (_archiveFileData == null) { GetArchiveInfo(disposeStream); } } /// <summary> /// Produces an array of indexes from 0 to the maximum value in the specified array /// </summary> /// <param name="indexes">The source array</param> /// <returns>The array of indexes from 0 to the maximum value in the specified array</returns> private static uint[] SolidIndexes(uint[] indexes) { #if CS4 int max = indexes.Aggregate(0, (current, i) => Math.Max(current, (int) i)); #else int max = 0; foreach (uint i in indexes) { max = Math.Max(max, (int)i); } #endif if (max > 0) { max++; var res = new uint[max]; for (int i = 0; i < max; i++) { res[i] = (uint)i; } return res; } return indexes; } /// <summary> /// Checkes whether all the indexes are valid. /// </summary> /// <param name="indexes">The indexes to check.</param> /// <returns>True is valid; otherwise, false.</returns> private static bool CheckIndexes(params int[] indexes) { #if CS4 // Wow, C# 4 is great! return indexes.All(i => i >= 0); #else bool res = true; foreach (int i in indexes) { if (i < 0) { res = false; break; } } return res; #endif } private void ArchiveExtractCallbackCommonInit(ArchiveExtractCallback aec) { aec.Open += ((s, e) => { _unpackedSize = (long)e.TotalSize; }); aec.FileExtractionStarted += FileExtractionStartedEventProxy; aec.FileExtractionFinished += FileExtractionFinishedEventProxy; aec.Extracting += ExtractingEventProxy; aec.FileExists += FileExistsEventProxy; } /// <summary> /// Gets the IArchiveExtractCallback callback /// </summary> /// <param name="directory">The directory where extract the files</param> /// <param name="filesCount">The number of files to be extracted</param> /// <param name="actualIndexes">The list of actual indexes (solid archives support)</param> /// <returns>The ArchiveExtractCallback callback</returns> private ArchiveExtractCallback GetArchiveExtractCallback(string directory, int filesCount, List<uint> actualIndexes) { var aec = String.IsNullOrEmpty(Password) ? new ArchiveExtractCallback(_archive, directory, filesCount, PreserveDirectoryStructure, actualIndexes, this) : new ArchiveExtractCallback(_archive, directory, filesCount, PreserveDirectoryStructure, actualIndexes, Password, this); ArchiveExtractCallbackCommonInit(aec); return aec; } /// <summary> /// Gets the IArchiveExtractCallback callback /// </summary> /// <param name="stream">The stream where extract the file</param> /// <param name="index">The file index</param> /// <param name="filesCount">The number of files to be extracted</param> /// <returns>The ArchiveExtractCallback callback</returns> private ArchiveExtractCallback GetArchiveExtractCallback(Stream stream, uint index, int filesCount) { var aec = String.IsNullOrEmpty(Password) ? new ArchiveExtractCallback(_archive, stream, filesCount, index, this) : new ArchiveExtractCallback(_archive, stream, filesCount, index, Password, this); ArchiveExtractCallbackCommonInit(aec); return aec; } private void FreeArchiveExtractCallback(ArchiveExtractCallback callback) { callback.Open -= ((s, e) => { _unpackedSize = (long)e.TotalSize; }); callback.FileExtractionStarted -= FileExtractionStartedEventProxy; callback.FileExtractionFinished -= FileExtractionFinishedEventProxy; callback.Extracting -= ExtractingEventProxy; callback.FileExists -= FileExistsEventProxy; } #endregion #endif /// <summary> /// Checks if the specified stream supports extraction. /// </summary> /// <param name="stream">The stream to check.</param> private static void ValidateStream(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanSeek || !stream.CanRead) { throw new ArgumentException("The specified stream can not seek or read.", "stream"); } if (stream.Length == 0) { throw new ArgumentException("The specified stream has zero length.", "stream"); } } #if UNMANAGED #region IDisposable Members private void CommonDispose() { if (_opened) { try { if (_archive != null) { _archive.Close(); } } catch (Exception) { } } _archive = null; _archiveFileData = null; _archiveProperties = null; _archiveFileInfoCollection = null; if (_inStream != null) { _inStream.Dispose(); } _inStream = null; if (_openCallback != null) { try { _openCallback.Dispose(); } catch (ObjectDisposedException) { } _openCallback = null; } if (_archiveStream != null) { if (_archiveStream is IDisposable) { try { if (_archiveStream is DisposeVariableWrapper) { (_archiveStream as DisposeVariableWrapper).DisposeStream = true; } (_archiveStream as IDisposable).Dispose(); } catch (ObjectDisposedException) { } _archiveStream = null; } } SevenZipLibraryManager.FreeLibrary(this, _format); } /// <summary> /// Releases the unmanaged resources used by SevenZipExtractor. /// </summary> public void Dispose() { if (_asynchronousDisposeLock) { throw new InvalidOperationException("SevenZipExtractor instance must not be disposed " + "while making an asynchronous method call."); } if (!_disposed) { CommonDispose(); } _disposed = true; GC.SuppressFinalize(this); } #endregion #region Core public Members #region Events /// <summary> /// Occurs when a new file is going to be unpacked. /// </summary> /// <remarks>Occurs when 7-zip engine requests for an output stream for a new file to unpack in.</remarks> public event EventHandler<FileInfoEventArgs> FileExtractionStarted; /// <summary> /// Occurs when a file has been successfully unpacked. /// </summary> public event EventHandler<FileInfoEventArgs> FileExtractionFinished; /// <summary> /// Occurs when the archive has been unpacked. /// </summary> public event EventHandler<EventArgs> ExtractionFinished; /// <summary> /// Occurs when data are being extracted. /// </summary> /// <remarks>Use this event for accurate progress handling and various ProgressBar.StepBy(e.PercentDelta) routines.</remarks> public event EventHandler<ProgressEventArgs> Extracting; /// <summary> /// Occurs during the extraction when a file already exists. /// </summary> public event EventHandler<FileOverwriteEventArgs> FileExists; #region Event proxies /// <summary> /// Event proxy for FileExtractionStarted. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The event arguments.</param> private void FileExtractionStartedEventProxy(object sender, FileInfoEventArgs e) { OnEvent(FileExtractionStarted, e, true); } /// <summary> /// Event proxy for FileExtractionFinished. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The event arguments.</param> private void FileExtractionFinishedEventProxy(object sender, FileInfoEventArgs e) { OnEvent(FileExtractionFinished, e, true); } /// <summary> /// Event proxy for Extractng. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The event arguments.</param> private void ExtractingEventProxy(object sender, ProgressEventArgs e) { OnEvent(Extracting, e, false); } /// <summary> /// Event proxy for FileExists. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The event arguments.</param> private void FileExistsEventProxy(object sender, FileOverwriteEventArgs e) { OnEvent(FileExists, e, true); } #endregion #endregion #region Properties /// <summary> /// Gets the collection of ArchiveFileInfo with all information about files in the archive /// </summary> public ReadOnlyCollection<ArchiveFileInfo> ArchiveFileData { get { DisposedCheck(); InitArchiveFileData(true); return _archiveFileInfoCollection; } } /// <summary> /// Gets the properties for the current archive /// </summary> public ReadOnlyCollection<ArchiveProperty> ArchiveProperties { get { DisposedCheck(); InitArchiveFileData(true); return _archiveProperties; } } /// <summary> /// Gets the collection of all file names contained in the archive. /// </summary> /// <remarks> /// Each get recreates the collection /// </remarks> public ReadOnlyCollection<string> ArchiveFileNames { get { DisposedCheck(); InitArchiveFileData(true); var fileNames = new List<string>(_archiveFileData.Count); #if CS4 fileNames.AddRange(_archiveFileData.Select(afi => afi.FileName)); #else foreach (var afi in _archiveFileData) { fileNames.Add(afi.FileName); } #endif return new ReadOnlyCollection<string>(fileNames); } } /// <summary> /// Gets the list of archive volume file names. /// </summary> public ReadOnlyCollection<string> VolumeFileNames { get { DisposedCheck(); InitArchiveFileData(true); return _volumeFileNames; } } #endregion /// <summary> /// Performs the archive integrity test. /// </summary> /// <returns>True is the archive is ok; otherwise, false.</returns> public bool Check() { DisposedCheck(); try { InitArchiveFileData(false); var archiveStream = GetArchiveStream(true); var openCallback = GetArchiveOpenCallback(); if (!OpenArchive(archiveStream, openCallback)) { return false; } using (var aec = GetArchiveExtractCallback("", (int)_filesCount, null)) { try { CheckedExecute( _archive.Extract(null, UInt32.MaxValue, 1, aec), SevenZipExtractionFailedException.DEFAULT_MESSAGE, aec); } finally { FreeArchiveExtractCallback(aec); } } } catch (Exception) { return false; } finally { if (_archive != null) { _archive.Close(); } ((InStreamWrapper)_archiveStream).Dispose(); _archiveStream = null; _opened = false; } return true; } #region ExtractFile overloads /// <summary> /// Unpacks the file by its name to the specified stream. /// </summary> /// <param name="fileName">The file full name in the archive file table.</param> /// <param name="stream">The stream where the file is to be unpacked.</param> public void ExtractFile(string fileName, Stream stream) { DisposedCheck(); InitArchiveFileData(false); int index = -1; foreach (ArchiveFileInfo afi in _archiveFileData) { if (afi.FileName == fileName && !afi.IsDirectory) { index = afi.Index; break; } } if (index == -1) { if (!ThrowException(null, new ArgumentOutOfRangeException( "fileName", "The specified file name was not found in the archive file table."))) { return; } } else { ExtractFile(index, stream); } } /// <summary> /// Unpacks the file by its index to the specified stream. /// </summary> /// <param name="index">Index in the archive file table.</param> /// <param name="stream">The stream where the file is to be unpacked.</param> public void ExtractFile(int index, Stream stream) { DisposedCheck(); ClearExceptions(); if (!CheckIndexes(index)) { if (!ThrowException(null, new ArgumentException("The index must be more or equal to zero.", "index"))) { return; } } if (!stream.CanWrite) { if (!ThrowException(null, new ArgumentException("The specified stream can not be written.", "stream"))) { return; } } InitArchiveFileData(false); if (index > _filesCount - 1) { if (!ThrowException(null, new ArgumentOutOfRangeException( "index", "The specified index is greater than the archive files count."))) { return; } } var indexes = new[] {(uint) index}; if (_isSolid.Value) { indexes = SolidIndexes(indexes); } var archiveStream = GetArchiveStream(false); var openCallback = GetArchiveOpenCallback(); if (!OpenArchive(archiveStream, openCallback)) { return; } try { using (var aec = GetArchiveExtractCallback(stream, (uint) index, indexes.Length)) { try { CheckedExecute( _archive.Extract(indexes, (uint) indexes.Length, 0, aec), SevenZipExtractionFailedException.DEFAULT_MESSAGE, aec); } finally { FreeArchiveExtractCallback(aec); } } } catch (Exception) { if (openCallback.ThrowException()) { throw; } } OnEvent(ExtractionFinished, EventArgs.Empty, false); ThrowUserException(); } #endregion #region ExtractFiles overloads /// <summary> /// Unpacks files by their indices to the specified directory. /// </summary> /// <param name="indexes">indexes of the files in the archive file table.</param> /// <param name="directory">Directory where the files are to be unpacked.</param> public void ExtractFiles(string directory, params int[] indexes) { DisposedCheck(); ClearExceptions(); if (!CheckIndexes(indexes)) { if ( !ThrowException(null, new ArgumentException("The indexes must be more or equal to zero.", "indexes"))) { return; } } InitArchiveFileData(false); #region Indexes stuff var uindexes = new uint[indexes.Length]; for (int i = 0; i < indexes.Length; i++) { uindexes[i] = (uint) indexes[i]; } #if CS4 if (uindexes.Where(i => i >= _filesCount).Any( i => !ThrowException(null, new ArgumentOutOfRangeException("indexes", "Index must be less than " + _filesCount.Value.ToString( CultureInfo.InvariantCulture) + "!")))) { return; } #else foreach (uint i in uindexes) { if (i >= _filesCount) { if (!ThrowException(null, new ArgumentOutOfRangeException("indexes", "Index must be less than " + _filesCount.Value.ToString( CultureInfo.InvariantCulture) + "!"))) { return; } } } #endif var origIndexes = new List<uint>(uindexes); origIndexes.Sort(); uindexes = origIndexes.ToArray(); if (_isSolid.Value) { uindexes = SolidIndexes(uindexes); } #endregion try { IInStream archiveStream; using ((archiveStream = GetArchiveStream(origIndexes.Count != 1)) as IDisposable) { var openCallback = GetArchiveOpenCallback(); if (!OpenArchive(archiveStream, openCallback)) { return; } try { using (var aec = GetArchiveExtractCallback(directory, (int) _filesCount, origIndexes)) { try { CheckedExecute( _archive.Extract(uindexes, (uint) uindexes.Length, 0, aec), SevenZipExtractionFailedException.DEFAULT_MESSAGE, aec); } finally { FreeArchiveExtractCallback(aec); } } } catch (Exception) { if (openCallback.ThrowException()) { throw; } } } OnEvent(ExtractionFinished, EventArgs.Empty, false); } finally { if (origIndexes.Count > 1) { if (_archive != null) { _archive.Close(); } _archiveStream = null; _opened = false; } } ThrowUserException(); } /// <summary> /// Unpacks files by their full names to the specified directory. /// </summary> /// <param name="fileNames">Full file names in the archive file table.</param> /// <param name="directory">Directory where the files are to be unpacked.</param> public void ExtractFiles(string directory, params string[] fileNames) { DisposedCheck(); InitArchiveFileData(false); var indexes = new List<int>(fileNames.Length); var archiveFileNames = new List<string>(ArchiveFileNames); foreach (string fn in fileNames) { if (!archiveFileNames.Contains(fn)) { if ( !ThrowException(null, new ArgumentOutOfRangeException("fileNames", "File \"" + fn + "\" was not found in the archive file table."))) { return; } } else { foreach (ArchiveFileInfo afi in _archiveFileData) { if (afi.FileName == fn && !afi.IsDirectory) { indexes.Add(afi.Index); break; } } } } ExtractFiles(directory, indexes.ToArray()); } /// <summary> /// Extracts files from the archive, giving a callback the choice what /// to do with each file. The order of the files is given by the archive. /// 7-Zip (and any other solid) archives are NOT supported. /// </summary> /// <param name="extractFileCallback">The callback to call for each file in the archive.</param> public void ExtractFiles(ExtractFileCallback extractFileCallback) { DisposedCheck(); InitArchiveFileData(false); if (IsSolid) { // solid strategy } else { foreach (ArchiveFileInfo archiveFileInfo in ArchiveFileData) { var extractFileCallbackArgs = new ExtractFileCallbackArgs(archiveFileInfo); extractFileCallback(extractFileCallbackArgs); if (extractFileCallbackArgs.CancelExtraction) { break; } if (extractFileCallbackArgs.ExtractToStream != null || extractFileCallbackArgs.ExtractToFile != null) { bool callDone = false; try { if (extractFileCallbackArgs.ExtractToStream != null) { ExtractFile(archiveFileInfo.Index, extractFileCallbackArgs.ExtractToStream); } else { using (var file = new FileStream(extractFileCallbackArgs.ExtractToFile, FileMode.CreateNew, FileAccess.Write, FileShare.None, 8192)) { ExtractFile(archiveFileInfo.Index, file); } } callDone = true; } catch (Exception ex) { extractFileCallbackArgs.Exception = ex; extractFileCallbackArgs.Reason = ExtractFileCallbackReason.Failure; extractFileCallback(extractFileCallbackArgs); if (!ThrowException(null, ex)) { return; } } if (callDone) { extractFileCallbackArgs.Reason = ExtractFileCallbackReason.Done; extractFileCallback(extractFileCallbackArgs); } } } } } #endregion /// <summary> /// Unpacks the whole archive to the specified directory. /// </summary> /// <param name="directory">The directory where the files are to be unpacked.</param> public void ExtractArchive(string directory) { DisposedCheck(); ClearExceptions(); InitArchiveFileData(false); try { IInStream archiveStream; using ((archiveStream = GetArchiveStream(true)) as IDisposable) { var openCallback = GetArchiveOpenCallback(); if (!OpenArchive(archiveStream, openCallback)) { return; } try { using (var aec = GetArchiveExtractCallback(directory, (int) _filesCount, null)) { try { CheckedExecute( _archive.Extract(null, UInt32.MaxValue, 0, aec), SevenZipExtractionFailedException.DEFAULT_MESSAGE, aec); OnEvent(ExtractionFinished, EventArgs.Empty, false); } finally { FreeArchiveExtractCallback(aec); } } } catch (Exception) { if (openCallback.ThrowException()) { throw; } } } } finally { if (_archive != null) { _archive.Close(); } _archiveStream = null; _opened = false; } ThrowUserException(); } #endregion #endif #region LZMA SDK functions internal static byte[] GetLzmaProperties(Stream inStream, out long outSize) { var lzmAproperties = new byte[5]; if (inStream.Read(lzmAproperties, 0, 5) != 5) { throw new LzmaException(); } outSize = 0; for (int i = 0; i < 8; i++) { int b = inStream.ReadByte(); if (b < 0) { throw new LzmaException(); } outSize |= ((long) (byte) b) << (i << 3); } return lzmAproperties; } /// <summary> /// Decompress the specified stream (C# inside) /// </summary> /// <param name="inStream">The source compressed stream</param> /// <param name="outStream">The destination uncompressed stream</param> /// <param name="inLength">The length of compressed data (null for inStream.Length)</param> /// <param name="codeProgressEvent">The event for handling the code progress</param> public static void DecompressStream(Stream inStream, Stream outStream, int? inLength, EventHandler<ProgressEventArgs> codeProgressEvent) { if (!inStream.CanRead || !outStream.CanWrite) { throw new ArgumentException("The specified streams are invalid."); } var decoder = new Decoder(); long outSize, inSize = (inLength.HasValue ? inLength.Value : inStream.Length) - inStream.Position; decoder.SetDecoderProperties(GetLzmaProperties(inStream, out outSize)); decoder.Code( inStream, outStream, inSize, outSize, new LzmaProgressCallback(inSize, codeProgressEvent)); } /// <summary> /// Decompress byte array compressed with LZMA algorithm (C# inside) /// </summary> /// <param name="data">Byte array to decompress</param> /// <returns>Decompressed byte array</returns> public static byte[] ExtractBytes(byte[] data) { using (var inStream = new MemoryStream(data)) { var decoder = new Decoder(); inStream.Seek(0, 0); using (var outStream = new MemoryStream()) { long outSize; decoder.SetDecoderProperties(GetLzmaProperties(inStream, out outSize)); decoder.Code(inStream, outStream, inStream.Length - inStream.Position, outSize, null); return outStream.ToArray(); } } } #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. // // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused. // using System; using System.Diagnostics.Contracts; namespace System.Text { [System.Runtime.InteropServices.ComVisible(true)] public class UTF7Encoding : Encoding { private const String base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // 0123456789111111111122222222223333333333444444444455555555556666 // 012345678901234567890123456789012345678901234567890123 // These are the characters that can be directly encoded in UTF7. private const String directChars = "\t\n\r '(),-./0123456789:?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // These are the characters that can be optionally directly encoded in UTF7. private const String optionalChars = "!\"#$%&*;<=>@[]^_`{|}"; // The set of base 64 characters. private byte[] _base64Bytes; // The decoded bits for every base64 values. This array has a size of 128 elements. // The index is the code point value of the base 64 characters. The value is -1 if // the code point is not a valid base 64 character. Otherwise, the value is a value // from 0 ~ 63. private sbyte[] _base64Values; // The array to decide if a Unicode code point below 0x80 can be directly encoded in UTF7. // This array has a size of 128. private bool[] _directEncode; private bool _allowOptionals; private const int UTF7_CODEPAGE = 65000; public UTF7Encoding() : this(false) { } public UTF7Encoding(bool allowOptionals) : base(UTF7_CODEPAGE) //Set the data item. { // Allowing optionals? _allowOptionals = allowOptionals; // Make our tables MakeTables(); } private void MakeTables() { // Build our tables _base64Bytes = new byte[64]; for (int i = 0; i < 64; i++) _base64Bytes[i] = (byte)base64Chars[i]; _base64Values = new sbyte[128]; for (int i = 0; i < 128; i++) _base64Values[i] = -1; for (int i = 0; i < 64; i++) _base64Values[_base64Bytes[i]] = (sbyte)i; _directEncode = new bool[128]; int count = directChars.Length; for (int i = 0; i < count; i++) { _directEncode[directChars[i]] = true; } if (_allowOptionals) { count = optionalChars.Length; for (int i = 0; i < count; i++) { _directEncode[optionalChars[i]] = true; } } } // We go ahead and set this because Encoding expects it, however nothing can fall back in UTF7. internal override void SetDefaultFallbacks() { // UTF7 had an odd decoderFallback behavior, and the Encoder fallback // is irrelevent because we encode surrogates individually and never check for unmatched ones // (so nothing can fallback during encoding) this.encoderFallback = new EncoderReplacementFallback(String.Empty); this.decoderFallback = new DecoderUTF7Fallback(); } [System.Runtime.InteropServices.ComVisible(false)] public override bool Equals(Object value) { UTF7Encoding that = value as UTF7Encoding; if (that != null) { return (_allowOptionals == that._allowOptionals) && (EncoderFallback.Equals(that.EncoderFallback)) && (DecoderFallback.Equals(that.DecoderFallback)); } return (false); } // Compared to all the other encodings, variations of UTF7 are unlikely [System.Runtime.InteropServices.ComVisible(false)] public override int GetHashCode() { return this.CodePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode(); } // // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to reimpliment them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (chars.Length == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetByteCount(String s) { // Validate input if (s == null) throw new ArgumentNullException("s"); Contract.EndContractBlock(); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = s) fixed (byte* pBytes = bytes) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (chars.Length == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = chars) fixed (byte* pBytes = bytes) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays. if (bytes.Length == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (bytes.Length == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; // Fixed doesn't like empty arrays if (chars.Length == 0) chars = new char[1]; fixed (byte* pBytes = bytes) fixed (char* pChars = chars) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(false)] public override unsafe String GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid problems with empty input buffer if (bytes.Length == 0) return String.Empty; fixed (byte* pBytes = bytes) return String.CreateStringFromEncoding( pBytes + index, count, this); } // // End of standard methods copied from EncodingNLS.cs // [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder) { Contract.Assert(chars != null, "[UTF7Encoding.GetByteCount]chars!=null"); Contract.Assert(count >= 0, "[UTF7Encoding.GetByteCount]count >=0"); // Just call GetBytes with bytes == null return GetBytes(chars, count, null, 0, baseEncoder); } [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS baseEncoder) { Contract.Assert(byteCount >= 0, "[UTF7Encoding.GetBytes]byteCount >=0"); Contract.Assert(chars != null, "[UTF7Encoding.GetBytes]chars!=null"); Contract.Assert(charCount >= 0, "[UTF7Encoding.GetBytes]charCount >=0"); // Get encoder info UTF7Encoding.Encoder encoder = (UTF7Encoding.Encoder)baseEncoder; // Default bits & count int bits = 0; int bitCount = -1; // prepare our helpers Encoding.EncodingByteBuffer buffer = new Encoding.EncodingByteBuffer( this, encoder, bytes, byteCount, chars, charCount); if (encoder != null) { bits = encoder.bits; bitCount = encoder.bitCount; // May have had too many left over while (bitCount >= 6) { bitCount -= 6; // If we fail we'll never really have enough room if (!buffer.AddByte(_base64Bytes[(bits >> bitCount) & 0x3F])) ThrowBytesOverflow(encoder, buffer.Count == 0); } } while (buffer.MoreData) { char currentChar = buffer.GetNextChar(); if (currentChar < 0x80 && _directEncode[currentChar]) { if (bitCount >= 0) { if (bitCount > 0) { // Try to add the next byte if (!buffer.AddByte(_base64Bytes[bits << 6 - bitCount & 0x3F])) break; // Stop here, didn't throw bitCount = 0; } // Need to get emit '-' and our char, 2 bytes total if (!buffer.AddByte((byte)'-')) break; // Stop here, didn't throw bitCount = -1; } // Need to emit our char if (!buffer.AddByte((byte)currentChar)) break; // Stop here, didn't throw } else if (bitCount < 0 && currentChar == '+') { if (!buffer.AddByte((byte)'+', (byte)'-')) break; // Stop here, didn't throw } else { if (bitCount < 0) { // Need to emit a + and 12 bits (3 bytes) // Only 12 of the 16 bits will be emitted this time, the other 4 wait 'til next time if (!buffer.AddByte((byte)'+')) break; // Stop here, didn't throw // We're now in bit mode, but haven't stored data yet bitCount = 0; } // Add our bits bits = bits << 16 | currentChar; bitCount += 16; while (bitCount >= 6) { bitCount -= 6; if (!buffer.AddByte(_base64Bytes[(bits >> bitCount) & 0x3F])) { bitCount += 6; // We didn't use these bits currentChar = buffer.GetNextChar(); // We're processing this char still, but AddByte // --'d it when we ran out of space break; // Stop here, not enough room for bytes } } if (bitCount >= 6) break; // Didn't have room to encode enough bits } } // Now if we have bits left over we have to encode them. // MustFlush may have been cleared by encoding.ThrowBytesOverflow earlier if converting if (bitCount >= 0 && (encoder == null || encoder.MustFlush)) { // Do we have bits we have to stick in? if (bitCount > 0) { if (buffer.AddByte(_base64Bytes[(bits << (6 - bitCount)) & 0x3F])) { // Emitted spare bits, 0 bits left bitCount = 0; } } // If converting and failed bitCount above, then we'll fail this too if (buffer.AddByte((byte)'-')) { // turned off bit mode'; bits = 0; bitCount = -1; } else // If not successful, convert will maintain state for next time, also // AddByte will have decremented our char count, however we need it to remain the same buffer.GetNextChar(); } // Do we have an encoder we're allowed to use? // bytes == null if counting, so don't use encoder then if (bytes != null && encoder != null) { // We already cleared bits & bitcount for mustflush case encoder.bits = bits; encoder.bitCount = bitCount; encoder.m_charsUsed = buffer.CharsUsed; } return buffer.Count; } [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { Contract.Assert(count >= 0, "[UTF7Encoding.GetCharCount]count >=0"); Contract.Assert(bytes != null, "[UTF7Encoding.GetCharCount]bytes!=null"); // Just call GetChars with null char* to do counting return GetChars(bytes, count, null, 0, baseDecoder); } [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { Contract.Assert(byteCount >= 0, "[UTF7Encoding.GetChars]byteCount >=0"); Contract.Assert(bytes != null, "[UTF7Encoding.GetChars]bytes!=null"); Contract.Assert(charCount >= 0, "[UTF7Encoding.GetChars]charCount >=0"); // Might use a decoder UTF7Encoding.Decoder decoder = (UTF7Encoding.Decoder)baseDecoder; // Get our output buffer info. Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer( this, decoder, chars, charCount, bytes, byteCount); // Get decoder info int bits = 0; int bitCount = -1; bool firstByte = false; if (decoder != null) { bits = decoder.bits; bitCount = decoder.bitCount; firstByte = decoder.firstByte; Contract.Assert(firstByte == false || decoder.bitCount <= 0, "[UTF7Encoding.GetChars]If remembered bits, then first byte flag shouldn't be set"); } // We may have had bits in the decoder that we couldn't output last time, so do so now if (bitCount >= 16) { // Check our decoder buffer if (!buffer.AddChar((char)((bits >> (bitCount - 16)) & 0xFFFF))) ThrowCharsOverflow(decoder, true); // Always throw, they need at least 1 char even in Convert // Used this one, clean up extra bits bitCount -= 16; } // Loop through the input while (buffer.MoreData) { byte currentByte = buffer.GetNextByte(); int c; if (bitCount >= 0) { // // Modified base 64 encoding. // sbyte v; if (currentByte < 0x80 && ((v = _base64Values[currentByte]) >= 0)) { firstByte = false; bits = (bits << 6) | ((byte)v); bitCount += 6; if (bitCount >= 16) { c = (bits >> (bitCount - 16)) & 0xFFFF; bitCount -= 16; } // If not enough bits just continue else continue; } else { // If it wasn't a base 64 byte, everything's going to turn off base 64 mode bitCount = -1; if (currentByte != '-') { // >= 0x80 (because of 1st if statemtn) // We need this check since the base64Values[b] check below need b <= 0x7f. // This is not a valid base 64 byte. Terminate the shifted-sequence and // emit this byte. // not in base 64 table // According to the RFC 1642 and the example code of UTF-7 // in Unicode 2.0, we should just zero-extend the invalid UTF7 byte // Chars won't be updated unless this works, try to fallback if (!buffer.Fallback(currentByte)) break; // Stop here, didn't throw // Used that byte, we're done with it continue; } // // The encoding for '+' is "+-". // if (firstByte) c = '+'; // We just turn it off if not emitting a +, so we're done. else continue; } // // End of modified base 64 encoding block. // } else if (currentByte == '+') { // // Found the start of a modified base 64 encoding block or a plus sign. // bitCount = 0; firstByte = true; continue; } else { // Normal character if (currentByte >= 0x80) { // Try to fallback if (!buffer.Fallback(currentByte)) break; // Stop here, didn't throw // Done falling back continue; } // Use the normal character c = currentByte; } if (c >= 0) { // Check our buffer if (!buffer.AddChar((char)c)) { // No room. If it was a plain char we'll try again later. // Note, we'll consume this byte and stick it in decoder, even if we can't output it if (bitCount >= 0) // Can we rememmber this byte (char) { buffer.AdjustBytes(+1); // Need to readd the byte that AddChar subtracted when it failed bitCount += 16; // We'll still need that char we have in our bits } break; // didn't throw, stop } } } // Stick stuff in the decoder if we can (chars == null if counting, so don't store decoder) if (chars != null && decoder != null) { // MustFlush? (Could've been cleared by ThrowCharsOverflow if Convert & didn't reach end of buffer) if (decoder.MustFlush) { // RFC doesn't specify what would happen if we have non-0 leftover bits, we just drop them decoder.bits = 0; decoder.bitCount = -1; decoder.firstByte = false; } else { decoder.bits = bits; decoder.bitCount = bitCount; decoder.firstByte = firstByte; } decoder.m_bytesUsed = buffer.BytesUsed; } // else ignore any hanging bits. // Return our count return buffer.Count; } public override System.Text.Decoder GetDecoder() { return new UTF7Encoding.Decoder(this); } public override System.Text.Encoder GetEncoder() { return new UTF7Encoding.Encoder(this); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Suppose that every char can not be direct-encoded, we know that // a byte can encode 6 bits of the Unicode character. And we will // also need two extra bytes for the shift-in ('+') and shift-out ('-') mark. // Therefore, the max byte should be: // byteCount = 2 + Math.Ceiling((double)charCount * 16 / 6); // That is always <= 2 + 3 * charCount; // Longest case is alternating encoded, direct, encoded data for 5 + 1 + 5... bytes per char. // UTF7 doesn't have left over surrogates, but if no input we may need an output - to turn off // encoding if MustFlush is true. // Its easiest to think of this as 2 bytes to turn on/off the base64 mode, then 3 bytes per char. // 3 bytes is 18 bits of encoding, which is more than we need, but if its direct encoded then 3 // bytes allows us to turn off and then back on base64 mode if necessary. // Note that UTF7 encoded surrogates individually and isn't worried about mismatches, so all // code points are encodable int UTF7. long byteCount = (long)charCount * 3 + 2; // check for overflow if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Worst case is 1 char per byte. Minimum 1 for left over bits in case decoder is being flushed // Also note that we ignore extra bits (per spec), so UTF7 doesn't have unknown in this direction. int charCount = byteCount; if (charCount == 0) charCount = 1; return charCount; } // Of all the amazing things... This MUST be Decoder so that our com name // for System.Text.Decoder doesn't change private class Decoder : DecoderNLS { /*private*/ internal int bits; /*private*/ internal int bitCount; /*private*/ internal bool firstByte; public Decoder(UTF7Encoding encoding) : base(encoding) { // base calls reset } public override void Reset() { this.bits = 0; this.bitCount = -1; this.firstByte = false; if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } // Anything left in our encoder? internal override bool HasState { get { // NOTE: This forces the last -, which some encoder might not encode. If we // don't see it we don't think we're done reading. return (this.bitCount != -1); } } } // Of all the amazing things... This MUST be Encoder so that our com name // for System.Text.Encoder doesn't change private class Encoder : EncoderNLS { /*private*/ internal int bits; /*private*/ internal int bitCount; public Encoder(UTF7Encoding encoding) : base(encoding) { // base calls reset } public override void Reset() { this.bitCount = -1; this.bits = 0; if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } // Anything left in our encoder? internal override bool HasState { get { return (this.bits != 0 || this.bitCount != -1); } } } // Preexisting UTF7 behavior for bad bytes was just to spit out the byte as the next char // and turn off base64 mode if it was in that mode. We still exit the mode, but now we fallback. internal sealed class DecoderUTF7Fallback : DecoderFallback { // Construction. Default replacement fallback uses no best fit and ? replacement string public DecoderUTF7Fallback() { } public override DecoderFallbackBuffer CreateFallbackBuffer() { return new DecoderUTF7FallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { // returns 1 char per bad byte return 1; } } public override bool Equals(Object value) { DecoderUTF7Fallback that = value as DecoderUTF7Fallback; if (that != null) { return true; } return (false); } public override int GetHashCode() { return 984; } } internal sealed class DecoderUTF7FallbackBuffer : DecoderFallbackBuffer { // Store our default string private char _cFallback = (char)0; private int _iCount = -1; private int _iSize; // Construction public DecoderUTF7FallbackBuffer(DecoderUTF7Fallback fallback) { } // Fallback Methods public override bool Fallback(byte[] bytesUnknown, int index) { // We expect no previous fallback in our buffer Contract.Assert(_iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks"); Contract.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte"); // Go ahead and get our fallback _cFallback = (char)bytesUnknown[0]; // Any of the fallback characters can be handled except for 0 if (_cFallback == 0) { return false; } _iCount = _iSize = 1; return true; } public override char GetNextChar() { if (_iCount-- > 0) return _cFallback; // Note: this means that 0 in UTF7 stream will never be emitted. return (char)0; } public override bool MovePrevious() { if (_iCount >= 0) { _iCount++; } // return true if we were allowed to do this return (_iCount >= 0 && _iCount <= _iSize); } // Return # of chars left in this fallback public override int Remaining { get { return (_iCount > 0) ? _iCount : 0; } } // Clear the buffer [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe void Reset() { _iCount = -1; byteStart = null; } // This version just counts the fallback and doesn't actually copy anything. [System.Security.SecurityCritical] // auto-generated internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* { // We expect no previous fallback in our buffer Contract.Assert(_iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks"); if (bytes.Length != 1) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); } // Can't fallback a byte 0, so return for that case, 1 otherwise. return bytes[0] == 0 ? 0 : 1; } } } }
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; using System.Runtime.InteropServices; // ERROR: Not supported in C#: OptionDeclaration // ERROR: Not supported in C#: OptionDeclaration using VB = Microsoft.VisualBasic; using System.Data.OleDb; namespace _4PosBackOffice.NET { internal partial class frmMonthEnd : System.Windows.Forms.Form { [DllImport("kernel32", EntryPoint = "GetComputerNameA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int GetComputerName(string lpBuffer, ref int nSize); const short mdPricingGroup = 0; const short mdDepartment = 1; const short mdPackSize = 2; short gMode; short lCNT; List<GroupBox> frmMode = new List<GroupBox>(); const short mdDayEnd = 0; const short mdTransactions = 1; const short mdConfirm = 2; const short mdComplete = 3; private void loadLanguage() { modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1274; //Month End Run|Checked if (modRecordSet.rsLang.RecordCount){this.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;this.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} //frmMode(0) = No Code [Outstanding Day End Run!] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmMode(0).Caption = rsLang("LanguageLayoutLnk_Description"): frmMode(0).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //Label1(5) = No Code [There is an outstanding day end run.] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Label1(5).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(5).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //Label1(4) = No Code [Please complete the Day End before proceeding with your Month End] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Label1(4).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(4).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004; //Exit|Checked if (modRecordSet.rsLang.RecordCount){cmdBack.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdBack.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1005; //Next| if (modRecordSet.rsLang.RecordCount){cmdNext.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdNext.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} //frmMode(1) = No Code [Outstanding Day End Run] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmMode(1).Caption = rsLang("LanguageLayoutLnk_Description"): frmMode(1).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //Label1(7) = No Code [There have been no Point......] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Label1(7).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(7).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //Note: Grammar wrong in label caption! //Label1(6) = No Code [There is no need to do your Month End Run.] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Label1(6).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(6).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //frmMode(2) = No Code [Confirm Month End Run] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmMode(3).Caption = rsLang("LanguageLayoutLnk_Description"): frmMode(3).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //Label1(1) = No Code [Are you sure you wish to run.......] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Label1(1).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(1).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //Label1(2) = No Code [By pressing 'Next' you will commit the Month End Run.] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Label1(1).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(1).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //frmMode(3) = No Code [Month End Run Complete] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmMode(3).Caption = rsLang("LanguageLayoutLnk_Description"): frmMode(3).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmMonthEnd.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; } private void doMode(ref short mode) { // Dim lNodeList As IXMLDOMNodeList gMode = mode; // Dim lNode As IXMLDOMNode ADODB.Recordset rs = default(ADODB.Recordset); short x = 0; for (x = 0; x <= frmMode.Count - 1; x++) { frmMode[x].Visible = false; } frmMode[gMode].Left = frmMode[0].Left; frmMode[gMode].Top = frmMode[0].Top; frmMode[gMode].Visible = true; ADODB.Recordset rsME = default(ADODB.Recordset); Scripting.TextStream textstreamME = default(Scripting.TextStream); Scripting.FileSystemObject fsoME = new Scripting.FileSystemObject(); switch (gMode) { case mdDayEnd: rs = modRecordSet.getRS(ref "SELECT id FROM (SELECT COUNT(*) AS id FROM company INNER JOIN Sale ON Company.Company_DayEndID = Sale.Sale_DayEndID) transactions"); if (rs.Fields("id").Value) { } else { doMode(ref mdTransactions); return; } this.cmdNext.Enabled = false; break; case mdTransactions: rs = modRecordSet.getRS(ref "SELECT Count(Sale.SaleID) AS id FROM Company INNER JOIN ((Sale INNER JOIN DayEnd ON Sale.Sale_DayEndID = DayEnd.DayEndID) INNER JOIN MonthEnd ON DayEnd.DayEnd_MonthEndID = MonthEnd.MonthEndID) ON Company.Company_MonthEndID = MonthEnd.MonthEndID;"); if (rs.Fields("id").Value) { doMode(ref mdConfirm); return; } //If blMontheEnd = True Then // str1 = "Month End Run failed to run, please try again!!!" & vbCrLf & "If the same problem persist, Consult 4POS for assistance" // MsgBox str1, vbApplicationModal + vbInformation + vbOKOnly, "Month End" //End If this.cmdNext.Enabled = false; break; case mdConfirm: break; case mdComplete: //Set lDOM = modGeneral.lsData.SQL("p4_monthEnd") //modSecurity.checkSecurity //do backup rsME = modRecordSet.getRS(ref "select Company_BackupPath from Company"); if (rsME.RecordCount) { if (!string.IsNullOrEmpty(rsME.Fields("Company_BackupPath").Value)) { if (fsoME.FileExists("C:\\4POSBackup.txt")) fsoME.DeleteFile("C:\\4POSBackup.txt", true); textstreamME = fsoME.OpenTextFile("C:\\4POSBackup.txt", Scripting.IOMode.ForWriting, true); textstreamME.Write(rsME.Fields("Company_BackupPath").Value); textstreamME.Close(); Interaction.Shell("c:\\4pos\\4posbackup.exe", AppWinStyle.NormalFocus); System.Windows.Forms.Application.DoEvents(); } } //do backup this.cmdNext.Visible = false; System.Windows.Forms.Application.DoEvents(); doMonthEnd(); break; } } private void BuildAll() { ADODB.Recordset rs = default(ADODB.Recordset); int x = 0; System.Windows.Forms.Application.DoEvents(); //cnnDB.Execute "UPDATE WarehouseStockItemLnk INNER JOIN (Company INNER JOIN DayEndStockItemLnk ON Company.Company_DayEndID = DayEndStockItemLnk.DayEndStockItemLnk_DayEndID) ON WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID = DayEndStockItemLnk.DayEndStockItemLnk_StockItemID SET DayEndStockItemLnk.DayEndStockItemLnk_Quantity = [DayEndStockItemLnk_QuantitySales]+[WarehouseStockItemLnk_Quantity] WHERE (((WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID)>1));" rs = modRecordSet.getRS(ref "Select * from Company"); for (x = rs.Fields("Company_DayEndID").Value; x >= 0; x += -1) { modRecordSet.cnnDB.Execute("UPDATE DayEndStockItemLnk AS DayEndStockItemLnk_1 INNER JOIN DayEndStockItemLnk ON DayEndStockItemLnk_1.DayEndStockItemLnk_StockItemID = DayEndStockItemLnk.DayEndStockItemLnk_StockItemID SET DayEndStockItemLnk.DayEndStockItemLnk_Quantity = DayEndStockItemLnk_1!DayEndStockItemLnk_Quantity+[DayEndStockItemLnk]![DayEndStockItemLnk_QuantitySales]-[DayEndStockItemLnk]![DayEndStockItemLnk_QuantityGRV]+[DayEndStockItemLnk]![DayEndStockItemLnk_QuantityShrink] WHERE (((DayEndStockItemLnk.DayEndStockItemLnk_DayEndID)=[DayEndStockItemLnk_1]![DayEndStockItemLnk_DayEndID]-1) AND ((DayEndStockItemLnk_1.DayEndStockItemLnk_DayEndID)=" + x + "));"); } } private void doMonthEnd() { string sql = null; string lPath = null; ADODB.Recordset rs = default(ADODB.Recordset); Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); ADODB.Connection dbcnnMonth = default(ADODB.Connection); //fix Server Path in Month End DBs string databaseName = null; this.Cursor = System.Windows.Forms.Cursors.WaitCursor; System.Windows.Forms.Application.DoEvents(); //BuildAll rs = modRecordSet.getRS(ref "SELECT Company_MonthEndID, Company_OpenDebtor From Company"); lPath = modRecordSet.serverPath + "month" + rs.Fields("Company_MonthEndID").Value + ".mdb"; //fix Server Path in Month End DBs databaseName = "month" + rs.Fields("Company_MonthEndID").Value + ".mdb"; sql = "UPDATE Company Set Company.Company_MonthEndID = Company.Company_MonthEndID + 1;"; modRecordSet.cnnDB.Execute(sql); sql = "INSERT INTO MonthEnd ( MonthEndID, MonthEnd_Date, MonthEnd_Days, MonthEnd_BudgetSales, MonthEnd_BudgetPurchases ) SELECT Company.Company_MonthEndID, Now(), 20, 100000, 100000 FROM Company;"; modRecordSet.cnnDB.Execute(sql); modRecordSet.cnnDB.Execute("UPDATE Company INNER JOIN DayEnd ON Company.Company_DayEndID = DayEnd.DayEndID SET DayEnd.DayEnd_MonthEndID = [Company]![Company_MonthEndID];"); fso.CopyFile(modRecordSet.serverPath + "template.mdb", lPath, true); dbcnnMonth = new ADODB.Connection(); var _with1 = dbcnnMonth; _with1.Provider = "Microsoft.ACE.OLEDB.12.0"; _with1.Properties("Jet OLEDB:System Database").Value = "" + modRecordSet.serverPath + "Secured.mdw"; _with1.Open(lPath, "liquid", "lqd"); sql = "UPDATE StockitemHistory SET StockitemHistory.StockitemHistory_Month12 = [StockitemHistory]![StockitemHistory_Month11], StockitemHistory.StockitemHistory_Month11 = [StockitemHistory]![StockitemHistory_Month10], StockitemHistory.StockitemHistory_Month10 = [StockitemHistory]![StockitemHistory_Month9], StockitemHistory.StockitemHistory_Month9 = [StockitemHistory]![StockitemHistory_Month8], StockitemHistory.StockitemHistory_Month8 = [StockitemHistory]![StockitemHistory_Month7], StockitemHistory.StockitemHistory_Month7 = [StockitemHistory]![StockitemHistory_Month6], StockitemHistory.StockitemHistory_Month6 = [StockitemHistory]![StockitemHistory_Month5], StockitemHistory.StockitemHistory_Month5 = [StockitemHistory]![StockitemHistory_Month4], "; sql = sql + "StockitemHistory.StockitemHistory_Month4 = [StockitemHistory]![StockitemHistory_Month3], StockitemHistory.StockitemHistory_Month3 = [StockitemHistory]![StockitemHistory_Month2], StockitemHistory.StockitemHistory_Month2 = [StockitemHistory]![StockitemHistory_Month1], StockitemHistory.StockitemHistory_Month1 = 0;"; modRecordSet.cnnDB.Execute(sql); sql = "INSERT INTO Customer ( CustomerID, Customer_ChannelID, Customer_InvoiceName, Customer_DepartmentName, Customer_FirstName, Customer_Surname, Customer_PhysicalAddress, Customer_PostalAddress, Customer_Telephone, Customer_Fax, Customer_Email, Customer_Disabled, Customer_Terms, Customer_CreditLimit, Customer_Current, Customer_30Days, Customer_60Days, Customer_90Days, Customer_120Days, Customer_150Days, Customer_PrintStatement,Customer_VATNumber ) "; sql = sql + "SELECT M_Customer.CustomerID, M_Customer.Customer_ChannelID, M_Customer.Customer_InvoiceName, M_Customer.Customer_DepartmentName, M_Customer.Customer_FirstName, M_Customer.Customer_Surname, M_Customer.Customer_PhysicalAddress, M_Customer.Customer_PostalAddress, M_Customer.Customer_Telephone, M_Customer.Customer_Fax, M_Customer.Customer_Email, M_Customer.Customer_Disabled, M_Customer.Customer_Terms, M_Customer.Customer_CreditLimit, M_Customer.Customer_Current, M_Customer.Customer_30Days, M_Customer.Customer_60Days, M_Customer.Customer_90Days, M_Customer.Customer_120Days, M_Customer.Customer_150Days, M_Customer.Customer_PrintStatement, M_Customer.Customer_VATNumber FROM M_Customer;"; dbcnnMonth.Execute(sql); sql = "INSERT INTO CustomerTransaction ( CustomerTransactionID, CustomerTransaction_CustomerID, CustomerTransaction_TransactionTypeID, CustomerTransaction_DayEndID, CustomerTransaction_MonthEndID, CustomerTransaction_ReferenceID, CustomerTransaction_Date, CustomerTransaction_Description, CustomerTransaction_Amount, CustomerTransaction_Reference, CustomerTransaction_PersonName, CustomerTransaction_Done, CustomerTransaction_Main, CustomerTransaction_Child, CustomerTransaction_Allocated ) "; sql = sql + "SELECT M_CustomerTransaction.CustomerTransactionID, M_CustomerTransaction.CustomerTransaction_CustomerID, M_CustomerTransaction.CustomerTransaction_TransactionTypeID, M_CustomerTransaction.CustomerTransaction_DayEndID, M_CustomerTransaction.CustomerTransaction_MonthEndID, M_CustomerTransaction.CustomerTransaction_ReferenceID, M_CustomerTransaction.CustomerTransaction_Date, M_CustomerTransaction.CustomerTransaction_Description, M_CustomerTransaction.CustomerTransaction_Amount, M_CustomerTransaction.CustomerTransaction_Reference, M_CustomerTransaction.CustomerTransaction_PersonName, M_CustomerTransaction.CustomerTransaction_Done, M_CustomerTransaction.CustomerTransaction_Main, M_CustomerTransaction.CustomerTransaction_Child, M_CustomerTransaction.CustomerTransaction_Allocated FROM M_CustomerTransaction;"; dbcnnMonth.Execute(sql); sql = "INSERT INTO CustomerTransactionAlloc ( CustomerTransactionAllocID, CustomerTransactionAlloc_CustomerID, CustomerTransactionAlloc_MainID, CustomerTransactionAlloc_ChildID, CustomerTransactionAlloc_Date, CustomerTransactionAlloc_Description, CustomerTransactionAlloc_Amount, CustomerTransactionAlloc_Reference, CustomerTransactionAlloc_PersonName ) "; sql = sql + "SELECT M_CustomerTransactionAlloc.CustomerTransactionAllocID, M_CustomerTransactionAlloc.CustomerTransactionAlloc_CustomerID, M_CustomerTransactionAlloc.CustomerTransactionAlloc_MainID, M_CustomerTransactionAlloc.CustomerTransactionAlloc_ChildID, M_CustomerTransactionAlloc.CustomerTransactionAlloc_Date, M_CustomerTransactionAlloc.CustomerTransactionAlloc_Description, M_CustomerTransactionAlloc.CustomerTransactionAlloc_Amount, M_CustomerTransactionAlloc.CustomerTransactionAlloc_Reference, M_CustomerTransactionAlloc.CustomerTransactionAlloc_PersonName FROM M_CustomerTransactionAlloc;"; dbcnnMonth.Execute(sql); if (rs.Fields("Company_OpenDebtor").Value == true) { //sql = "DELETE M_CustomerTransaction.* FROM M_CustomerTransaction WHERE (((M_CustomerTransaction.CustomerTransaction_Allocated)=[M_CustomerTransaction].[CustomerTransaction_Amount]) AND ((M_CustomerTransaction.CustomerTransaction_Allocated)<>0));" //dbcnnMonth.Execute sql sql = "DELETE M_CustomerTransaction.* FROM M_CustomerTransaction;"; dbcnnMonth.Execute(sql); //version 1 problem //sql = "INSERT INTO M_CustomerTransaction ( CustomerTransaction_CustomerID, CustomerTransaction_TransactionTypeID, CustomerTransaction_DayEndID, CustomerTransaction_MonthEndID, CustomerTransaction_ReferenceID, CustomerTransaction_Date, CustomerTransaction_Description, CustomerTransaction_Amount, CustomerTransaction_Reference, CustomerTransaction_PersonName, CustomerTransaction_Done, CustomerTransaction_Main, CustomerTransaction_Child, CustomerTransaction_Allocated ) " //sql = sql & "SELECT CustomerTransaction.CustomerTransaction_CustomerID, CustomerTransaction.CustomerTransaction_TransactionTypeID, CustomerTransaction.CustomerTransaction_DayEndID, CustomerTransaction.CustomerTransaction_MonthEndID, CustomerTransaction.CustomerTransaction_ReferenceID, CustomerTransaction.CustomerTransaction_Date, CustomerTransaction.CustomerTransaction_Description, (CustomerTransaction.CustomerTransaction_Amount-CustomerTransaction.CustomerTransaction_Allocated) AS SumOfCustomerTransaction_Amount, CustomerTransaction.CustomerTransaction_Reference & ' B/F' AS ref, CustomerTransaction.CustomerTransaction_PersonName, CustomerTransaction.CustomerTransaction_Done, CustomerTransaction.CustomerTransaction_Main, CustomerTransaction.CustomerTransaction_Child, CustomerTransaction.CustomerTransaction_Allocated " //sql = sql & "From CustomerTransaction WHERE (((CustomerTransaction.CustomerTransaction_Allocated)<>[CustomerTransaction].[CustomerTransaction_Amount])) AND (((CustomerTransaction.CustomerTransaction_Allocated)<>0));" //dbcnnMonth.Execute sql //version 2 //sql = "INSERT INTO M_CustomerTransaction ( CustomerTransaction_CustomerID, CustomerTransaction_TransactionTypeID, CustomerTransaction_DayEndID, CustomerTransaction_MonthEndID, CustomerTransaction_ReferenceID, CustomerTransaction_Date, CustomerTransaction_Description, CustomerTransaction_Amount, CustomerTransaction_Reference, CustomerTransaction_PersonName, CustomerTransaction_Done ) " //sql = sql & "SELECT CustomerTransaction.CustomerTransaction_CustomerID, CustomerTransaction.CustomerTransaction_TransactionTypeID, M_Company.Company_DayEndID, M_Company.Company_MonthEndID, CustomerTransaction.CustomerTransaction_ReferenceID, CustomerTransaction.CustomerTransaction_Date, CustomerTransaction.CustomerTransaction_Description, (CustomerTransaction.CustomerTransaction_Amount-CustomerTransaction.CustomerTransaction_Allocated) AS SumOfCustomerTransaction_Amount, CustomerTransaction.CustomerTransaction_Reference & '" & " *" & "' AS ref, CustomerTransaction.CustomerTransaction_PersonName, CustomerTransaction.CustomerTransaction_Done " //sql = sql & "FROM CustomerTransaction, M_Company WHERE (((CustomerTransaction.CustomerTransaction_Allocated)<>[CustomerTransaction].[CustomerTransaction_Amount])) ORDER BY CustomerTransaction.CustomerTransactionID;" //dbcnnMonth.Execute sql //version 3 sql = "INSERT INTO M_CustomerTransaction ( CustomerTransaction_CustomerID, CustomerTransaction_TransactionTypeID, CustomerTransaction_DayEndID, CustomerTransaction_MonthEndID, CustomerTransaction_ReferenceID, CustomerTransaction_Date, CustomerTransaction_Description, CustomerTransaction_Amount, CustomerTransaction_Reference, CustomerTransaction_PersonName, CustomerTransaction_Done ) "; sql = sql + "SELECT CustomerTransaction.CustomerTransaction_CustomerID, CustomerTransaction.CustomerTransaction_TransactionTypeID, CustomerTransaction.CustomerTransaction_DayEndID, CustomerTransaction.CustomerTransaction_MonthEndID, CustomerTransaction.CustomerTransaction_ReferenceID, CustomerTransaction.CustomerTransaction_Date, CustomerTransaction.CustomerTransaction_Description, (CustomerTransaction.CustomerTransaction_Amount-CustomerTransaction.CustomerTransaction_Allocated) AS SumOfCustomerTransaction_Amount, CustomerTransaction.CustomerTransaction_Reference & '" + " *" + "' AS ref, CustomerTransaction.CustomerTransaction_PersonName, CustomerTransaction.CustomerTransaction_Done "; sql = sql + "FROM CustomerTransaction WHERE (((CustomerTransaction.CustomerTransaction_Allocated)<>[CustomerTransaction].[CustomerTransaction_Amount])) ORDER BY CustomerTransaction.CustomerTransactionID;"; dbcnnMonth.Execute(sql); } else { //DO THE OLD WAY sql = "DELETE M_CustomerTransaction.* FROM M_CustomerTransaction;"; dbcnnMonth.Execute(sql); sql = "INSERT INTO M_CustomerTransaction ( CustomerTransaction_CustomerID, CustomerTransaction_TransactionTypeID, CustomerTransaction_DayEndID, CustomerTransaction_MonthEndID, CustomerTransaction_ReferenceID, CustomerTransaction_Date, CustomerTransaction_Description, CustomerTransaction_Amount, CustomerTransaction_Reference, CustomerTransaction_PersonName ) SELECT CustomerTransaction.CustomerTransaction_CustomerID, 7 AS transType, M_Company.Company_DayEndID, M_Company.Company_MonthEndID, 0 AS reference, Now() AS [date], '' AS [desc], Sum(CustomerTransaction.CustomerTransaction_Amount) AS SumOfCustomerTransaction_Amount, 'Month End' AS ref, 'System' AS person From CustomerTransaction, M_Company GROUP BY CustomerTransaction.CustomerTransaction_CustomerID, M_Company.Company_DayEndID, M_Company.Company_MonthEndID;"; dbcnnMonth.Execute(sql); } sql = "UPDATE M_Customer SET M_Customer.Customer_150Days = [M_Customer]![Customer_150Days]+[M_Customer]![Customer_120Days], M_Customer.Customer_120Days = [M_Customer]![Customer_90Days], M_Customer.Customer_90Days = [M_Customer]![Customer_60Days], M_Customer.Customer_60Days = [M_Customer]![Customer_30Days], M_Customer.Customer_30Days = [M_Customer]![Customer_Current], M_Customer.Customer_Current = 0;"; dbcnnMonth.Execute(sql); //Debtor Age shifting if Credit dbcnnMonth.Execute("UPDATE M_Customer SET M_Customer.Customer_120Days = iif(([M_Customer]![Customer_150Days]<0),([M_Customer]![Customer_120Days]+[M_Customer]![Customer_150Days]),[M_Customer]![Customer_120Days]);"); dbcnnMonth.Execute("UPDATE M_Customer SET M_Customer.Customer_150Days = iif(([M_Customer]![Customer_150Days]<0),0,[M_Customer]![Customer_150Days]);"); dbcnnMonth.Execute("UPDATE M_Customer SET M_Customer.Customer_90Days = iif(([M_Customer]![Customer_120Days]<0),([M_Customer]![Customer_90Days]+[M_Customer]![Customer_120Days]),[M_Customer]![Customer_90Days]);"); dbcnnMonth.Execute("UPDATE M_Customer SET M_Customer.Customer_120Days = iif(([M_Customer]![Customer_120Days]<0),0,[M_Customer]![Customer_120Days]);"); dbcnnMonth.Execute("UPDATE M_Customer SET M_Customer.Customer_60Days = iif(([M_Customer]![Customer_90Days]<0),([M_Customer]![Customer_60Days]+[M_Customer]![Customer_90Days]),[M_Customer]![Customer_60Days]);"); dbcnnMonth.Execute("UPDATE M_Customer SET M_Customer.Customer_90Days = iif(([M_Customer]![Customer_90Days]<0),0,[M_Customer]![Customer_90Days]);"); dbcnnMonth.Execute("UPDATE M_Customer SET M_Customer.Customer_30Days = iif(([M_Customer]![Customer_60Days]<0),([M_Customer]![Customer_30Days]+[M_Customer]![Customer_60Days]),[M_Customer]![Customer_30Days]);"); dbcnnMonth.Execute("UPDATE M_Customer SET M_Customer.Customer_60Days = iif(([M_Customer]![Customer_60Days]<0),0,[M_Customer]![Customer_60Days]);"); dbcnnMonth.Execute("UPDATE M_Customer SET M_Customer.Customer_Current = iif(([M_Customer]![Customer_30Days]<0),([M_Customer]![Customer_Current]+[M_Customer]![Customer_30Days]),[M_Customer]![Customer_Current]);"); dbcnnMonth.Execute("UPDATE M_Customer SET M_Customer.Customer_30Days = iif(([M_Customer]![Customer_30Days]<0),0,[M_Customer]![Customer_30Days]);"); //Debtor Age shifting if Credit //Tranfer change sql = "INSERT INTO DayEndStockItemLnk ( DayEndStockItemLnk_DayEndID, DayEndStockItemLnk_StockItemID, DayEndStockItemLnk_Quantity, DayEndStockItemLnk_QuantitySales, DayEndStockItemLnk_QuantityShrink, DayEndStockItemLnk_QuantityGRV, DayEndStockItemLnk_ListCost, DayEndStockItemLnk_ActualCost, DayEndStockItemLnk_Warehouse ) SELECT M_DayEndStockItemLnk.DayEndStockItemLnk_DayEndID, M_DayEndStockItemLnk.DayEndStockItemLnk_StockItemID, M_DayEndStockItemLnk.DayEndStockItemLnk_Quantity, M_DayEndStockItemLnk.DayEndStockItemLnk_QuantitySales, M_DayEndStockItemLnk.DayEndStockItemLnk_QuantityShrink, M_DayEndStockItemLnk.DayEndStockItemLnk_QuantityGRV, M_DayEndStockItemLnk.DayEndStockItemLnk_ListCost, M_DayEndStockItemLnk.DayEndStockItemLnk_ActualCost, M_DayEndStockItemLnk.DayEndStockItemLnk_Warehouse From M_DayEndStockItemLnk, M_Company WHERE (((M_DayEndStockItemLnk.DayEndStockItemLnk_DayEndID)<>[M_Company]![Company_DayEndID]));" sql = "INSERT INTO DayEndStockItemLnk ( DayEndStockItemLnk_DayEndID, DayEndStockItemLnk_StockItemID, DayEndStockItemLnk_Quantity, DayEndStockItemLnk_QuantitySales, DayEndStockItemLnk_QuantityShrink, DayEndStockItemLnk_QuantityGRV, DayEndStockItemLnk_QuantityTransafer, DayEndStockItemLnk_ListCost, DayEndStockItemLnk_ActualCost, DayEndStockItemLnk_Warehouse ) SELECT M_DayEndStockItemLnk.DayEndStockItemLnk_DayEndID, M_DayEndStockItemLnk.DayEndStockItemLnk_StockItemID, M_DayEndStockItemLnk.DayEndStockItemLnk_Quantity, M_DayEndStockItemLnk.DayEndStockItemLnk_QuantitySales, M_DayEndStockItemLnk.DayEndStockItemLnk_QuantityShrink, M_DayEndStockItemLnk.DayEndStockItemLnk_QuantityGRV, M_DayEndStockItemLnk.DayEndStockItemLnk_QuantityTransafer, M_DayEndStockItemLnk.DayEndStockItemLnk_ListCost, M_DayEndStockItemLnk.DayEndStockItemLnk_ActualCost, M_DayEndStockItemLnk.DayEndStockItemLnk_Warehouse "; sql = sql + "From M_DayEndStockItemLnk, M_Company WHERE (((M_DayEndStockItemLnk.DayEndStockItemLnk_DayEndID)<>[M_Company]![Company_DayEndID]));"; dbcnnMonth.Execute(sql); sql = "DELETE M_DayEndStockItemLnk.* From M_DayEndStockItemLnk, M_Company WHERE (((M_DayEndStockItemLnk.DayEndStockItemLnk_DayEndID)<>[M_Company]![Company_DayEndID]));"; dbcnnMonth.Execute(sql); //Tranfer change sql = "INSERT INTO StockTransferWH ( StockTransferWH_Date, StockTransferWH_DayEndID, StockTransferWH_PersonID, StockTransferWH_WHFrom, StockTransferWH_WHTo, StockTransferWH_StockItemID, StockTransferWH_Qty ) SELECT M_StockTransferWH.StockTransferWH_Date, M_StockTransferWH.StockTransferWH_DayEndID, M_StockTransferWH.StockTransferWH_PersonID, M_StockTransferWH.StockTransferWH_WHFrom, M_StockTransferWH.StockTransferWH_WHTo, M_StockTransferWH.StockTransferWH_StockItemID, M_StockTransferWH.StockTransferWH_Qty "; sql = sql + "From M_StockTransferWH, M_Company WHERE (((M_StockTransferWH.StockTransferWH_DayEndID)<>[M_Company]![Company_DayEndID]));"; dbcnnMonth.Execute(sql); sql = "DELETE M_StockTransferWH.* From M_StockTransferWH, M_Company WHERE (((M_StockTransferWH.StockTransferWH_DayEndID)<>[M_Company]![Company_DayEndID]));"; dbcnnMonth.Execute(sql); //Tranfer change sql = "INSERT INTO Declaration ( DeclarationID, Declaration_POSID, Declaration_DayEndID, Declaration_Date, Declaration_Cash, Declaration_CashServer, Declaration_CashCount, Declaration_Cheque, Declaration_ChequeServer, Declaration_ChequeCount, Declaration_Card, Declaration_CardServer, Declaration_CardCount, Declaration_Payout, Declaration_PayoutServer, Declaration_PayoutCount, Declaration_Total, Declaration_TotalServer, Declaration_TotalCount ) "; sql = sql + "SELECT M_Declaration.DeclarationID, M_Declaration.Declaration_POSID, M_Declaration.Declaration_DayEndID, M_Declaration.Declaration_Date, M_Declaration.Declaration_Cash, M_Declaration.Declaration_CashServer, M_Declaration.Declaration_CashCount, M_Declaration.Declaration_Cheque, M_Declaration.Declaration_ChequeServer, M_Declaration.Declaration_ChequeCount, M_Declaration.Declaration_Card, M_Declaration.Declaration_CardServer, M_Declaration.Declaration_CardCount, M_Declaration.Declaration_Payout, M_Declaration.Declaration_PayoutServer, M_Declaration.Declaration_PayoutCount, M_Declaration.Declaration_Total, M_Declaration.Declaration_TotalServer, M_Declaration.Declaration_TotalCount FROM M_Declaration;"; dbcnnMonth.Execute(sql); sql = "DELETE M_Declaration.* FROM M_Declaration;"; dbcnnMonth.Execute(sql); sql = "INSERT INTO Sale ( SaleID, Sale_PosID, Sale_DeclarationID, Sale_ChannelID, Sale_PersonID, Sale_ManagerID, Sale_DayEndID, Sale_Date, Sale_DatePOS, Sale_SubTotal, Sale_Discount, Sale_Total, Sale_Tender, Sale_Slip, Sale_PaymentType, Sale_Reference,Sale_CardRef,Sale_OrderRef,Sale_SerialRef,Sale_Cash,Sale_Card,Sale_Cheque,Sale_CDebit,Sale_PersonShiftID,Sale_TableNumber,Sale_GuestCount,Sale_SlipCount,Sale_Gratuity,Sale_DisChk,Sale_SaleChk ) "; sql = sql + "SELECT M_Sale.SaleID, M_Sale.Sale_PosID, M_Sale.Sale_DeclarationID, M_Sale.Sale_ChannelID, M_Sale.Sale_PersonID, M_Sale.Sale_ManagerID, M_Sale.Sale_DayEndID, M_Sale.Sale_Date, M_Sale.Sale_DatePOS, M_Sale.Sale_SubTotal, M_Sale.Sale_Discount, M_Sale.Sale_Total, M_Sale.Sale_Tender, M_Sale.Sale_Slip, M_Sale.Sale_PaymentType, Sale_Reference,M_Sale.Sale_CardRef,M_Sale.Sale_OrderRef,M_Sale.Sale_SerialRef, M_Sale.Sale_Cash,M_Sale.Sale_Card,M_Sale.Sale_Cheque,M_Sale.Sale_CDebit,M_Sale.Sale_PersonShiftID,M_Sale.Sale_TableNumber,M_Sale.Sale_GuestCount,M_Sale.Sale_SlipCount,M_Sale.Sale_Gratuity,M_Sale.Sale_DisChk,M_Sale.Sale_SaleChk FROM M_Sale;"; dbcnnMonth.Execute(sql); sql = "INSERT INTO SaleItem ( SaleItemID, SaleItem_SaleID, SaleItem_StockItemID, SaleItem_ShrinkQuantity, SaleItem_Quantity, SaleItem_LineNo, SaleItem_Vat, SaleItem_PriceOriginal, SaleItem_Price, SaleItem_Revoke, SaleItem_Reversal, SaleItem_DepositType, SaleItem_DepositCost, SaleItem_ActualCost, SaleItem_ListCost, SaleItem_SetID, SaleItem_WarehouseID ) SELECT M_SaleItem.SaleItemID, M_SaleItem.SaleItem_SaleID, M_SaleItem.SaleItem_StockItemID, M_SaleItem.SaleItem_ShrinkQuantity, M_SaleItem.SaleItem_Quantity, M_SaleItem.SaleItem_LineNo, M_SaleItem.SaleItem_Vat, M_SaleItem.SaleItem_PriceOriginal, M_SaleItem.SaleItem_Price, M_SaleItem.SaleItem_Revoke, M_SaleItem.SaleItem_Reversal, M_SaleItem.SaleItem_DepositType, M_SaleItem.SaleItem_DepositCost, M_SaleItem.SaleItem_ActualCost, M_SaleItem.SaleItem_ListCost, M_SaleItem.SaleItem_SetID, M_SaleItem.SaleItem_WarehouseID FROM M_SaleItem;"; dbcnnMonth.Execute(sql); sql = "INSERT INTO SaleItemReciept ( SaleItemReciept_SaleItemID, SaleItemReciept_StockitemID, SaleItemReciept_Quantity, SaleItemReciept_DepositCost, SaleItemReciept_ListCost, SaleItemReciept_ActualCost, SaleItemReciept_Price ) SELECT M_SaleItemReciept.SaleItemReciept_SaleItemID, M_SaleItemReciept.SaleItemReciept_StockitemID, M_SaleItemReciept.SaleItemReciept_Quantity, M_SaleItemReciept.SaleItemReciept_DepositCost, M_SaleItemReciept.SaleItemReciept_ListCost, M_SaleItemReciept.SaleItemReciept_ActualCost, M_SaleItemReciept.SaleItemReciept_Price FROM M_SaleItemReciept;"; dbcnnMonth.Execute(sql); sql = "DELETE M_SaleItemReciept.* FROM M_SaleItemReciept;"; dbcnnMonth.Execute(sql); sql = "DELETE M_SaleItem.* FROM M_SaleItem;"; dbcnnMonth.Execute(sql); sql = "DELETE M_Sale.* FROM M_Sale;"; dbcnnMonth.Execute(sql); sql = "INSERT INTO Supplier ( SupplierID, Supplier_SystemID, Supplier_Name, Supplier_PostalAddress, Supplier_PhysicalAddress, Supplier_Telephone, Supplier_Facimile, Supplier_RepresentativeName, Supplier_RepresentativeNumber, Supplier_ShippingCode, Supplier_OrderAttentionLine, Supplier_Terms, Supplier_Ullage, Supplier_discountCOD, Supplier_discount15days, Supplier_discount30days, Supplier_discount60days, Supplier_discount90days, Supplier_discount120days, Supplier_discountSmartCard, Supplier_discountDefault, Supplier_Current, Supplier_30Days, Supplier_60Days, Supplier_90Days, Supplier_120Days, Supplier_GRVtype ) "; sql = sql + "SELECT M_Supplier.SupplierID, M_Supplier.Supplier_SystemID, M_Supplier.Supplier_Name, M_Supplier.Supplier_PostalAddress, M_Supplier.Supplier_PhysicalAddress, M_Supplier.Supplier_Telephone, M_Supplier.Supplier_Facimile, M_Supplier.Supplier_RepresentativeName, M_Supplier.Supplier_RepresentativeNumber, M_Supplier.Supplier_ShippingCode, M_Supplier.Supplier_OrderAttentionLine, M_Supplier.Supplier_Terms, M_Supplier.Supplier_Ullage, M_Supplier.Supplier_discountCOD, M_Supplier.Supplier_discount15days, M_Supplier.Supplier_discount30days, M_Supplier.Supplier_discount60days, M_Supplier.Supplier_discount90days, M_Supplier.Supplier_discount120days, M_Supplier.Supplier_discountSmartCard, M_Supplier.Supplier_discountDefault, M_Supplier.Supplier_Current, M_Supplier.Supplier_30Days, M_Supplier.Supplier_60Days, M_Supplier.Supplier_90Days, M_Supplier.Supplier_120Days, M_Supplier.Supplier_GRVtype FROM M_Supplier;"; dbcnnMonth.Execute(sql); sql = "INSERT INTO SupplierTransaction ( SupplierTransactionID, SupplierTransaction_SupplierID, SupplierTransaction_PersonID, SupplierTransaction_TransactionTypeID, SupplierTransaction_MonthEndID, SupplierTransaction_MonthEndIDFor, SupplierTransaction_DayEndID, SupplierTransaction_ReferenceID, SupplierTransaction_Date, SupplierTransaction_Description, SupplierTransaction_Amount, SupplierTransaction_Reference ) "; sql = sql + "SELECT M_SupplierTransaction.SupplierTransactionID, M_SupplierTransaction.SupplierTransaction_SupplierID, M_SupplierTransaction.SupplierTransaction_PersonID, M_SupplierTransaction.SupplierTransaction_TransactionTypeID, M_SupplierTransaction.SupplierTransaction_MonthEndID, M_SupplierTransaction.SupplierTransaction_MonthEndIDFor, M_SupplierTransaction.SupplierTransaction_DayEndID, M_SupplierTransaction.SupplierTransaction_ReferenceID, M_SupplierTransaction.SupplierTransaction_Date, M_SupplierTransaction.SupplierTransaction_Description, M_SupplierTransaction.SupplierTransaction_Amount, M_SupplierTransaction.SupplierTransaction_Reference FROM M_SupplierTransaction;"; dbcnnMonth.Execute(sql); sql = "DELETE M_SupplierTransaction.* FROM M_SupplierTransaction;"; dbcnnMonth.Execute(sql); //********************* sql = "INSERT INTO M_SupplierTransaction ( SupplierTransaction_SupplierID, SupplierTransaction_PersonID, SupplierTransaction_TransactionTypeID, SupplierTransaction_MonthEndID, SupplierTransaction_MonthEndIDFor, SupplierTransaction_DayEndID, SupplierTransaction_ReferenceID, SupplierTransaction_Date, SupplierTransaction_Description, SupplierTransaction_Amount, SupplierTransaction_Reference ) SELECT SupplierTransaction.SupplierTransaction_SupplierID, 1 AS person, 7 AS tranType, M_Company.Company_MonthEndID, M_Company.Company_MonthEndID, M_Company.Company_DayEndID, 0 AS refID, Now() AS [date], '' AS [desc], Sum(SupplierTransaction.SupplierTransaction_Amount) AS SumOfSupplierTransaction_Amount, 'Month End' AS ref From SupplierTransaction, M_Company GROUP BY SupplierTransaction.SupplierTransaction_SupplierID, M_Company.Company_MonthEndID, M_Company.Company_MonthEndID, M_Company.Company_DayEndID;"; dbcnnMonth.Execute(sql); sql = "UPDATE M_Supplier SET M_Supplier.Supplier_120Days = [M_Supplier]![Supplier_120Days]+[M_Supplier]![Supplier_90Days], M_Supplier.Supplier_90Days = [M_Supplier]![Supplier_60Days], M_Supplier.Supplier_60Days = [M_Supplier]![Supplier_30Days], M_Supplier.Supplier_30Days = [M_Supplier]![Supplier_Current], M_Supplier.Supplier_Current = 0;"; dbcnnMonth.Execute(sql); //Debtor Age shifting if Credit //dbcnnMonth.Execute "UPDATE M_Supplier SET M_Supplier.Supplier_120Days = iif(([M_Supplier]![Supplier_150Days]<0),([M_Supplier]![Supplier_120Days]+[M_Supplier]![Supplier_150Days]),[M_Supplier]![Supplier_120Days]);" //dbcnnMonth.Execute "UPDATE M_Supplier SET M_Supplier.Supplier_150Days = iif(([M_Supplier]![Supplier_150Days]<0),0,[M_Supplier]![Supplier_150Days]);" dbcnnMonth.Execute("UPDATE M_Supplier SET M_Supplier.Supplier_90Days = iif(([M_Supplier]![Supplier_120Days]<0),([M_Supplier]![Supplier_90Days]+[M_Supplier]![Supplier_120Days]),[M_Supplier]![Supplier_90Days]);"); dbcnnMonth.Execute("UPDATE M_Supplier SET M_Supplier.Supplier_120Days = iif(([M_Supplier]![Supplier_120Days]<0),0,[M_Supplier]![Supplier_120Days]);"); dbcnnMonth.Execute("UPDATE M_Supplier SET M_Supplier.Supplier_60Days = iif(([M_Supplier]![Supplier_90Days]<0),([M_Supplier]![Supplier_60Days]+[M_Supplier]![Supplier_90Days]),[M_Supplier]![Supplier_60Days]);"); dbcnnMonth.Execute("UPDATE M_Supplier SET M_Supplier.Supplier_90Days = iif(([M_Supplier]![Supplier_90Days]<0),0,[M_Supplier]![Supplier_90Days]);"); dbcnnMonth.Execute("UPDATE M_Supplier SET M_Supplier.Supplier_30Days = iif(([M_Supplier]![Supplier_60Days]<0),([M_Supplier]![Supplier_30Days]+[M_Supplier]![Supplier_60Days]),[M_Supplier]![Supplier_30Days]);"); dbcnnMonth.Execute("UPDATE M_Supplier SET M_Supplier.Supplier_60Days = iif(([M_Supplier]![Supplier_60Days]<0),0,[M_Supplier]![Supplier_60Days]);"); dbcnnMonth.Execute("UPDATE M_Supplier SET M_Supplier.Supplier_Current = iif(([M_Supplier]![Supplier_30Days]<0),([M_Supplier]![Supplier_Current]+[M_Supplier]![Supplier_30Days]),[M_Supplier]![Supplier_Current]);"); dbcnnMonth.Execute("UPDATE M_Supplier SET M_Supplier.Supplier_30Days = iif(([M_Supplier]![Supplier_30Days]<0),0,[M_Supplier]![Supplier_30Days]);"); //Debtor Age shifting if Credit this.Cursor = System.Windows.Forms.Cursors.Default; //fix Server Path in Month End DBs ADODB.Recordset rsPOSList = default(ADODB.Recordset); string strSvrName = null; //Create a buffer strSvrName = new string(Strings.Chr(0), 255); //Get the computer name GetComputerName(strSvrName, ref 255); //remove the unnecessary chr$(0)'s strSvrName = Strings.Left(strSvrName, Strings.InStr(1, strSvrName, Strings.Chr(0))); strSvrName = Strings.Left(strSvrName, Strings.Len(strSvrName) - 1); //MsgBox strSvrName rsPOSList = modRecordSet.getRS(ref "SELECT * FROM POS;"); if (rsPOSList.RecordCount > 1) { //if more then 1 POS //Set rsMonthList = getRS("SELECT MonthEndID FROM MonthEnd;") //If rsMonthList.RecordCount Then // Do While rsMonthList.EOF = False // databaseName = "Month" & rsMonthList("MonthEndID") & ".mdb" if (fso.FileExists(modRecordSet.serverPath + databaseName)) { buildPath1_Month(ref databaseName, ref strSvrName); System.Windows.Forms.Application.DoEvents(); buildPath1_Month(ref databaseName, ref strSvrName); } // rsMonthList.moveNext // Loop //End If } //fix Server Path in Month End DBs //If rs("Company_OpenDebtor") = True Then //Else // If MsgBox("Would you like to Enable 'OPEN DEBTOR' option from starting month?" & vbCrLf & vbCrLf & "NOTE: It is recommended to turn this option now if you wish to use." & vbCrLf & vbCrLf & "You can enable it later from 'Store Setup and Security -> General Parameters'.", vbYesNo) = vbYes Then // sql = "UPDATE Company Set Company.Company_OpenDebtor = True;" // cnnDB.Execute sql // End If //End If //For Auto UpdatePOS on MonthEnd if (Interaction.MsgBox("You are requested to do UpdatePOS at this stage, to run some Reports." + Constants.vbCrLf + Constants.vbCrLf + "NOTE: If you have changed Prices for some items, UpdatePOS will update Terminals." + Constants.vbCrLf + Constants.vbCrLf + "If you want to Run UpdatePOS now select 'YES' or click 'NO' If you don't want to change the prices on terminals.", MsgBoxStyle.YesNo) == MsgBoxResult.Yes) { modApplication.blMEndUpdatePOS = true; My.MyProject.Forms.frmUpdatePOScriteria.ShowDialog(); } else { modApplication.blMEndUpdatePOS = false; } modApplication.blMEndUpdatePOS = false; } private bool buildPath1_Month(ref string lPath, ref string lServerPath) { bool functionReturnValue = false; ADOX.Catalog cat = new ADOX.Catalog(); ADOX.Table tbl = new ADOX.Table(); ADODB.Recordset rs = default(ADODB.Recordset); ADODB.Connection cn = default(ADODB.Connection); string lFile = null; string holdfile = null; short x = 0; Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); string lDir = null; // ERROR: Not supported in C#: OnErrorStatement Cursor = System.Windows.Forms.Cursors.WaitCursor; //lPath = upgradePath System.Windows.Forms.Application.DoEvents(); lDir = Strings.LCase("\\\\" + lServerPath + "\\C\\4posServer\\"); cn = modRecordSet.openConnectionInstance(ref lPath); if (cn == null) { } else { cat.let_ActiveConnection(cn); foreach ( tbl in cat.Tables) { if (tbl.Type == "LINK") { System.Windows.Forms.Application.DoEvents(); //lFile = tbl.Name if (tbl.Properties("Jet OLEDB:Link Datasource").Value != lDir + "pricing.mdb") { tbl.Properties("Jet OLEDB:Link Datasource").Value = Strings.Replace(Strings.LCase(tbl.Properties("Jet OLEDB:Link Datasource").Value), Strings.LCase("C:\\4posServer\\"), lDir); } //DoEvents //If tbl.Properties("Jet OLEDB:Link Datasource") <> lDIR & "pricing.mdb" Then // tbl.Properties("Jet OLEDB:Link Datasource") = Replace(LCase(tbl.Properties("Jet OLEDB:Link Datasource")), LCase("C:\4posServer\"), lDIR) //End If } } //UPGRADE_NOTE: Object cat may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"' cat = null; cn.Close(); //UPGRADE_NOTE: Object cn may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"' cn = null; cat = new ADOX.Catalog(); } System.Windows.Forms.Application.DoEvents(); Cursor = System.Windows.Forms.Cursors.Default; functionReturnValue = true; return functionReturnValue; buildPath_Error: Cursor = System.Windows.Forms.Cursors.Default; Interaction.MsgBox(Err().Description); functionReturnValue = false; return functionReturnValue; } private void cmdBack_Click(System.Object eventSender, System.EventArgs eventArgs) { this.Close(); } private void cmdNext_Click(System.Object eventSender, System.EventArgs eventArgs) { switch (gMode) { case mdDayEnd: doMode(ref mdConfirm); break; case mdConfirm: doMode(ref mdComplete); break; } } private void frmMonthEnd_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); if (KeyAscii == 27) { KeyAscii = 0; cmdBack_Click(cmdBack, new System.EventArgs()); } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void frmMonthEnd_Load(System.Object eventSender, System.EventArgs eventArgs) { Width = sizeConvertors.twipsToPixels(sizeConvertors.pixelToTwips(this.frmMode[0].Left, true) + sizeConvertors.pixelToTwips(frmMode[0].Width, true) + 250, true); Height = sizeConvertors.twipsToPixels(sizeConvertors.pixelToTwips(this.cmdBack.Top, false) + sizeConvertors.pixelToTwips(cmdBack.Height, false) + 250 + 240, false); frmMode.AddRange(new GroupBox[] { _frmMode_0, _frmMode_1, _frmMode_2, _frmMode_3 }); loadLanguage(); doMode(ref mdDayEnd); } } }
using System; using System.Collections.Generic; using System.Linq; using Core; using Entities; using IrrlichtNETCP; namespace Game { /// <summary> /// Handles the collisions of the game /// </summary> internal static class CollisionManager { private static Dictionary<Entity, long> _respawnDictionary; static CollisionManager() { _respawnDictionary = new Dictionary<Entity, long>(); } internal static bool CanMoveBetween(Vector3D start, Vector3D end) { Line3D line = new Line3D(start, end); foreach (var wallNode in SceneNodeManager.WallSceneNodes) { if (IntersectsWithLine(wallNode.BoundingBox, line)) return false; } foreach (var customEntity in SceneNodeManager.CustomEntities.Where(e => e.IsObstacle)) { if (IntersectsWithLine(customEntity.BoundingBox, line)) return false; } return true; } internal static bool EntityVisible(Entity origin, Entity target) { Vector3D[] originEdges = null; origin.BoundingBox.GetEdges(out originEdges); Vector3D[] targetEdges = null; target.BoundingBox.GetEdges(out targetEdges); foreach (var originEdge in originEdges) { foreach (var targetEdge in targetEdges) { Line3D line = new Line3D(originEdge, targetEdge); DebugRenderer.DrawLine3D(line, Color.Red); foreach (var wallNode in SceneNodeManager.WallSceneNodes) { if (IntersectsWithLine(wallNode.BoundingBox, line)) return false; } } } return true; } private static bool IntersectsWithLine(Box3D box, Line3D line) { Vector3D lineVector = line.Vector.Normalize(); float halfLength = (float)(line.Length * 0.5); Vector3D t = box.Center - line.Middle; Vector3D e = (box.MaxEdge - box.MinEdge); e = e * (float)(0.5); if ((Math.Abs(t.X) > e.X + halfLength * Math.Abs(lineVector.X)) || (Math.Abs(t.Y) > e.Y + halfLength * Math.Abs(lineVector.Y)) || (Math.Abs(t.Z) > e.Z + halfLength * Math.Abs(lineVector.Z))) return false; float r = e.Y * (float)Math.Abs(lineVector.Z) + e.Z * Math.Abs(lineVector.Y); if (Math.Abs(t.Y * lineVector.Z - t.Z * lineVector.Y) > r) return false; r = e.X * (float)Math.Abs(lineVector.Z) + e.Z * Math.Abs(lineVector.X); if (Math.Abs(t.Z * lineVector.X - t.X * lineVector.Z) > r) return false; r = e.X * (float)Math.Abs(lineVector.Y) + e.Y * Math.Abs(lineVector.X); if (Math.Abs(t.X * lineVector.Y - t.Y * lineVector.X) > r) return false; return true; } internal static void CheckProjectileCollisions(CombatEntity entity) { List<ProjectileEntity> projectilesToRemove = new List<ProjectileEntity>(); foreach (ProjectileEntity projectile in CombatManager.ProjectileList) { if (projectile.BoundingBox.IntersectsWithBox(entity.BoundingBox)) //Hits entity { if (entity != projectile.Owner) //Entity did not hit itself { SoundManager.PlayPain(); entity.Health -= (int)(projectile.DamageDealt * projectile.Owner.DamageModifier); entity.HitsTaken += 1; projectilesToRemove.Add(projectile); continue; } } foreach (WallEntity node in SceneNodeManager.WallSceneNodes) { if (projectile.BoundingBox.IntersectsWithBox(node.BoundingBox)) { projectilesToRemove.Add(projectile); DebugRenderer.DrawCollisionBoundingBox(node, Color.Red); break; } } for (int i = 0; i < SceneNodeManager.CustomEntities.Count; i++) { var customEntity = SceneNodeManager.CustomEntities[i]; if (customEntity.Shootable == true) { if (projectile.BoundingBox.IntersectsWithBox(customEntity.BoundingBox)) { if (entity.Node.ID == projectile.Owner.Node.ID) { customEntity.Health -= (int)(projectile.DamageDealt * projectile.Owner.DamageModifier); if (customEntity.Health == 0) { Globals.Scene.AddToDeletionQueue(customEntity.Node); SceneNodeManager.CustomEntities.Remove(customEntity); entity.CustomEntitiesDestroyed += 1; } projectilesToRemove.Add(projectile); break; } } } } } projectilesToRemove.ForEach(p => { CombatManager.ProjectileList.Remove(p); Globals.Scene.AddToDeletionQueue(p.Node); }); } internal static void ClearSpawningItems() { _respawnDictionary.Clear(); } internal static void CheckSpawningItems() { foreach (var pair in _respawnDictionary) { if (Globals.Device.Timer.Time >= pair.Value) { var entity = pair.Key; entity.Node.Visible = true; } } } internal static void CheckMedkitCollisions(CombatEntity player) { foreach (MedkitEntity medkit in SceneNodeManager.VisibleMedkitEntities) { if ((player.Health < RuleManager.MaxHealth) && (player.BoundingBox.IntersectsWithBox(medkit.BoundingBox))) { SoundManager.PlayGetHealth(); medkit.Node.Visible = false; _respawnDictionary[medkit] = Globals.Device.Timer.Time + RuleManager.MedkitRespawnTime; player.Health += medkit.HealthBoost; } } } internal static void CheckBazookaCollisions(CombatEntity player) { foreach (BazookaEntity bazooka in SceneNodeManager.VisibleBazookaEntities) { if ((player.Ammo < RuleManager.MaxAmmo) && (player.BoundingBox.IntersectsWithBox(bazooka.BoundingBox))) { SoundManager.PlayGetBazooka(); bazooka.Node.Visible = false; _respawnDictionary[bazooka] = Globals.Device.Timer.Time + RuleManager.BazookaRespawnTime; player.Ammo++; } } } internal static void CheckPlayerCollisions(CombatEntity player, CombatEntity other) { if (player.BoundingBox.IntersectsWithBox(other.BoundingBox)) { player.Health -= (int)(1 * other.DamageModifier); other.Health -= (int)(1 * player.DamageModifier); } } } }
// // ScriptReference.cs.cs // // This file was generated by XMLSPY 2004 Enterprise Edition. // // YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE // OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION. // // Refer to the XMLSPY Documentation for further details. // http://www.altova.com/xmlspy // using System; using System.Collections; using System.Xml; using Altova.Types; namespace XMLRules { public class ScriptReference : Altova.Node { #region Forward constructors public ScriptReference() : base() { SetCollectionParents(); } public ScriptReference(XmlDocument doc) : base(doc) { SetCollectionParents(); } public ScriptReference(XmlNode node) : base(node) { SetCollectionParents(); } public ScriptReference(Altova.Node node) : base(node) { SetCollectionParents(); } #endregion // Forward constructors public override void AdjustPrefix() { int nCount; nCount = DomChildCount(NodeType.Element, "", "ScriptName"); for (int i = 0; i < nCount; i++) { XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "ScriptName", i); InternalAdjustPrefix(DOMNode, true); } nCount = DomChildCount(NodeType.Element, "", "Parameter"); for (int i = 0; i < nCount; i++) { XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "Parameter", i); InternalAdjustPrefix(DOMNode, true); new ParameterType(DOMNode).AdjustPrefix(); } } #region ScriptName accessor methods public int GetScriptNameMinCount() { return 1; } public int ScriptNameMinCount { get { return 1; } } public int GetScriptNameMaxCount() { return 1; } public int ScriptNameMaxCount { get { return 1; } } public int GetScriptNameCount() { return DomChildCount(NodeType.Element, "", "ScriptName"); } public int ScriptNameCount { get { return DomChildCount(NodeType.Element, "", "ScriptName"); } } public bool HasScriptName() { return HasDomChild(NodeType.Element, "", "ScriptName"); } public SchemaString GetScriptNameAt(int index) { return new SchemaString(GetDomNodeValue(GetDomChildAt(NodeType.Element, "", "ScriptName", index))); } public SchemaString GetScriptName() { return GetScriptNameAt(0); } public SchemaString ScriptName { get { return GetScriptNameAt(0); } } public void RemoveScriptNameAt(int index) { RemoveDomChildAt(NodeType.Element, "", "ScriptName", index); } public void RemoveScriptName() { while (HasScriptName()) RemoveScriptNameAt(0); } public void AddScriptName(SchemaString newValue) { AppendDomChild(NodeType.Element, "", "ScriptName", newValue.ToString()); } public void InsertScriptNameAt(SchemaString newValue, int index) { InsertDomChildAt(NodeType.Element, "", "ScriptName", index, newValue.ToString()); } public void ReplaceScriptNameAt(SchemaString newValue, int index) { ReplaceDomChildAt(NodeType.Element, "", "ScriptName", index, newValue.ToString()); } #endregion // ScriptName accessor methods #region ScriptName collection public ScriptNameCollection MyScriptNames = new ScriptNameCollection( ); public class ScriptNameCollection: IEnumerable { ScriptReference parent; public ScriptReference Parent { set { parent = value; } } public ScriptNameEnumerator GetEnumerator() { return new ScriptNameEnumerator(parent); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class ScriptNameEnumerator: IEnumerator { int nIndex; ScriptReference parent; public ScriptNameEnumerator(ScriptReference par) { parent = par; nIndex = -1; } public void Reset() { nIndex = -1; } public bool MoveNext() { nIndex++; return(nIndex < parent.ScriptNameCount ); } public SchemaString Current { get { return(parent.GetScriptNameAt(nIndex)); } } object IEnumerator.Current { get { return(Current); } } } #endregion // ScriptName collection #region Parameter accessor methods public int GetParameterMinCount() { return 0; } public int ParameterMinCount { get { return 0; } } public int GetParameterMaxCount() { return Int32.MaxValue; } public int ParameterMaxCount { get { return Int32.MaxValue; } } public int GetParameterCount() { return DomChildCount(NodeType.Element, "", "Parameter"); } public int ParameterCount { get { return DomChildCount(NodeType.Element, "", "Parameter"); } } public bool HasParameter() { return HasDomChild(NodeType.Element, "", "Parameter"); } public ParameterType GetParameterAt(int index) { return new ParameterType(GetDomChildAt(NodeType.Element, "", "Parameter", index)); } public ParameterType GetParameter() { return GetParameterAt(0); } public ParameterType Parameter { get { return GetParameterAt(0); } } public void RemoveParameterAt(int index) { RemoveDomChildAt(NodeType.Element, "", "Parameter", index); } public void RemoveParameter() { while (HasParameter()) RemoveParameterAt(0); } public void AddParameter(ParameterType newValue) { AppendDomElement("", "Parameter", newValue); } public void InsertParameterAt(ParameterType newValue, int index) { InsertDomElementAt("", "Parameter", index, newValue); } public void ReplaceParameterAt(ParameterType newValue, int index) { ReplaceDomElementAt("", "Parameter", index, newValue); } #endregion // Parameter accessor methods #region Parameter collection public ParameterCollection MyParameters = new ParameterCollection( ); public class ParameterCollection: IEnumerable { ScriptReference parent; public ScriptReference Parent { set { parent = value; } } public ParameterEnumerator GetEnumerator() { return new ParameterEnumerator(parent); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class ParameterEnumerator: IEnumerator { int nIndex; ScriptReference parent; public ParameterEnumerator(ScriptReference par) { parent = par; nIndex = -1; } public void Reset() { nIndex = -1; } public bool MoveNext() { nIndex++; return(nIndex < parent.ParameterCount ); } public ParameterType Current { get { return(parent.GetParameterAt(nIndex)); } } object IEnumerator.Current { get { return(Current); } } } #endregion // Parameter collection private void SetCollectionParents() { MyScriptNames.Parent = this; MyParameters.Parent = this; } } }
namespace Xilium.CefGlue { using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Xilium.CefGlue.Interop; /// <summary> /// Class used to represent a frame in the browser window. When used in the /// browser process the methods of this class may be called on any thread unless /// otherwise indicated in the comments. When used in the render process the /// methods of this class may only be called on the main thread. /// </summary> public sealed unsafe partial class CefFrame { /// <summary> /// True if this object is currently attached to a valid frame. /// </summary> public bool IsValid { get { return cef_frame_t.is_valid(_self) != 0; } } /// <summary> /// Execute undo in this frame. /// </summary> public void Undo() { cef_frame_t.undo(_self); } /// <summary> /// Execute redo in this frame. /// </summary> public void Redo() { cef_frame_t.redo(_self); } /// <summary> /// Execute cut in this frame. /// </summary> public void Cut() { cef_frame_t.cut(_self); } /// <summary> /// Execute copy in this frame. /// </summary> public void Copy() { cef_frame_t.copy(_self); } /// <summary> /// Execute paste in this frame. /// </summary> public void Paste() { cef_frame_t.paste(_self); } /// <summary> /// Execute delete in this frame. /// </summary> public void Delete() { cef_frame_t.del(_self); } /// <summary> /// Execute select all in this frame. /// </summary> public void SelectAll() { cef_frame_t.select_all(_self); } /// <summary> /// Save this frame's HTML source to a temporary file and open it in the /// default text viewing application. This method can only be called from the /// browser process. /// </summary> public void ViewSource() { cef_frame_t.view_source(_self); } /// <summary> /// Retrieve this frame's HTML source as a string sent to the specified /// visitor. /// </summary> public void GetSource(CefStringVisitor visitor) { if (visitor == null) throw new ArgumentNullException("visitor"); cef_frame_t.get_source(_self, visitor.ToNative()); } /// <summary> /// Retrieve this frame's display text as a string sent to the specified /// visitor. /// </summary> public void GetText(CefStringVisitor visitor) { if (visitor == null) throw new ArgumentNullException("visitor"); cef_frame_t.get_text(_self, visitor.ToNative()); } /// <summary> /// Load the request represented by the |request| object. /// </summary> public void LoadRequest(CefRequest request) { if (request == null) throw new ArgumentNullException("request"); cef_frame_t.load_request(_self, request.ToNative()); } /// <summary> /// Load the specified |url|. /// </summary> public void LoadUrl(string url) { fixed (char* url_str = url) { var n_url = new cef_string_t(url_str, url != null ? url.Length : 0); cef_frame_t.load_url(_self, &n_url); } } /// <summary> /// Load the contents of |string_val| with the specified dummy |url|. |url| /// should have a standard scheme (for example, http scheme) or behaviors like /// link clicks and web security restrictions may not behave as expected. /// </summary> public void LoadString(string content, string url) { fixed (char* content_str = content) fixed (char* url_str = url) { var n_content = new cef_string_t(content_str, content != null ? content.Length : 0); var n_url = new cef_string_t(url_str, url != null ? url.Length : 0); cef_frame_t.load_string(_self, &n_content, &n_url); } } /// <summary> /// Execute a string of JavaScript code in this frame. The |script_url| /// parameter is the URL where the script in question can be found, if any. /// The renderer may request this URL to show the developer the source of the /// error. The |start_line| parameter is the base line number to use for error /// reporting. /// </summary> public void ExecuteJavaScript(string code, string url, int line) { fixed (char* code_str = code) fixed (char* url_str = url) { var n_code = new cef_string_t(code_str, code != null ? code.Length : 0); var n_url = new cef_string_t(url_str, url != null ? url.Length : 0); cef_frame_t.execute_java_script(_self, &n_code, &n_url, line); } } /// <summary> /// Returns true if this is the main (top-level) frame. /// </summary> public bool IsMain { get { return cef_frame_t.is_main(_self) != 0; } } /// <summary> /// Returns true if this is the focused frame. /// </summary> public bool IsFocused { get { return cef_frame_t.is_focused(_self) != 0; } } /// <summary> /// Returns the name for this frame. If the frame has an assigned name (for /// example, set via the iframe "name" attribute) then that value will be /// returned. Otherwise a unique name will be constructed based on the frame /// parent hierarchy. The main (top-level) frame will always have an empty name /// value. /// </summary> public string Name { get { var n_result = cef_frame_t.get_name(_self); return cef_string_userfree.ToString(n_result); } } /// <summary> /// Returns the globally unique identifier for this frame. /// </summary> public long Identifier { get { return cef_frame_t.get_identifier(_self); } } /// <summary> /// Returns the parent of this frame or NULL if this is the main (top-level) /// frame. /// </summary> public CefFrame Parent { get { return CefFrame.FromNativeOrNull( cef_frame_t.get_parent(_self) ); } } /// <summary> /// Returns the URL currently loaded in this frame. /// </summary> public string Url { get { var n_result = cef_frame_t.get_url(_self); return cef_string_userfree.ToString(n_result); } } /// <summary> /// Returns the browser that this frame belongs to. /// </summary> public CefBrowser Browser { get { return CefBrowser.FromNative( cef_frame_t.get_browser(_self) ); } } /// <summary> /// Get the V8 context associated with the frame. This method can only be /// called from the render process. /// </summary> public CefV8Context V8Context { get { return CefV8Context.FromNative( cef_frame_t.get_v8context(_self) ); } } /// <summary> /// Visit the DOM document. This method can only be called from the render /// process. /// </summary> public void VisitDom(CefDomVisitor visitor) { if (visitor == null) throw new ArgumentNullException("visitor"); cef_frame_t.visit_dom(_self, visitor.ToNative()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using Xunit.Abstractions; using System; using System.IO; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; using XmlCoreTest.Common; namespace System.Xml.Tests { public class CSameInstanceXsltArgTestCase : XsltApiTestCaseBase { // Variables from init string protected string _strPath; // Path of the data files // Other global variables public XsltArgumentList xsltArg1; // Shared XsltArgumentList for same instance testing private ITestOutputHelper _output; public CSameInstanceXsltArgTestCase(ITestOutputHelper output) : base(output) { _output = output; Init(null); } public new void Init(object objParam) { // Get parameter info _strPath = Path.Combine("TestFiles", FilePathUtil.GetTestDataPath(), "XsltApi"); xsltArg1 = new XsltArgumentList(); MyObject obj1 = new MyObject(1, _output); MyObject obj2 = new MyObject(2, _output); MyObject obj3 = new MyObject(3, _output); MyObject obj4 = new MyObject(4, _output); MyObject obj5 = new MyObject(5, _output); xsltArg1.AddExtensionObject("urn:my-obj1", obj1); xsltArg1.AddExtensionObject("urn:my-obj2", obj2); xsltArg1.AddExtensionObject("urn:my-obj3", obj3); xsltArg1.AddExtensionObject("urn:my-obj4", obj4); xsltArg1.AddExtensionObject("urn:my-obj5", obj5); xsltArg1.AddParam("myArg1", szEmpty, "Test1"); xsltArg1.AddParam("myArg2", szEmpty, "Test2"); xsltArg1.AddParam("myArg3", szEmpty, "Test3"); xsltArg1.AddParam("myArg4", szEmpty, "Test4"); xsltArg1.AddParam("myArg5", szEmpty, "Test5"); return; } } //[TestCase(Name = "Same instance testing: XsltArgList - GetParam", Desc = "GetParam test cases")] public class CSameInstanceXsltArgumentListGetParam : CSameInstanceXsltArgTestCase { private ITestOutputHelper _output; public CSameInstanceXsltArgumentListGetParam(ITestOutputHelper output) : base(output) { _output = output; } //////////////////////////////////////////////////////////////// // Same instance testing: // Multiple GetParam() over same ArgumentList //////////////////////////////////////////////////////////////// public int GetParam1(object args) { Object retObj; for (int i = 1; i <= 100; i++) { retObj = xsltArg1.GetParam(((object[])args)[1].ToString(), szEmpty); _output.WriteLine("GetParam: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tAdded Value: {0}\tRetrieved Value:{1}\n", "Test1", retObj.ToString()); if (retObj.ToString() != "Test1") { _output.WriteLine("ERROR!!!"); return 0; } } return 1; } public int GetParam2(object args) { Object retObj; for (int i = 1; i <= 100; i++) { retObj = xsltArg1.GetParam(((object[])args)[1].ToString(), szEmpty); string expected = "Test" + ((object[])args)[0]; _output.WriteLine("GetParam: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tAdded Value: {0}\tRetrieved Value:{1}\n", expected, retObj.ToString()); if (retObj.ToString() != expected) { _output.WriteLine("ERROR!!!"); return 0; } } return 1; } //[Variation("Multiple GetParam for same parameter name")] [InlineData()] [Theory] public void proc1() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 1, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 2, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 3, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 4, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 5, "myArg1" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple GetParam for different parameter name")] [InlineData()] [Theory] public void proc2() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 1, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 2, "myArg2" }); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 3, "myArg3" }); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 4, "myArg4" }); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 5, "myArg5" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } } //[TestCase(Name = "Same instance testing: XsltArgList - GetExtensionObject", Desc = "GetExtensionObject test cases")] public class CSameInstanceXsltArgumentListGetExtnObject : CSameInstanceXsltArgTestCase { private ITestOutputHelper _output; public CSameInstanceXsltArgumentListGetExtnObject(ITestOutputHelper output) : base(output) { _output = output; } //////////////////////////////////////////////////////////////// // Same instance testing: // Multiple GetExtensionObject() over same ArgumentList //////////////////////////////////////////////////////////////// public int GetExtnObject1(object args) { Object retObj; for (int i = 1; i <= 100; i++) { retObj = xsltArg1.GetExtensionObject(((object[])args)[1].ToString()); _output.WriteLine("GetExtensionObject: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tValue returned: " + ((MyObject)retObj).MyValue()); if (((MyObject)retObj).MyValue() != 1) { _output.WriteLine("ERROR!!! Set and retrieved value appear to be different"); return 0; } } return 1; } public int GetExtnObject2(object args) { Object retObj; for (int i = 1; i <= 100; i++) { retObj = xsltArg1.GetExtensionObject(((object[])args)[1].ToString()); _output.WriteLine("GetExtensionObject: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tValue returned: " + ((MyObject)retObj).MyValue()); if (((MyObject)retObj).MyValue() != (int)((object[])args)[0]) { _output.WriteLine("ERROR!!! Set and retrieved value appear to be different"); return 0; } } return 1; } //[Variation("Multiple GetExtensionObject for same namespace System.Xml.Tests")] [InlineData()] [Theory] public void proc1() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 1, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 2, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 3, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 4, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 5, "urn:my-obj1" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple GetExtensionObject for different namespace System.Xml.Tests")] [InlineData()] [Theory] public void proc2() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 1, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 2, "urn:my-obj2" }); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 3, "urn:my-obj3" }); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 4, "urn:my-obj4" }); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 5, "urn:my-obj5" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } } //[TestCase(Name = "Same instance testing: XsltArgList - Transform", Desc = "Multiple transforms")] public class CSameInstanceXsltArgumentListTransform : CSameInstanceXsltArgTestCase { private ITestOutputHelper _output; public CSameInstanceXsltArgumentListTransform(ITestOutputHelper output) : base(output) { _output = output; } //////////////////////////////////////////////////////////////// // Same instance testing: // Multiple Transform() using shared ArgumentList //////////////////////////////////////////////////////////////// public int SharedArgList(object args) { string _strXslFile = ((object[])args)[1].ToString(); string _strXmlFile = ((object[])args)[2].ToString(); if (_strXslFile.Substring(0, 5) != "http:") _strXslFile = Path.Combine(_strPath, _strXslFile); if (_strXmlFile.Substring(0, 5) != "http:") _strXmlFile = Path.Combine(_strPath, _strXmlFile); #pragma warning disable 0618 XmlValidatingReader xrData = new XmlValidatingReader(new XmlTextReader(_strXmlFile)); XPathDocument xd = new XPathDocument(xrData, XmlSpace.Preserve); xrData.Dispose(); XslTransform xslt = new XslTransform(); XmlValidatingReader xrTemp = new XmlValidatingReader(new XmlTextReader(_strXslFile)); #pragma warning restore 0618 xrTemp.ValidationType = ValidationType.None; xrTemp.EntityHandling = EntityHandling.ExpandCharEntities; xslt.Load(xrTemp); XmlReader xrXSLT = null; for (int i = 1; i <= 100; i++) { xrXSLT = xslt.Transform(xd, xsltArg1); _output.WriteLine("SharedArgumentList: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tDone with transform..."); } return 1; } //////////////////////////////////////////////////////////////// // Same instance testing: // Multiple Transform() using shared ArgumentList //////////////////////////////////////////////////////////////// //[Variation("Multiple transforms using shared ArgumentList")] [InlineData()] [Theory] public void proc1() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 1, "xsltarg_multithreading1.xsl", "foo.xml" }); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 2, "xsltarg_multithreading2.xsl", "foo.xml" }); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 3, "xsltarg_multithreading3.xsl", "foo.xml" }); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 4, "xsltarg_multithreading4.xsl", "foo.xml" }); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 5, "xsltarg_multithreading5.xsl", "foo.xml" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Archiver.Codecs { public class BoundedReplayRequestEncoder { public const ushort BLOCK_LENGTH = 48; public const ushort TEMPLATE_ID = 18; public const ushort SCHEMA_ID = 101; public const ushort SCHEMA_VERSION = 6; private BoundedReplayRequestEncoder _parentMessage; private IMutableDirectBuffer _buffer; protected int _offset; protected int _limit; public BoundedReplayRequestEncoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IMutableDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public BoundedReplayRequestEncoder Wrap(IMutableDirectBuffer buffer, int offset) { this._buffer = buffer; this._offset = offset; Limit(offset + BLOCK_LENGTH); return this; } public BoundedReplayRequestEncoder WrapAndApplyHeader( IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder) { headerEncoder .Wrap(buffer, offset) .BlockLength(BLOCK_LENGTH) .TemplateId(TEMPLATE_ID) .SchemaId(SCHEMA_ID) .Version(SCHEMA_VERSION); return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ControlSessionIdEncodingOffset() { return 0; } public static int ControlSessionIdEncodingLength() { return 8; } public static long ControlSessionIdNullValue() { return -9223372036854775808L; } public static long ControlSessionIdMinValue() { return -9223372036854775807L; } public static long ControlSessionIdMaxValue() { return 9223372036854775807L; } public BoundedReplayRequestEncoder ControlSessionId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public BoundedReplayRequestEncoder CorrelationId(long value) { _buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int RecordingIdEncodingOffset() { return 16; } public static int RecordingIdEncodingLength() { return 8; } public static long RecordingIdNullValue() { return -9223372036854775808L; } public static long RecordingIdMinValue() { return -9223372036854775807L; } public static long RecordingIdMaxValue() { return 9223372036854775807L; } public BoundedReplayRequestEncoder RecordingId(long value) { _buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian); return this; } public static int PositionEncodingOffset() { return 24; } public static int PositionEncodingLength() { return 8; } public static long PositionNullValue() { return -9223372036854775808L; } public static long PositionMinValue() { return -9223372036854775807L; } public static long PositionMaxValue() { return 9223372036854775807L; } public BoundedReplayRequestEncoder Position(long value) { _buffer.PutLong(_offset + 24, value, ByteOrder.LittleEndian); return this; } public static int LengthEncodingOffset() { return 32; } public static int LengthEncodingLength() { return 8; } public static long LengthNullValue() { return -9223372036854775808L; } public static long LengthMinValue() { return -9223372036854775807L; } public static long LengthMaxValue() { return 9223372036854775807L; } public BoundedReplayRequestEncoder Length(long value) { _buffer.PutLong(_offset + 32, value, ByteOrder.LittleEndian); return this; } public static int LimitCounterIdEncodingOffset() { return 40; } public static int LimitCounterIdEncodingLength() { return 4; } public static int LimitCounterIdNullValue() { return -2147483648; } public static int LimitCounterIdMinValue() { return -2147483647; } public static int LimitCounterIdMaxValue() { return 2147483647; } public BoundedReplayRequestEncoder LimitCounterId(int value) { _buffer.PutInt(_offset + 40, value, ByteOrder.LittleEndian); return this; } public static int ReplayStreamIdEncodingOffset() { return 44; } public static int ReplayStreamIdEncodingLength() { return 4; } public static int ReplayStreamIdNullValue() { return -2147483648; } public static int ReplayStreamIdMinValue() { return -2147483647; } public static int ReplayStreamIdMaxValue() { return 2147483647; } public BoundedReplayRequestEncoder ReplayStreamId(int value) { _buffer.PutInt(_offset + 44, value, ByteOrder.LittleEndian); return this; } public static int ReplayChannelId() { return 8; } public static string ReplayChannelCharacterEncoding() { return "US-ASCII"; } public static string ReplayChannelMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ReplayChannelHeaderLength() { return 4; } public BoundedReplayRequestEncoder PutReplayChannel(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public BoundedReplayRequestEncoder PutReplayChannel(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public BoundedReplayRequestEncoder ReplayChannel(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { BoundedReplayRequestDecoder writer = new BoundedReplayRequestDecoder(); writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.AppendTo(builder); } } }
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ using System; using System.Collections.Generic; using System.Linq; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Queries; using Lucene.Net.Randomized.Generators; using Lucene.Net.Search; using Lucene.Net.Store; using Lucene.Net.Support; using Lucene.Net.Util; using NUnit.Framework; namespace Lucene.Net.Tests.Queries { public class TermsFilterTest : LuceneTestCase { [Test] public void TestCachability() { TermsFilter a = TermsFilter(Random().NextBoolean(), new Term("field1", "a"), new Term("field1", "b")); HashSet<Filter> cachedFilters = new HashSet<Filter>(); cachedFilters.Add(a); TermsFilter b = TermsFilter(Random().NextBoolean(), new Term("field1", "b"), new Term("field1", "a")); assertTrue("Must be cached", cachedFilters.Contains(b)); //duplicate term assertTrue("Must be cached", cachedFilters.Contains(TermsFilter(true, new Term("field1", "a"), new Term("field1", "a"), new Term("field1", "b")))); assertFalse("Must not be cached", cachedFilters.Contains(TermsFilter(Random().NextBoolean(), new Term("field1", "a"), new Term("field1", "a"), new Term("field1", "b"), new Term("field1", "v")))); } [Test] public void TestMissingTerms() { string fieldName = "field1"; Directory rd = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random(), rd, Similarity, TimeZone); for (int i = 0; i < 100; i++) { Document doc = new Document(); int term = i * 10; //terms are units of 10; doc.Add(NewStringField(fieldName, "" + term, Field.Store.YES)); w.AddDocument(doc); } IndexReader reader = SlowCompositeReaderWrapper.Wrap(w.Reader); assertTrue(reader.Context is AtomicReaderContext); AtomicReaderContext context = (AtomicReaderContext)reader.Context; w.Dispose(); IList<Term> terms = new List<Term>(); terms.Add(new Term(fieldName, "19")); FixedBitSet bits = (FixedBitSet)TermsFilter(Random().NextBoolean(), terms).GetDocIdSet(context, context.AtomicReader.LiveDocs); assertNull("Must match nothing", bits); terms.Add(new Term(fieldName, "20")); bits = (FixedBitSet)TermsFilter(Random().NextBoolean(), terms).GetDocIdSet(context, context.AtomicReader.LiveDocs); assertEquals("Must match 1", 1, bits.Cardinality()); terms.Add(new Term(fieldName, "10")); bits = (FixedBitSet)TermsFilter(Random().NextBoolean(), terms).GetDocIdSet(context, context.AtomicReader.LiveDocs); assertEquals("Must match 2", 2, bits.Cardinality()); terms.Add(new Term(fieldName, "00")); bits = (FixedBitSet)TermsFilter(Random().NextBoolean(), terms).GetDocIdSet(context, context.AtomicReader.LiveDocs); assertEquals("Must match 2", 2, bits.Cardinality()); reader.Dispose(); rd.Dispose(); } [Test] public void TestMissingField() { string fieldName = "field1"; Directory rd1 = NewDirectory(); RandomIndexWriter w1 = new RandomIndexWriter(Random(), rd1, Similarity, TimeZone); Document doc = new Document(); doc.Add(NewStringField(fieldName, "content1", Field.Store.YES)); w1.AddDocument(doc); IndexReader reader1 = w1.Reader; w1.Dispose(); fieldName = "field2"; Directory rd2 = NewDirectory(); RandomIndexWriter w2 = new RandomIndexWriter(Random(), rd2, Similarity, TimeZone); doc = new Document(); doc.Add(NewStringField(fieldName, "content2", Field.Store.YES)); w2.AddDocument(doc); IndexReader reader2 = w2.Reader; w2.Dispose(); TermsFilter tf = new TermsFilter(new Term(fieldName, "content1")); MultiReader multi = new MultiReader(reader1, reader2); foreach (AtomicReaderContext context in multi.Leaves) { DocIdSet docIdSet = tf.GetDocIdSet(context, context.AtomicReader.LiveDocs); if (context.Reader.DocFreq(new Term(fieldName, "content1")) == 0) { assertNull(docIdSet); } else { FixedBitSet bits = (FixedBitSet)docIdSet; assertTrue("Must be >= 0", bits.Cardinality() >= 0); } } multi.Dispose(); reader1.Dispose(); reader2.Dispose(); rd1.Dispose(); rd2.Dispose(); } [Test] public void TestFieldNotPresent() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); int num = AtLeast(3); int skip = Random().Next(num); var terms = new List<Term>(); for (int i = 0; i < num; i++) { terms.Add(new Term("field" + i, "content1")); Document doc = new Document(); if (skip == i) { continue; } doc.Add(NewStringField("field" + i, "content1", Field.Store.YES)); w.AddDocument(doc); } w.ForceMerge(1); IndexReader reader = w.Reader; w.Dispose(); assertEquals(1, reader.Leaves.size()); AtomicReaderContext context = reader.Leaves.First(); TermsFilter tf = new TermsFilter(terms); FixedBitSet bits = (FixedBitSet)tf.GetDocIdSet(context, context.AtomicReader.LiveDocs); assertEquals("Must be num fields - 1 since we skip only one field", num - 1, bits.Cardinality()); reader.Dispose(); dir.Dispose(); } [Test] public void TestSkipField() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); int num = AtLeast(10); var terms = new HashSet<Term>(); for (int i = 0; i < num; i++) { string field = "field" + Random().Next(100); terms.Add(new Term(field, "content1")); Document doc = new Document(); doc.Add(NewStringField(field, "content1", Field.Store.YES)); w.AddDocument(doc); } int randomFields = Random().Next(10); for (int i = 0; i < randomFields; i++) { while (true) { string field = "field" + Random().Next(100); Term t = new Term(field, "content1"); if (!terms.Contains(t)) { terms.Add(t); break; } } } w.ForceMerge(1); IndexReader reader = w.Reader; w.Dispose(); assertEquals(1, reader.Leaves.size()); AtomicReaderContext context = reader.Leaves.First(); TermsFilter tf = new TermsFilter(terms.ToList()); FixedBitSet bits = (FixedBitSet)tf.GetDocIdSet(context, context.AtomicReader.LiveDocs); assertEquals(context.Reader.NumDocs, bits.Cardinality()); reader.Dispose(); dir.Dispose(); } [Test] public void TestRandom() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); int num = AtLeast(100); bool singleField = Random().NextBoolean(); IList<Term> terms = new List<Term>(); for (int i = 0; i < num; i++) { string field = "field" + (singleField ? "1" : Random().Next(100).ToString()); string @string = TestUtil.RandomRealisticUnicodeString(Random()); terms.Add(new Term(field, @string)); Document doc = new Document(); doc.Add(NewStringField(field, @string, Field.Store.YES)); w.AddDocument(doc); } IndexReader reader = w.Reader; w.Dispose(); IndexSearcher searcher = NewSearcher(reader); int numQueries = AtLeast(10); for (int i = 0; i < numQueries; i++) { Collections.Shuffle(terms); int numTerms = 1 + Random().Next(Math.Min(BooleanQuery.MaxClauseCount, terms.Count)); BooleanQuery bq = new BooleanQuery(); for (int j = 0; j < numTerms; j++) { bq.Add(new BooleanClause(new TermQuery(terms[j]), Occur.SHOULD)); } TopDocs queryResult = searcher.Search(new ConstantScoreQuery(bq), reader.MaxDoc); MatchAllDocsQuery matchAll = new MatchAllDocsQuery(); TermsFilter filter = TermsFilter(singleField, terms.SubList(0, numTerms)); TopDocs filterResult = searcher.Search(matchAll, filter, reader.MaxDoc); assertEquals(filterResult.TotalHits, queryResult.TotalHits); ScoreDoc[] scoreDocs = filterResult.ScoreDocs; for (int j = 0; j < scoreDocs.Length; j++) { assertEquals(scoreDocs[j].Doc, queryResult.ScoreDocs[j].Doc); } } reader.Dispose(); dir.Dispose(); } private TermsFilter TermsFilter(bool singleField, params Term[] terms) { return TermsFilter(singleField, terms.ToList()); } private TermsFilter TermsFilter(bool singleField, IEnumerable<Term> termList) { if (!singleField) { return new TermsFilter(termList.ToList()); } TermsFilter filter; var bytes = new List<BytesRef>(); string field = null; foreach (Term term in termList) { bytes.Add(term.Bytes); if (field != null) { assertEquals(term.Field, field); } field = term.Field; } assertNotNull(field); filter = new TermsFilter(field, bytes); return filter; } [Test] public void TestHashCodeAndEquals() { int num = AtLeast(100); bool singleField = Random().NextBoolean(); IList<Term> terms = new List<Term>(); var uniqueTerms = new HashSet<Term>(); for (int i = 0; i < num; i++) { string field = "field" + (singleField ? "1" : Random().Next(100).ToString()); string @string = TestUtil.RandomRealisticUnicodeString(Random()); terms.Add(new Term(field, @string)); uniqueTerms.Add(new Term(field, @string)); TermsFilter left = TermsFilter(singleField && Random().NextBoolean(), uniqueTerms); Collections.Shuffle(terms); TermsFilter right = TermsFilter(singleField && Random().NextBoolean(), terms); assertEquals(right, left); assertEquals(right.GetHashCode(), left.GetHashCode()); if (uniqueTerms.Count > 1) { IList<Term> asList = new List<Term>(uniqueTerms); asList.RemoveAt(0); TermsFilter notEqual = TermsFilter(singleField && Random().NextBoolean(), asList); assertFalse(left.Equals(notEqual)); assertFalse(right.Equals(notEqual)); } } } [Test] public void TestSingleFieldEquals() { // Two terms with the same hash code //assertEquals("AaAaBB".GetHashCode(), "BBBBBB".GetHashCode()); TermsFilter left = TermsFilter(true, new Term("id", "AaAaAa"), new Term("id", "AaAaBB")); TermsFilter right = TermsFilter(true, new Term("id", "AaAaAa"), new Term("id", "BBBBBB")); assertFalse(left.Equals(right)); } [Test] public void TestNoTerms() { var emptyTerms = new List<Term>(); var emptyBytesRef = new List<BytesRef>(); Assert.Throws<ArgumentException>(() => new TermsFilter(emptyTerms)); Assert.Throws<ArgumentException>(() => new TermsFilter(emptyTerms.ToArray())); Assert.Throws<ArgumentException>(() => new TermsFilter(null, emptyBytesRef.ToArray())); Assert.Throws<ArgumentException>(() => new TermsFilter(null, emptyBytesRef)); } [Test] public void TestToString() { TermsFilter termsFilter = new TermsFilter(new Term("field1", "a"), new Term("field1", "b"), new Term("field1", "c")); assertEquals("field1:a field1:b field1:c", termsFilter.ToString()); } } }