context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Globalization; using System.Security.Cryptography; using System.Security.Cryptography.Xml; using System.Threading; using System.Xml; using EasyLicense.Lib.License.Exception; namespace EasyLicense.Lib.License.Validator { /// <summary> /// Base license validator. /// </summary> public abstract class AbstractLicenseValidator { private readonly string licenseServerUrl; private readonly Timer nextLeaseTimer; private readonly string publicKey; private bool currentlyValidatingSubscriptionLicense; private bool disableFutureChecks; /// <summary> /// Creates a license validator with specfied public key. /// </summary> /// <param name="publicKey">public key</param> protected AbstractLicenseValidator(string publicKey) { LicenseAttributes = new Dictionary<string, string>(); nextLeaseTimer = new Timer(LeaseLicenseAgain); this.publicKey = publicKey; } /// <summary> /// Creates a license validator using the client information and a service endpoint address /// to validate the license. /// </summary> /// <param name="publicKey"></param> /// <param name="licenseServerUrl"></param> /// <param name="clientId"></param> protected AbstractLicenseValidator(string publicKey, string licenseServerUrl, Guid clientId) { LicenseAttributes = new Dictionary<string, string>(); nextLeaseTimer = new Timer(LeaseLicenseAgain); this.publicKey = publicKey; this.licenseServerUrl = licenseServerUrl; } /// <summary> /// Gets or Sets Floating license support /// </summary> public virtual bool DisableFloatingLicenses { get; set; } /// <summary> /// Gets the expiration date of the license /// </summary> public virtual DateTime ExpirationDate { get; private set; } /// <summary> /// Gets extra license information /// </summary> public virtual IDictionary<string, string> LicenseAttributes { get; } /// <summary> /// Gets the Type of the license /// </summary> public virtual LicenseType LicenseType { get; private set; } /// <summary> /// Gets the name of the license holder /// </summary> public virtual string Name { get; private set; } /// <summary> /// Gets or Sets the endpoint address of the subscription service /// </summary> public virtual string SubscriptionEndpoint { get; set; } /// <summary> /// Gets the Id of the license holder /// </summary> public Guid UserId { get; private set; } /// <summary> /// Gets or Sets the license content /// </summary> protected abstract string License { get; set; } /// <summary> /// Fired when license data is invalidated /// </summary> public event Action<InvalidationType> LicenseInvalidated; /// <summary> /// Validates loaded license /// </summary> public virtual void AssertValidLicense() { LicenseAttributes.Clear(); if (HasExistingLicense()) return; throw new LicenseNotFoundException(); } /// <summary> /// Disables further license checks for the session. /// </summary> public void DisableFutureChecks() { disableFutureChecks = true; nextLeaseTimer.Dispose(); } public virtual int GetLicenseAttribute(string attributeName) { if (LicenseAttributes.ContainsKey(attributeName)) return Convert.ToInt32(LicenseAttributes[attributeName]); return -1; } /// <summary> /// Removes existing license from the machine. /// </summary> public virtual void RemoveExistingLicense() { } /// <summary> /// Loads license data from validated license file. /// </summary> /// <returns></returns> public bool TryLoadingLicenseValuesFromValidatedXml() { try { var doc = new XmlDocument(); doc.LoadXml(License); if (TryGetValidDocument(publicKey, doc) == false) return false; if (doc.FirstChild == null) return false; if (doc.SelectSingleNode("/floating-license") != null) { var node = doc.SelectSingleNode("/floating-license/license-server-public-key/text()"); if (node == null) throw new InvalidOperationException( "Invalid license file format, floating license without license server public key"); return ValidateFloatingLicense(node.InnerText); } var result = ValidateXmlDocumentLicense(doc); if (result && disableFutureChecks == false) nextLeaseTimer.Change(TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5)); return result; } catch (RhinoLicensingException) { throw; } catch { return false; } } internal bool ValidateXmlDocumentLicense(XmlDocument doc) { var id = doc.SelectSingleNode("/license/@id"); if (id == null) return false; UserId = new Guid(id.Value); var date = doc.SelectSingleNode("/license/@expiration"); if (date == null) return false; ExpirationDate = DateTime.ParseExact(date.Value, "yyyy-MM-ddTHH:mm:ss.fffffff", CultureInfo.InvariantCulture); var licenseType = doc.SelectSingleNode("/license/@type"); if (licenseType == null) return false; LicenseType = (LicenseType) Enum.Parse(typeof(LicenseType), licenseType.Value); var name = doc.SelectSingleNode("/license/name/text()"); if (name == null) return false; Name = name.Value; var license = doc.SelectSingleNode("/license"); foreach (XmlAttribute attrib in license.Attributes) { if (attrib.Name == "type" || attrib.Name == "expiration" || attrib.Name == "id") continue; LicenseAttributes[attrib.Name] = attrib.Value; } return true; } /// <summary> /// Loads the license file. /// </summary> /// <param name="newLicense"></param> /// <returns></returns> protected bool TryOverwritingWithNewLicense(string newLicense) { if (string.IsNullOrEmpty(newLicense)) return false; try { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(newLicense); } catch { return false; } License = newLicense; return true; } private bool HasExistingLicense() { try { if (TryLoadingLicenseValuesFromValidatedXml() == false) return false; bool result; if (LicenseType == LicenseType.Subscription) result = ValidateSubscription(); else result = DateTime.UtcNow < ExpirationDate; if (result == false) throw new LicenseExpiredException("Expiration Date : " + ExpirationDate); return true; } catch (RhinoLicensingException) { throw; } catch { return false; } } private void LeaseLicenseAgain(object state) { if (HasExistingLicense()) return; RaiseLicenseInvalidated(); } private void RaiseLicenseInvalidated() { var licenseInvalidated = LicenseInvalidated; if (licenseInvalidated == null) throw new InvalidOperationException( "License was invalidated, but there is no one subscribe to the LicenseInvalidated event"); licenseInvalidated(LicenseType == LicenseType.Floating ? InvalidationType.CannotGetNewLicense : InvalidationType.TimeExpired); } private void TryGettingNewLeaseSubscription() { } private bool TryGetValidDocument(string licensePublicKey, XmlDocument doc) { var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(licensePublicKey); var nsMgr = new XmlNamespaceManager(doc.NameTable); nsMgr.AddNamespace("sig", "http://www.w3.org/2000/09/xmldsig#"); var signedXml = new SignedXml(doc); var sig = (XmlElement) doc.SelectSingleNode("//sig:Signature", nsMgr); if (sig == null) return false; signedXml.LoadXml(sig); return signedXml.CheckSignature(rsa); } private bool ValidateFloatingLicense(string publicKeyOfFloatingLicense) { if (DisableFloatingLicenses) return false; if (licenseServerUrl == null) throw new InvalidOperationException("Floating license encountered, but licenseServerUrl was not set"); var success = false; // not support . return success; } private bool ValidateSubscription() { if ((ExpirationDate - DateTime.UtcNow).TotalDays > 4) return true; if (currentlyValidatingSubscriptionLicense) return DateTime.UtcNow < ExpirationDate; if (SubscriptionEndpoint == null) throw new InvalidOperationException( "Subscription endpoints are not supported for this license validator"); try { TryGettingNewLeaseSubscription(); } catch { throw; } return ValidateWithoutUsingSubscriptionLeasing(); } private bool ValidateWithoutUsingSubscriptionLeasing() { currentlyValidatingSubscriptionLicense = true; try { return HasExistingLicense(); } finally { currentlyValidatingSubscriptionLicense = false; } } } /// <summary> /// InvalidationType /// </summary> public enum InvalidationType { /// <summary> /// Can not create a new license /// </summary> CannotGetNewLicense, /// <summary> /// License is expired /// </summary> TimeExpired } }
/* ==================================================================== 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.UserModel { using System; using System.Text; using NPOI.HSSF.Record; using NPOI.HSSF.Util; using NPOI.Util; /// <summary> /// Represents a workbook color palette. /// Internally, the XLS format refers to colors using an offset into the palette /// record. Thus, the first color in the palette has the index 0x8, the second /// has the index 0x9, etc. through 0x40 /// @author Brian Sanders (bsanders at risklabs dot com) /// </summary> public class HSSFPalette { private PaletteRecord palette; public HSSFPalette(PaletteRecord palette) { this.palette = palette; } /// <summary> /// Retrieves the color at a given index /// </summary> /// <param name="index">the palette index, between 0x8 to 0x40 inclusive.</param> /// <returns>the color, or null if the index Is not populated</returns> public HSSFColor GetColor(short index) { //Handle the special AUTOMATIC case if (index == HSSFColor.Automatic.Index) return HSSFColor.Automatic.GetInstance(); else { byte[] b = palette.GetColor(index); if (b != null) { return new CustomColor(index, b); } } return null; } /// <summary> /// Finds the first occurance of a given color /// </summary> /// <param name="red">the RGB red component, between 0 and 255 inclusive</param> /// <param name="green">the RGB green component, between 0 and 255 inclusive</param> /// <param name="blue">the RGB blue component, between 0 and 255 inclusive</param> /// <returns>the color, or null if the color does not exist in this palette</returns> public HSSFColor FindColor(byte red, byte green, byte blue) { byte[] b = palette.GetColor(PaletteRecord.FIRST_COLOR_INDEX); for (short i = (short)PaletteRecord.FIRST_COLOR_INDEX; b != null; b = palette.GetColor(++i)) { if (b[0] == red && b[1] == green && b[2] == blue) { return new CustomColor(i, b); } } return null; } /// <summary> /// Finds the closest matching color in the custom palette. The /// method for Finding the distance between the colors Is fairly /// primative. /// </summary> /// <param name="red">The red component of the color to match.</param> /// <param name="green">The green component of the color to match.</param> /// <param name="blue">The blue component of the color to match.</param> /// <returns>The closest color or null if there are no custom /// colors currently defined.</returns> public HSSFColor FindSimilarColor(byte red, byte green, byte blue) { HSSFColor result = null; int minColorDistance = int.MaxValue; byte[] b = palette.GetColor(PaletteRecord.FIRST_COLOR_INDEX); for (short i = (short)PaletteRecord.FIRST_COLOR_INDEX; b != null; b = palette.GetColor(++i)) { int colorDistance = Math.Abs(red - b[0]) + Math.Abs(green - b[1]) + Math.Abs(blue - b[2]); if (colorDistance < minColorDistance) { minColorDistance = colorDistance; result = GetColor(i); } } return result; } /// <summary> /// Sets the color at the given offset /// </summary> /// <param name="index">the palette index, between 0x8 to 0x40 inclusive</param> /// <param name="red">the RGB red component, between 0 and 255 inclusive</param> /// <param name="green">the RGB green component, between 0 and 255 inclusive</param> /// <param name="blue">the RGB blue component, between 0 and 255 inclusive</param> public void SetColorAtIndex(short index, byte red, byte green, byte blue) { palette.SetColor(index, red, green, blue); } /// <summary> /// Adds a new color into an empty color slot. /// </summary> /// <param name="red">The red component</param> /// <param name="green">The green component</param> /// <param name="blue">The blue component</param> /// <returns>The new custom color.</returns> public HSSFColor AddColor(byte red, byte green, byte blue) { byte[] b = palette.GetColor(PaletteRecord.FIRST_COLOR_INDEX); short i; for (i = (short)PaletteRecord.FIRST_COLOR_INDEX; i < PaletteRecord.STANDARD_PALETTE_SIZE + PaletteRecord.FIRST_COLOR_INDEX; b = palette.GetColor(++i)) { if (b == null) { SetColorAtIndex(i, red, green, blue); return GetColor(i); } } throw new Exception("Could not Find free color index"); } /// <summary> /// user custom color /// </summary> private class CustomColor : HSSFColor { private short byteOffset; private byte red; private byte green; private byte blue; /// <summary> /// Initializes a new instance of the <see cref="CustomColor"/> class. /// </summary> /// <param name="byteOffset">The byte offset.</param> /// <param name="colors">The colors.</param> public CustomColor(short byteOffset, byte[] colors): this(byteOffset, colors[0], colors[1], colors[2]) { } /// <summary> /// Initializes a new instance of the <see cref="CustomColor"/> class. /// </summary> /// <param name="byteOffset">The byte offset.</param> /// <param name="red">The red.</param> /// <param name="green">The green.</param> /// <param name="blue">The blue.</param> public CustomColor(short byteOffset, byte red, byte green, byte blue) { this.byteOffset = byteOffset; this.red = red; this.green = green; this.blue = blue; } /// <summary> /// Gets index to the standard palette /// </summary> /// <value></value> public override short Indexed { get { return byteOffset; } } /// <summary> /// Gets triplet representation like that in Excel /// </summary> /// <value></value> public override byte[] GetTriplet() { return new byte[] { (byte)(red & 0xff), (byte)(green & 0xff), (byte)(blue & 0xff) }; } /// <summary> /// Gets a hex string exactly like a gnumeric triplet /// </summary> /// <value></value> public override String GetHexString() { StringBuilder sb = new StringBuilder(); sb.Append(GetGnumericPart(red)); sb.Append(':'); sb.Append(GetGnumericPart(green)); sb.Append(':'); sb.Append(GetGnumericPart(blue)); return sb.ToString(); } /// <summary> /// Gets the gnumeric part. /// </summary> /// <param name="color">The color.</param> /// <returns></returns> private String GetGnumericPart(byte color) { String s; if (color == 0) { s = "0"; } else { int c = color & 0xff; //as Unsigned c = (c << 8) | c; //pad to 16-bit s = StringUtil.ToHexString(c).ToUpper(); while (s.Length < 4) { s = "0" + s; } } return s; } } } }
// Lucene version compatibility level 4.8.1 using Lucene.Net.Analysis.Standard.Std31; using Lucene.Net.Analysis.Standard.Std34; using Lucene.Net.Analysis.Standard.Std40; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Util; using System; using System.IO; namespace Lucene.Net.Analysis.Standard { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// A grammar-based tokenizer constructed with JFlex. /// <para> /// As of Lucene version 3.1, this class implements the Word Break rules from the /// Unicode Text Segmentation algorithm, as specified in /// <a href="http://unicode.org/reports/tr29/">Unicode Standard Annex #29</a>. /// <p/> /// </para> /// <para>Many applications have specific tokenizer needs. If this tokenizer does /// not suit your application, please consider copying this source code /// directory to your project and maintaining your own grammar-based tokenizer. /// /// </para> /// <para>You must specify the required <see cref="LuceneVersion"/> /// compatibility when creating <see cref="StandardTokenizer"/>: /// <list type="bullet"> /// <item><description> As of 3.4, Hiragana and Han characters are no longer wrongly split /// from their combining characters. If you use a previous version number, /// you get the exact broken behavior for backwards compatibility.</description></item> /// <item><description> As of 3.1, StandardTokenizer implements Unicode text segmentation. /// If you use a previous version number, you get the exact behavior of /// <see cref="ClassicTokenizer"/> for backwards compatibility.</description></item> /// </list> /// </para> /// </summary> public sealed class StandardTokenizer : Tokenizer { /// <summary> /// A private instance of the JFlex-constructed scanner </summary> private IStandardTokenizerInterface scanner; public const int ALPHANUM = 0; /// @deprecated (3.1) [Obsolete("(3.1)")] public const int APOSTROPHE = 1; /// @deprecated (3.1) [Obsolete("(3.1)")] public const int ACRONYM = 2; /// @deprecated (3.1) [Obsolete("(3.1)")] public const int COMPANY = 3; public const int EMAIL = 4; /// @deprecated (3.1) [Obsolete("(3.1)")] public const int HOST = 5; public const int NUM = 6; /// @deprecated (3.1) [Obsolete("(3.1)")] public const int CJ = 7; /// @deprecated (3.1) [Obsolete("(3.1)")] public const int ACRONYM_DEP = 8; public const int SOUTHEAST_ASIAN = 9; public const int IDEOGRAPHIC = 10; public const int HIRAGANA = 11; public const int KATAKANA = 12; public const int HANGUL = 13; /// <summary> /// String token types that correspond to token type int constants </summary> public static readonly string[] TOKEN_TYPES = { "<ALPHANUM>", "<APOSTROPHE>", "<ACRONYM>", "<COMPANY>", "<EMAIL>", "<HOST>", "<NUM>", "<CJ>", "<ACRONYM_DEP>", "<SOUTHEAST_ASIAN>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>", "<HANGUL>" }; private int skippedPositions; private int maxTokenLength = StandardAnalyzer.DEFAULT_MAX_TOKEN_LENGTH; /// <summary> /// Set the max allowed token length. Any token longer /// than this is skipped. /// </summary> public int MaxTokenLength { get => maxTokenLength; set { if (value < 1) { throw new ArgumentException("maxTokenLength must be greater than zero"); } this.maxTokenLength = value; } } /// <summary> /// Creates a new instance of the <see cref="StandardTokenizer"/>. Attaches /// the <paramref name="input"/> to the newly created JFlex-generated (then ported to .NET) scanner. /// </summary> /// <param name="matchVersion"> Lucene compatibility version - See <see cref="StandardTokenizer"/> </param> /// <param name="input"> The input reader /// /// See http://issues.apache.org/jira/browse/LUCENE-1068 </param> public StandardTokenizer(LuceneVersion matchVersion, TextReader input) : base(input) { Init(matchVersion); } /// <summary> /// Creates a new <see cref="StandardTokenizer"/> with a given <see cref="AttributeSource.AttributeFactory"/> /// </summary> public StandardTokenizer(LuceneVersion matchVersion, AttributeFactory factory, TextReader input) : base(factory, input) { Init(matchVersion); } private void Init(LuceneVersion matchVersion) { #pragma warning disable 612, 618 if (matchVersion.OnOrAfter(LuceneVersion.LUCENE_47)) { this.scanner = new StandardTokenizerImpl(m_input); } else if (matchVersion.OnOrAfter(LuceneVersion.LUCENE_40)) { this.scanner = new StandardTokenizerImpl40(m_input); } else if (matchVersion.OnOrAfter(LuceneVersion.LUCENE_34)) { this.scanner = new StandardTokenizerImpl34(m_input); } else if (matchVersion.OnOrAfter(LuceneVersion.LUCENE_31)) { this.scanner = new StandardTokenizerImpl31(m_input); } #pragma warning restore 612, 618 else { this.scanner = new ClassicTokenizerImpl(m_input); } termAtt = AddAttribute<ICharTermAttribute>(); posIncrAtt = AddAttribute<IPositionIncrementAttribute>(); offsetAtt = AddAttribute<IOffsetAttribute>(); typeAtt = AddAttribute<ITypeAttribute>(); } // this tokenizer generates three attributes: // term offset, positionIncrement and type private ICharTermAttribute termAtt; private IOffsetAttribute offsetAtt; private IPositionIncrementAttribute posIncrAtt; private ITypeAttribute typeAtt; /* * (non-Javadoc) * * @see org.apache.lucene.analysis.TokenStream#next() */ public override sealed bool IncrementToken() { ClearAttributes(); skippedPositions = 0; while (true) { int tokenType = scanner.GetNextToken(); if (tokenType == StandardTokenizerInterface.YYEOF) { return false; } if (scanner.YyLength <= maxTokenLength) { posIncrAtt.PositionIncrement = skippedPositions + 1; scanner.GetText(termAtt); int start = scanner.YyChar; offsetAtt.SetOffset(CorrectOffset(start), CorrectOffset(start + termAtt.Length)); // This 'if' should be removed in the next release. For now, it converts // invalid acronyms to HOST. When removed, only the 'else' part should // remain. #pragma warning disable 612, 618 if (tokenType == StandardTokenizer.ACRONYM_DEP) { typeAtt.Type = StandardTokenizer.TOKEN_TYPES[StandardTokenizer.HOST]; #pragma warning restore 612, 618 termAtt.Length = termAtt.Length - 1; // remove extra '.' } else { typeAtt.Type = StandardTokenizer.TOKEN_TYPES[tokenType]; } return true; } else // When we skip a too-long term, we still increment the // position increment { skippedPositions++; } } } public override sealed void End() { base.End(); // set final offset int finalOffset = CorrectOffset(scanner.YyChar + scanner.YyLength); offsetAtt.SetOffset(finalOffset, finalOffset); // adjust any skipped tokens posIncrAtt.PositionIncrement = posIncrAtt.PositionIncrement + skippedPositions; } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { scanner.YyReset(m_input); } } public override void Reset() { base.Reset(); scanner.YyReset(m_input); skippedPositions = 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using Xunit; namespace System.Tests { public class ConvertToStringTests { [Fact] public static void FromBoxedObject() { object[] testValues = { // Boolean true, false, // Byte byte.MinValue, (byte)100, byte.MaxValue, // Decimal decimal.Zero, decimal.One, decimal.MinusOne, decimal.MaxValue, decimal.MinValue, 1.234567890123456789012345678m, 1234.56m, -1234.56m, // Double -12.2364, -1.7753E-83, +12.345e+234, +12e+1, double.NegativeInfinity, double.PositiveInfinity, double.NaN, // Int16 short.MinValue, 0, short.MaxValue, // Int32 int.MinValue, 0, int.MaxValue, // Int64 long.MinValue, (long)0, long.MaxValue, // SByte sbyte.MinValue, (sbyte)0, sbyte.MaxValue, // Single -12.2364f, (float)+12.345e+234, +12e+1f, float.NegativeInfinity, float.PositiveInfinity, float.NaN, // TimeSpan TimeSpan.Zero, TimeSpan.Parse("1999.9:09:09"), TimeSpan.Parse("-1111.1:11:11"), TimeSpan.Parse("1:23:45"), TimeSpan.Parse("-2:34:56"), // UInt16 ushort.MinValue, (ushort)100, ushort.MaxValue, // UInt32 uint.MinValue, (uint)100, uint.MaxValue, // UInt64 ulong.MinValue, (ulong)100, ulong.MaxValue }; string[] expectedValues = { // Boolean "True", "False", // Byte "0", "100", "255", // Decimal "0", "1", "-1", "79228162514264337593543950335", "-79228162514264337593543950335", "1.234567890123456789012345678", "1234.56", "-1234.56", // Double "-12.2364", "-1.7753E-83", "1.2345E+235", "120", "-Infinity", "Infinity", "NaN", // Int16 "-32768", "0", "32767", // Int32 "-2147483648", "0", "2147483647", // Int64 "-9223372036854775808", "0", "9223372036854775807", // SByte "-128", "0", "127", // Single "-12.2364", "Infinity", "120", "-Infinity", "Infinity", "NaN", // TimeSpan "00:00:00", "1999.09:09:09", "-1111.01:11:11", "01:23:45", "-02:34:56", // UInt16 "0", "100", "65535", // UInt32 "0", "100", "4294967295", // UInt64 "0", "100", "18446744073709551615", }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], NumberFormatInfo.InvariantInfo)); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void FromBoxedObject_NotNetFramework() { object[] testValues = { // Double -12.236465923406483, // Single -1.7753e-83f, -12.2364659234064826243f, }; string[] expectedValues = { // Double "-12.236465923406483", // Single "-0", "-12.236465", }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], NumberFormatInfo.InvariantInfo)); } } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] public static void FromBoxedObject_NetFramework() { object[] testValues = { // Double -12.236465923406483, // Single -1.7753e-83f, -12.2364659234064826243f, }; string[] expectedValues = { // Double "-12.2364659234065", // Single "0", "-12.23647", }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], NumberFormatInfo.InvariantInfo)); } } [Fact] public static void FromObject() { Assert.Equal("System.Tests.ConvertToStringTests", Convert.ToString(new ConvertToStringTests())); } [Fact] public static void FromDateTime() { DateTime[] testValues = { new DateTime(2000, 8, 15, 16, 59, 59), new DateTime(1, 1, 1, 1, 1, 1) }; string[] expectedValues = { "08/15/2000 16:59:59", "01/01/0001 01:01:01" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(testValues[i].ToString(), Convert.ToString(testValues[i])); Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], DateTimeFormatInfo.InvariantInfo)); } } [Fact] public static void FromChar() { char[] testValues = { 'a', 'A', '@', '\n' }; string[] expectedValues = { "a", "A", "@", "\n" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i])); Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], CultureInfo.InvariantCulture)); } } private static void Verify<TInput>(Func<TInput, string> convert, Func<TInput, IFormatProvider, string> convertWithFormatProvider, TInput[] testValues, string[] expectedValues, IFormatProvider formatProvider = null) { Assert.Equal(expectedValues.Length, testValues.Length); if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture; } for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], convert(testValues[i])); Assert.Equal(expectedValues[i], convertWithFormatProvider(testValues[i], formatProvider)); } } [Fact] public static void FromByteBase2() { byte[] testValues = { byte.MinValue, 100, byte.MaxValue }; string[] expectedValues = { "0", "1100100", "11111111" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2)); } } [Fact] public static void FromByteBase8() { byte[] testValues = { byte.MinValue, 100, byte.MaxValue }; string[] expectedValues = { "0", "144", "377" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8)); } } [Fact] public static void FromByteBase10() { byte[] testValues = { byte.MinValue, 100, byte.MaxValue }; string[] expectedValues = { "0", "100", "255" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10)); } } [Fact] public static void FromByteBase16() { byte[] testValues = { byte.MinValue, 100, byte.MaxValue }; string[] expectedValues = { "0", "64", "ff" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16)); } } [Fact] public static void FromByteInvalidBase() { AssertExtensions.Throws<ArgumentException>(null, () => Convert.ToString(byte.MaxValue, 13)); } [Fact] public static void FromInt16Base2() { short[] testValues = { short.MinValue, 0, short.MaxValue }; string[] expectedValues = { "1000000000000000", "0", "111111111111111" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2)); } } [Fact] public static void FromInt16Base8() { short[] testValues = { short.MinValue, 0, short.MaxValue }; string[] expectedValues = { "100000", "0", "77777" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8)); } } [Fact] public static void FromInt16Base10() { short[] testValues = { short.MinValue, 0, short.MaxValue }; string[] expectedValues = { "-32768", "0", "32767" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10)); } } [Fact] public static void FromInt16Base16() { short[] testValues = { short.MinValue, 0, short.MaxValue }; string[] expectedValues = { "8000", "0", "7fff" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16)); } } [Fact] public static void FromInt16InvalidBase() { AssertExtensions.Throws<ArgumentException>(null, () => Convert.ToString(short.MaxValue, 0)); } [Fact] public static void FromInt32Base2() { int[] testValues = { int.MinValue, 0, int.MaxValue }; string[] expectedValues = { "10000000000000000000000000000000", "0", "1111111111111111111111111111111" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2)); } } [Fact] public static void FromInt32Base8() { int[] testValues = { int.MinValue, 0, int.MaxValue }; string[] expectedValues = { "20000000000", "0", "17777777777" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8)); } } [Fact] public static void FromInt32Base10() { int[] testValues = { int.MinValue, 0, int.MaxValue }; string[] expectedValues = { "-2147483648", "0", "2147483647" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10)); } } [Fact] public static void FromInt32Base16() { int[] testValues = { int.MinValue, 0, int.MaxValue }; string[] expectedValues = { "80000000", "0", "7fffffff" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16)); } } [Fact] public static void FromInt32InvalidBase() { AssertExtensions.Throws<ArgumentException>(null, () => Convert.ToString(int.MaxValue, 9)); } [Fact] public static void FromInt64Base2() { long[] testValues = { long.MinValue, 0, long.MaxValue }; string[] expectedValues = { "1000000000000000000000000000000000000000000000000000000000000000", "0", "111111111111111111111111111111111111111111111111111111111111111" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2)); } } [Fact] public static void FromInt64Base8() { long[] testValues = { long.MinValue, 0, long.MaxValue }; string[] expectedValues = { "1000000000000000000000", "0", "777777777777777777777" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8)); } } [Fact] public static void FromInt64Base10() { long[] testValues = { long.MinValue, 0, long.MaxValue }; string[] expectedValues = { "-9223372036854775808", "0", "9223372036854775807" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10)); } } [Fact] public static void FromInt64Base16() { long[] testValues = { long.MinValue, 0, long.MaxValue }; string[] expectedValues = { "8000000000000000", "0", "7fffffffffffffff" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16)); } } [Fact] public static void FromInt64InvalidBase() { AssertExtensions.Throws<ArgumentException>(null, () => Convert.ToString(long.MaxValue, 1)); } [Fact] public static void FromBoolean() { bool[] testValues = new[] { true, false }; for (int i = 0; i < testValues.Length; i++) { string expected = testValues[i].ToString(); string actual = Convert.ToString(testValues[i]); Assert.Equal(expected, actual); actual = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(expected, actual); } } [Fact] public static void FromSByte() { sbyte[] testValues = new sbyte[] { sbyte.MinValue, -1, 0, 1, sbyte.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromByte() { byte[] testValues = new byte[] { byte.MinValue, 0, 1, 100, byte.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromInt16Array() { short[] testValues = new short[] { short.MinValue, -1000, -1, 0, 1, 1000, short.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromUInt16Array() { ushort[] testValues = new ushort[] { ushort.MinValue, 0, 1, 1000, ushort.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromInt32Array() { int[] testValues = new int[] { int.MinValue, -1000, -1, 0, 1, 1000, int.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromUInt32Array() { uint[] testValues = new uint[] { uint.MinValue, 0, 1, 1000, uint.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromInt64Array() { long[] testValues = new long[] { long.MinValue, -1000, -1, 0, 1, 1000, long.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromUInt64Array() { ulong[] testValues = new ulong[] { ulong.MinValue, 0, 1, 1000, ulong.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromSingleArray() { float[] testValues = new float[] { float.MinValue, 0.0f, 1.0f, 1000.0f, float.MaxValue, float.NegativeInfinity, float.PositiveInfinity, float.Epsilon, float.NaN }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromDoubleArray() { double[] testValues = new double[] { double.MinValue, 0.0, 1.0, 1000.0, double.MaxValue, double.NegativeInfinity, double.PositiveInfinity, double.Epsilon, double.NaN }; // Vanilla Test Cases for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromDecimalArray() { decimal[] testValues = new decimal[] { decimal.MinValue, decimal.Parse("-1.234567890123456789012345678", NumberFormatInfo.InvariantInfo), (decimal)0.0, (decimal)1.0, (decimal)1000.0, decimal.MaxValue, decimal.One, decimal.Zero, decimal.MinusOne }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromDateTimeArray() { DateTime[] testValues = new DateTime[] { DateTime.Parse("08/15/2000 16:59:59", DateTimeFormatInfo.InvariantInfo), DateTime.Parse("01/01/0001 01:01:01", DateTimeFormatInfo.InvariantInfo) }; IFormatProvider formatProvider = DateTimeFormatInfo.GetInstance(new CultureInfo("en-US")); for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], formatProvider); string expected = testValues[i].ToString(formatProvider); Assert.Equal(expected, result); } } [Fact] public static void FromString() { string[] testValues = new string[] { "Hello", " ", "", "\0" }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(), result); } } [Fact] public static void FromIFormattable() { FooFormattable foo = new FooFormattable(3); string result = Convert.ToString(foo); Assert.Equal("FooFormattable: 3", result); result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo); Assert.Equal("System.Globalization.NumberFormatInfo: 3", result); foo = null; result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo); Assert.Equal("", result); } [Fact] public static void FromNonIConvertible() { Foo foo = new Foo(3); string result = Convert.ToString(foo); Assert.Equal("System.Tests.ConvertToStringTests+Foo", result); result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo); Assert.Equal("System.Tests.ConvertToStringTests+Foo", result); foo = null; result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo); Assert.Equal("", result); } private class FooFormattable : IFormattable { private int _value; public FooFormattable(int value) { _value = value; } public string ToString(string format, IFormatProvider formatProvider) { if (formatProvider != null) { return string.Format("{0}: {1}", formatProvider, _value); } else { return string.Format("FooFormattable: {0}", (_value)); } } } private class Foo { private int _value; public Foo(int value) { _value = value; } public string ToString(IFormatProvider provider) { if (provider != null) { return string.Format("{0}: {1}", provider, _value); } else { return string.Format("Foo: {0}", _value); } } } } }
/* * 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 OpenSim 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.Collections.Generic; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Physics.Manager; namespace OpenSim.Region.Physics.BasicPhysicsPlugin { /// <summary> /// Effectively a physics plugin that simulates no physics at all. /// </summary> public class BasicPhysicsPlugin : IPhysicsPlugin { public BasicPhysicsPlugin() { } public bool Init() { return true; } public PhysicsScene GetScene(string sceneIdentifier) { return new BasicScene(sceneIdentifier); } public string GetName() { return ("basicphysics"); } public void Dispose() { } } public class BasicScene : PhysicsScene { private List<BasicActor> _actors = new List<BasicActor>(); private float[] _heightMap; //protected internal string sceneIdentifier; public BasicScene(string _sceneIdentifier) { //sceneIdentifier = _sceneIdentifier; } public override void Initialise(IMesher meshmerizer, IConfigSource config) { // Does nothing right now } public override void Dispose() { } public override PhysicsActor AddAvatar(string avName, OpenMetaverse.Vector3 position, OpenMetaverse.Vector3 size, bool isFlying) { BasicActor act = new BasicActor(); act.Position = position; act.Flying = isFlying; _actors.Add(act); return act; } public override void RemovePrim(PhysicsActor prim) { } public override void RemoveAvatar(PhysicsActor actor) { BasicActor act = (BasicActor) actor; if (_actors.Contains(act)) { _actors.Remove(act); } } /* public override PhysicsActor AddPrim(OpenMetaverse.Vector3 position, OpenMetaverse.Vector3 size, Quaternion rotation) { return null; } */ public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, OpenMetaverse.Vector3 position, OpenMetaverse.Vector3 size, Quaternion rotation) { return AddPrimShape(primName, pbs, position, size, rotation, false); } public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, OpenMetaverse.Vector3 position, OpenMetaverse.Vector3 size, Quaternion rotation, bool isPhysical) { return null; } public override void AddPhysicsActorTaint(PhysicsActor prim) { } public override float Simulate(float timeStep) { float fps = 0; for (int i = 0; i < _actors.Count; ++i) { BasicActor actor = _actors[i]; actor.Position.X += actor.Velocity.X*timeStep; actor.Position.Y += actor.Velocity.Y*timeStep; if (actor.Position.Y < 0) { actor.Position.Y = 0.1F; } else if (actor.Position.Y >= Constants.RegionSize) { actor.Position.Y = 255.9F; } if (actor.Position.X < 0) { actor.Position.X = 0.1F; } else if (actor.Position.X >= Constants.RegionSize) { actor.Position.X = 255.9F; } float height = _heightMap[(int)actor.Position.Y * Constants.RegionSize + (int)actor.Position.X] + actor.Size.Z; if (actor.Flying) { if (actor.Position.Z + (actor.Velocity.Z*timeStep) < _heightMap[(int)actor.Position.Y * Constants.RegionSize + (int)actor.Position.X] + 2) { actor.Position.Z = height; actor.Velocity.Z = 0; actor.IsColliding = true; } else { actor.Position.Z += actor.Velocity.Z*timeStep; actor.IsColliding = false; } } else { actor.Position.Z = height; actor.Velocity.Z = 0; actor.IsColliding = true; } } return fps; } public override void GetResults() { } public override bool IsThreaded { get { return (false); // for now we won't be multithreaded } } public override void SetTerrain(float[] heightMap) { _heightMap = heightMap; } public override void SetWaterLevel(float baseheight) { } public override void DeleteTerrain() { } public override Dictionary<uint, float> GetTopColliders() { Dictionary<uint, float> returncolliders = new Dictionary<uint, float>(); return returncolliders; } } public class BasicActor : PhysicsActor { private OpenMetaverse.Vector3 _position; private OpenMetaverse.Vector3 _velocity; private OpenMetaverse.Vector3 _acceleration; private OpenMetaverse.Vector3 _size; private OpenMetaverse.Vector3 m_rotationalVelocity = OpenMetaverse.Vector3.Zero; private bool flying; private bool iscolliding; public BasicActor() { _velocity = new OpenMetaverse.Vector3(); _position = new OpenMetaverse.Vector3(); _acceleration = new OpenMetaverse.Vector3(); _size = new OpenMetaverse.Vector3(); } public override int PhysicsActorType { get { return (int) ActorTypes.Agent; } set { return; } } public override OpenMetaverse.Vector3 RotationalVelocity { get { return m_rotationalVelocity; } set { m_rotationalVelocity = value; } } public override bool SetAlwaysRun { get { return false; } set { return; } } public override uint LocalID { set { return; } } public override bool Grabbed { set { return; } } public override bool Selected { set { return; } } public override float Buoyancy { get { return 0f; } set { return; } } public override bool FloatOnWater { set { return; } } public override bool IsPhysical { get { return false; } set { return; } } public override bool ThrottleUpdates { get { return false; } set { return; } } public override bool Flying { get { return flying; } set { flying = value; } } public override bool IsColliding { get { return iscolliding; } set { iscolliding = value; } } public override bool CollidingGround { get { return false; } set { return; } } public override bool CollidingObj { get { return false; } set { return; } } public override bool Stopped { get { return false; } } public override OpenMetaverse.Vector3 Position { get { return _position; } set { _position = value; } } public override OpenMetaverse.Vector3 Size { get { return _size; } set { _size = value; _size.Z = _size.Z / 2.0f; } } public override PrimitiveBaseShape Shape { set { return; } } public override float Mass { get { return 0f; } } public override OpenMetaverse.Vector3 Force { get { return OpenMetaverse.Vector3.Zero; } set { return; } } public override int VehicleType { get { return 0; } set { return; } } public override void VehicleFloatParam(int param, float value) { } public override void VehicleVectorParam(int param, OpenMetaverse.Vector3 value) { } public override void VehicleRotationParam(int param, Quaternion rotation) { } public override void SetVolumeDetect(int param) { } public override OpenMetaverse.Vector3 CenterOfMass { get { return OpenMetaverse.Vector3.Zero; } } public override OpenMetaverse.Vector3 GeometricCenter { get { return OpenMetaverse.Vector3.Zero; } } public override OpenMetaverse.Vector3 Velocity { get { return _velocity; } set { _velocity = value; } } public override OpenMetaverse.Vector3 Torque { get { return OpenMetaverse.Vector3.Zero; } set { return; } } public override float CollisionScore { get { return 0f; } set { } } public override Quaternion Orientation { get { return Quaternion.Identity; } set { } } public override OpenMetaverse.Vector3 Acceleration { get { return _acceleration; } } public override bool Kinematic { get { return true; } set { } } public override void link(PhysicsActor obj) { } public override void delink() { } public override void LockAngularMotion(OpenMetaverse.Vector3 axis) { } public void SetAcceleration(OpenMetaverse.Vector3 accel) { _acceleration = accel; } public override void AddForce(OpenMetaverse.Vector3 force, bool pushforce) { } public override void AddAngularForce(OpenMetaverse.Vector3 force, bool pushforce) { } public override void SetMomentum(OpenMetaverse.Vector3 momentum) { } public override void CrossingFailure() { } public override OpenMetaverse.Vector3 PIDTarget { set { return; } } public override bool PIDActive { set { return; } } public override float PIDTau { set { return; } } public override float PIDHoverHeight { set { return; } } public override bool PIDHoverActive { set { return; } } public override PIDHoverType PIDHoverType { set { return; } } public override float PIDHoverTau { set { return; } } public override void SubscribeEvents(int ms) { } public override void UnSubscribeEvents() { } public override bool SubscribedEvents() { return false; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The type WorkbookChartRequestBuilder. /// </summary> public partial class WorkbookChartRequestBuilder : EntityRequestBuilder, IWorkbookChartRequestBuilder { /// <summary> /// Constructs a new WorkbookChartRequestBuilder. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> public WorkbookChartRequestBuilder( string requestUrl, IBaseClient client) : base(requestUrl, client) { } /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> public new IWorkbookChartRequest Request() { return this.Request(null); } /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> public new IWorkbookChartRequest Request(IEnumerable<Option> options) { return new WorkbookChartRequest(this.RequestUrl, this.Client, options); } /// <summary> /// Gets the request builder for Axes. /// </summary> /// <returns>The <see cref="IWorkbookChartAxesRequestBuilder"/>.</returns> public IWorkbookChartAxesRequestBuilder Axes { get { return new WorkbookChartAxesRequestBuilder(this.AppendSegmentToRequestUrl("axes"), this.Client); } } /// <summary> /// Gets the request builder for DataLabels. /// </summary> /// <returns>The <see cref="IWorkbookChartDataLabelsRequestBuilder"/>.</returns> public IWorkbookChartDataLabelsRequestBuilder DataLabels { get { return new WorkbookChartDataLabelsRequestBuilder(this.AppendSegmentToRequestUrl("dataLabels"), this.Client); } } /// <summary> /// Gets the request builder for Format. /// </summary> /// <returns>The <see cref="IWorkbookChartAreaFormatRequestBuilder"/>.</returns> public IWorkbookChartAreaFormatRequestBuilder Format { get { return new WorkbookChartAreaFormatRequestBuilder(this.AppendSegmentToRequestUrl("format"), this.Client); } } /// <summary> /// Gets the request builder for Legend. /// </summary> /// <returns>The <see cref="IWorkbookChartLegendRequestBuilder"/>.</returns> public IWorkbookChartLegendRequestBuilder Legend { get { return new WorkbookChartLegendRequestBuilder(this.AppendSegmentToRequestUrl("legend"), this.Client); } } /// <summary> /// Gets the request builder for Series. /// </summary> /// <returns>The <see cref="IWorkbookChartSeriesCollectionRequestBuilder"/>.</returns> public IWorkbookChartSeriesCollectionRequestBuilder Series { get { return new WorkbookChartSeriesCollectionRequestBuilder(this.AppendSegmentToRequestUrl("series"), this.Client); } } /// <summary> /// Gets the request builder for Title. /// </summary> /// <returns>The <see cref="IWorkbookChartTitleRequestBuilder"/>.</returns> public IWorkbookChartTitleRequestBuilder Title { get { return new WorkbookChartTitleRequestBuilder(this.AppendSegmentToRequestUrl("title"), this.Client); } } /// <summary> /// Gets the request builder for Worksheet. /// </summary> /// <returns>The <see cref="IWorkbookWorksheetRequestBuilder"/>.</returns> public IWorkbookWorksheetRequestBuilder Worksheet { get { return new WorkbookWorksheetRequestBuilder(this.AppendSegmentToRequestUrl("worksheet"), this.Client); } } /// <summary> /// Gets the request builder for WorkbookChartSetData. /// </summary> /// <returns>The <see cref="IWorkbookChartSetDataRequestBuilder"/>.</returns> public IWorkbookChartSetDataRequestBuilder SetData( string seriesBy, Newtonsoft.Json.Linq.JToken sourceData = null) { return new WorkbookChartSetDataRequestBuilder( this.AppendSegmentToRequestUrl("microsoft.graph.setData"), this.Client, seriesBy, sourceData); } /// <summary> /// Gets the request builder for WorkbookChartSetPosition. /// </summary> /// <returns>The <see cref="IWorkbookChartSetPositionRequestBuilder"/>.</returns> public IWorkbookChartSetPositionRequestBuilder SetPosition( Newtonsoft.Json.Linq.JToken startCell = null, Newtonsoft.Json.Linq.JToken endCell = null) { return new WorkbookChartSetPositionRequestBuilder( this.AppendSegmentToRequestUrl("microsoft.graph.setPosition"), this.Client, startCell, endCell); } /// <summary> /// Gets the request builder for WorkbookChartImage. /// </summary> /// <returns>The <see cref="IWorkbookChartImageRequestBuilder"/>.</returns> public IWorkbookChartImageRequestBuilder Image() { return new WorkbookChartImageRequestBuilder( this.AppendSegmentToRequestUrl("microsoft.graph.image"), this.Client); } /// <summary> /// Gets the request builder for WorkbookChartImage. /// </summary> /// <returns>The <see cref="IWorkbookChartImageRequestBuilder"/>.</returns> public IWorkbookChartImageRequestBuilder Image( Int32 width) { return new WorkbookChartImageRequestBuilder( this.AppendSegmentToRequestUrl("microsoft.graph.image"), this.Client, width); } /// <summary> /// Gets the request builder for WorkbookChartImage. /// </summary> /// <returns>The <see cref="IWorkbookChartImageRequestBuilder"/>.</returns> public IWorkbookChartImageRequestBuilder Image( Int32 width, Int32 height) { return new WorkbookChartImageRequestBuilder( this.AppendSegmentToRequestUrl("microsoft.graph.image"), this.Client, width, height); } /// <summary> /// Gets the request builder for WorkbookChartImage. /// </summary> /// <returns>The <see cref="IWorkbookChartImageRequestBuilder"/>.</returns> public IWorkbookChartImageRequestBuilder Image( Int32 width, Int32 height, string fittingMode) { return new WorkbookChartImageRequestBuilder( this.AppendSegmentToRequestUrl("microsoft.graph.image"), this.Client, width, height, fittingMode); } } }
using Bridge.Contract; using Bridge.Contract.Constants; using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.Semantics; using ICSharpCode.NRefactory.TypeSystem; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Bridge.Translator { public class IndexerAccessor { public IAttribute InlineAttr { get; set; } public string InlineCode { get; set; } public IMethod Method { get; set; } public bool IgnoreAccessor { get; set; } } public class IndexerBlock : ConversionBlock { private bool isRefArg; public IndexerBlock(IEmitter emitter, IndexerExpression indexerExpression) : base(emitter, indexerExpression) { this.Emitter = emitter; this.IndexerExpression = indexerExpression; } public IndexerExpression IndexerExpression { get; set; } protected override Expression GetExpression() { return this.IndexerExpression; } protected override void EmitConversionExpression() { this.VisitIndexerExpression(); } protected void VisitIndexerExpression() { this.isRefArg = this.Emitter.IsRefArg; this.Emitter.IsRefArg = false; IndexerExpression indexerExpression = this.IndexerExpression; int pos = this.Emitter.Output.Length; var resolveResult = this.Emitter.Resolver.ResolveNode(indexerExpression, this.Emitter); var memberResolveResult = resolveResult as MemberResolveResult; var arrayAccess = resolveResult as ArrayAccessResolveResult; if (arrayAccess != null && arrayAccess.Indexes.Count > 1) { this.EmitMultiDimArrayAccess(indexerExpression); Helpers.CheckValueTypeClone(resolveResult, indexerExpression, this, pos); return; } var isIgnore = true; var isAccessorsIndexer = false; IProperty member = null; IndexerAccessor current = null; if (memberResolveResult != null) { var resolvedMember = memberResolveResult.Member; isIgnore = this.Emitter.Validator.IsExternalType(resolvedMember.DeclaringTypeDefinition); isAccessorsIndexer = this.Emitter.Validator.IsAccessorsIndexer(resolvedMember); var property = resolvedMember as IProperty; if (property != null) { member = property; current = IndexerBlock.GetIndexerAccessor(this.Emitter, member, this.Emitter.IsAssignment); } } if (current != null && current.InlineAttr != null) { this.EmitInlineIndexer(indexerExpression, current); } else if (!(isIgnore || (current != null && current.IgnoreAccessor)) || isAccessorsIndexer) { this.EmitAccessorIndexer(indexerExpression, memberResolveResult, member); } else { this.EmitSingleDimArrayIndexer(indexerExpression); } Helpers.CheckValueTypeClone(resolveResult, indexerExpression, this, pos); } private void WriteInterfaceMember(string interfaceTempVar, MemberResolveResult resolveResult, bool isSetter, string prefix = null) { if (interfaceTempVar != null) { this.WriteComma(); this.Write(interfaceTempVar); } var itypeDef = resolveResult.Member.DeclaringTypeDefinition; var externalInterface = this.Emitter.Validator.IsExternalInterface(itypeDef); bool variance = MetadataUtils.IsJsGeneric(itypeDef, this.Emitter) && itypeDef.TypeParameters != null && itypeDef.TypeParameters.Any(typeParameter => typeParameter.Variance != VarianceModifier.Invariant); this.WriteOpenBracket(); if (externalInterface != null && externalInterface.IsDualImplementation || variance) { this.Write(JS.Funcs.BRIDGE_GET_I); this.WriteOpenParentheses(); if (interfaceTempVar != null) { this.Write(interfaceTempVar); } else { var oldIsAssignment = this.Emitter.IsAssignment; var oldUnary = this.Emitter.IsUnaryAccessor; this.Emitter.IsAssignment = false; this.Emitter.IsUnaryAccessor = false; this.IndexerExpression.Target.AcceptVisitor(this.Emitter); this.Emitter.IsAssignment = oldIsAssignment; this.Emitter.IsUnaryAccessor = oldUnary; } this.WriteComma(); var interfaceName = Helpers.GetPropertyRef(resolveResult.Member, this.Emitter, isSetter, ignoreInterface:false); if (interfaceName.StartsWith("\"")) { this.Write(interfaceName); } else { this.WriteScript(interfaceName); } if (variance) { this.WriteComma(); this.WriteScript(Helpers.GetPropertyRef(resolveResult.Member, this.Emitter, isSetter, ignoreInterface: false, withoutTypeParams:true)); } this.Write(")"); } else if (externalInterface == null || externalInterface.IsNativeImplementation) { this.Write(Helpers.GetPropertyRef(resolveResult.Member, this.Emitter, isSetter, ignoreInterface: false)); } else { this.Write(Helpers.GetPropertyRef(resolveResult.Member, this.Emitter, isSetter, ignoreInterface: true)); } this.WriteCloseBracket(); if (interfaceTempVar != null) { this.WriteCloseParentheses(); } } public static IndexerAccessor GetIndexerAccessor(IEmitter emitter, IProperty member, bool setter) { var method = setter ? member.Setter : member.Getter; if (method == null) { return null; } var inlineAttr = emitter.GetAttribute(method.Attributes, Translator.Bridge_ASSEMBLY + ".TemplateAttribute"); var ignoreAccessor = emitter.Validator.IsExternalType(method); return new IndexerAccessor { IgnoreAccessor = ignoreAccessor, InlineAttr = inlineAttr, InlineCode = emitter.GetInline(method), Method = method }; } protected virtual void EmitInlineIndexer(IndexerExpression indexerExpression, IndexerAccessor current) { var oldIsAssignment = this.Emitter.IsAssignment; var oldUnary = this.Emitter.IsUnaryAccessor; var inlineCode = current.InlineCode; var rr = this.Emitter.Resolver.ResolveNode(indexerExpression, this.Emitter) as MemberResolveResult; if (rr != null) { inlineCode = Helpers.ConvertTokens(this.Emitter, inlineCode, rr.Member); } bool hasThis = inlineCode != null && inlineCode.Contains("{this}"); if (inlineCode != null && inlineCode.StartsWith("<self>")) { hasThis = true; inlineCode = inlineCode.Substring(6); } if (!hasThis && current.InlineAttr != null) { this.Emitter.IsAssignment = false; this.Emitter.IsUnaryAccessor = false; indexerExpression.Target.AcceptVisitor(this.Emitter); this.Emitter.IsAssignment = oldIsAssignment; this.Emitter.IsUnaryAccessor = oldUnary; } if (hasThis) { this.Write(""); var oldBuilder = this.Emitter.Output; this.Emitter.Output = new StringBuilder(); this.Emitter.IsAssignment = false; this.Emitter.IsUnaryAccessor = false; indexerExpression.Target.AcceptVisitor(this.Emitter); int thisIndex = inlineCode.IndexOf("{this}"); var thisArg = this.Emitter.Output.ToString(); inlineCode = inlineCode.Replace("{this}", thisArg); this.Emitter.Output = new StringBuilder(); inlineCode = inlineCode.Replace("{value}", "[[value]]"); new InlineArgumentsBlock(this.Emitter, new ArgumentsInfo(this.Emitter, indexerExpression, rr as InvocationResolveResult), inlineCode).Emit(); inlineCode = this.Emitter.Output.ToString(); inlineCode = inlineCode.Replace("[[value]]", "{0}"); this.Emitter.IsAssignment = oldIsAssignment; this.Emitter.IsUnaryAccessor = oldUnary; this.Emitter.Output = oldBuilder; int[] range = null; if (thisIndex > -1) { range = new[] { thisIndex, thisIndex + thisArg.Length }; } this.PushWriter(inlineCode, null, thisArg, range); if (!this.Emitter.IsAssignment) { this.PopWriter(); } return; } if (inlineCode != null) { this.WriteDot(); this.PushWriter(inlineCode); this.Emitter.IsAssignment = false; this.Emitter.IsUnaryAccessor = false; new ExpressionListBlock(this.Emitter, indexerExpression.Arguments, null, null, 0).Emit(); this.Emitter.IsAssignment = oldIsAssignment; this.Emitter.IsUnaryAccessor = oldUnary; if (!this.Emitter.IsAssignment) { this.PopWriter(); } else { this.WriteComma(); } } } protected virtual void EmitAccessorIndexer(IndexerExpression indexerExpression, MemberResolveResult memberResolveResult, IProperty member) { string targetVar = null; string valueVar = null; bool writeTargetVar = false; bool isStatement = false; var oldIsAssignment = this.Emitter.IsAssignment; var oldUnary = this.Emitter.IsUnaryAccessor; var isInterfaceMember = false; bool nativeImplementation = true; var hasTypeParemeter = Helpers.IsTypeParameterType(memberResolveResult.Member.DeclaringType); var isExternalInterface = false; if (memberResolveResult.Member.DeclaringTypeDefinition != null && memberResolveResult.Member.DeclaringTypeDefinition.Kind == TypeKind.Interface) { var itypeDef = memberResolveResult.Member.DeclaringTypeDefinition; var variance = MetadataUtils.IsJsGeneric(itypeDef, this.Emitter) && itypeDef.TypeParameters != null && itypeDef.TypeParameters.Any(typeParameter => typeParameter.Variance != VarianceModifier.Invariant); if (variance) { isInterfaceMember = true; } else { var ei = this.Emitter.Validator.IsExternalInterface(memberResolveResult.Member.DeclaringTypeDefinition); if (ei != null) { nativeImplementation = ei.IsNativeImplementation; isExternalInterface = true; } else { nativeImplementation = memberResolveResult.Member.DeclaringTypeDefinition.ParentAssembly.AssemblyName == CS.NS.BRIDGE || !this.Emitter.Validator.IsExternalType(memberResolveResult.Member.DeclaringTypeDefinition); } if (ei != null && ei.IsSimpleImplementation) { nativeImplementation = false; isExternalInterface = false; } else if (hasTypeParemeter || ei != null && !nativeImplementation) { isInterfaceMember = true; writeTargetVar = true; } } } if (this.Emitter.IsUnaryAccessor) { writeTargetVar = true; isStatement = indexerExpression.Parent is UnaryOperatorExpression && indexerExpression.Parent.Parent is ExpressionStatement; if (memberResolveResult != null && NullableType.IsNullable(memberResolveResult.Type)) { isStatement = false; } if (!isStatement) { this.WriteOpenParentheses(); } } var targetrr = this.Emitter.Resolver.ResolveNode(indexerExpression.Target, this.Emitter); var memberTargetrr = targetrr as MemberResolveResult; bool isField = memberTargetrr != null && memberTargetrr.Member is IField && (memberTargetrr.TargetResult is ThisResolveResult || memberTargetrr.TargetResult is TypeResolveResult || memberTargetrr.TargetResult is LocalResolveResult); bool isSimple = targetrr is ThisResolveResult || targetrr is LocalResolveResult || targetrr is ConstantResolveResult || isField; bool needTemp = isExternalInterface && !nativeImplementation && !isSimple; if (isInterfaceMember && (!this.Emitter.IsUnaryAccessor || isStatement) && needTemp) { this.WriteOpenParentheses(); } if (writeTargetVar) { if (needTemp) { targetVar = this.GetTempVarName(); this.Write(targetVar); this.Write(" = "); } } if (this.Emitter.IsUnaryAccessor && !isStatement && targetVar == null) { valueVar = this.GetTempVarName(); this.Write(valueVar); this.Write(" = "); } this.Emitter.IsAssignment = false; this.Emitter.IsUnaryAccessor = false; indexerExpression.Target.AcceptVisitor(this.Emitter); this.Emitter.IsAssignment = oldIsAssignment; this.Emitter.IsUnaryAccessor = oldUnary; if (targetVar != null) { if (this.Emitter.IsUnaryAccessor && !isStatement) { this.WriteComma(false); valueVar = this.GetTempVarName(); this.Write(valueVar); this.Write(" = "); this.Write(targetVar); } else if (!isInterfaceMember) { this.WriteSemiColon(); this.WriteNewLine(); this.Write(targetVar); } } if (!isInterfaceMember) { this.WriteDot(); } bool isBase = indexerExpression.Target is BaseReferenceExpression; var argsInfo = new ArgumentsInfo(this.Emitter, indexerExpression); var argsExpressions = argsInfo.ArgumentsExpressions; var paramsArg = argsInfo.ParamsExpression; var name = Helpers.GetPropertyRef(member, this.Emitter, this.Emitter.IsAssignment, ignoreInterface: !nativeImplementation); if (!this.Emitter.IsAssignment) { if (this.Emitter.IsUnaryAccessor) { var oldWriter = this.SaveWriter(); this.NewWriter(); new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); var paramsStr = this.Emitter.Output.ToString(); this.RestoreWriter(oldWriter); bool isDecimal = Helpers.IsDecimalType(member.ReturnType, this.Emitter.Resolver); bool isLong = Helpers.Is64Type(member.ReturnType, this.Emitter.Resolver); bool isNullable = NullableType.IsNullable(member.ReturnType); if (isStatement) { if (isInterfaceMember) { this.WriteInterfaceMember(targetVar, memberResolveResult, true, JS.Funcs.Property.SET); } else { this.Write(Helpers.GetPropertyRef(memberResolveResult.Member, this.Emitter, true, ignoreInterface: !nativeImplementation)); } this.WriteOpenParentheses(); this.Write(paramsStr); this.WriteComma(false); if (isDecimal || isLong) { if (isNullable) { this.Write(JS.Types.SYSTEM_NULLABLE + "." + JS.Funcs.Math.LIFT1); this.WriteOpenParentheses(); if (this.Emitter.UnaryOperatorType == UnaryOperatorType.Increment || this.Emitter.UnaryOperatorType == UnaryOperatorType.PostIncrement) { this.WriteScript(JS.Funcs.Math.INC); } else { this.WriteScript(JS.Funcs.Math.DEC); } this.WriteComma(); if (targetVar != null) { this.Write(targetVar); } else { indexerExpression.Target.AcceptVisitor(this.Emitter); } if (!isInterfaceMember) { this.WriteDot(); this.Write(Helpers.GetPropertyRef(member, this.Emitter, false, ignoreInterface: !nativeImplementation)); } else { this.WriteInterfaceMember(targetVar, memberResolveResult, false, JS.Funcs.Property.GET); } this.WriteOpenParentheses(); this.Write(paramsStr); this.WriteCloseParentheses(); this.WriteCloseParentheses(); } else { if (targetVar != null) { this.Write(targetVar); } else { indexerExpression.Target.AcceptVisitor(this.Emitter); } if (!isInterfaceMember) { this.WriteDot(); this.Write(Helpers.GetPropertyRef(member, this.Emitter, false, ignoreInterface: !nativeImplementation)); } else { this.WriteInterfaceMember(targetVar, memberResolveResult, false, JS.Funcs.Property.GET); } this.WriteOpenParentheses(); this.Write(paramsStr); this.WriteCloseParentheses(); this.WriteDot(); if (this.Emitter.UnaryOperatorType == UnaryOperatorType.Increment || this.Emitter.UnaryOperatorType == UnaryOperatorType.PostIncrement) { this.Write(JS.Funcs.Math.INC); } else { this.Write(JS.Funcs.Math.DEC); } this.WriteOpenCloseParentheses(); } } else { if (targetVar != null) { this.Write(targetVar); } else { indexerExpression.Target.AcceptVisitor(this.Emitter); } if (!isInterfaceMember) { this.WriteDot(); this.Write(Helpers.GetPropertyRef(member, this.Emitter, false, ignoreInterface: !nativeImplementation)); } else { this.WriteInterfaceMember(targetVar, memberResolveResult, false, JS.Funcs.Property.GET); } this.WriteOpenParentheses(); this.Write(paramsStr); this.WriteCloseParentheses(); if (this.Emitter.UnaryOperatorType == UnaryOperatorType.Increment || this.Emitter.UnaryOperatorType == UnaryOperatorType.PostIncrement) { this.Write("+"); } else { this.Write("-"); } this.Write("1"); } this.WriteCloseParentheses(); } else { if (!isInterfaceMember) { this.Write(Helpers.GetPropertyRef(member, this.Emitter, false, ignoreInterface: !nativeImplementation)); } else { this.WriteInterfaceMember(targetVar, memberResolveResult, false, JS.Funcs.Property.GET); } this.WriteOpenParentheses(); this.Write(paramsStr); this.WriteCloseParentheses(); this.WriteComma(); if (targetVar != null) { this.Write(targetVar); } else { indexerExpression.Target.AcceptVisitor(this.Emitter); } if (!isInterfaceMember) { this.WriteDot(); this.Write(Helpers.GetPropertyRef(member, this.Emitter, true, ignoreInterface: !nativeImplementation)); } else { this.WriteInterfaceMember(targetVar, memberResolveResult, true, JS.Funcs.Property.SET); } this.WriteOpenParentheses(); this.Write(paramsStr); this.WriteComma(false); if (isDecimal || isLong) { if (isNullable) { this.Write(JS.Types.SYSTEM_NULLABLE + "." + JS.Funcs.Math.LIFT1); this.WriteOpenParentheses(); if (this.Emitter.UnaryOperatorType == UnaryOperatorType.Increment || this.Emitter.UnaryOperatorType == UnaryOperatorType.PostIncrement) { this.WriteScript(JS.Funcs.Math.INC); } else { this.WriteScript(JS.Funcs.Math.DEC); } this.WriteComma(); this.Write(valueVar); this.WriteCloseParentheses(); } else { this.Write(valueVar); this.WriteDot(); if (this.Emitter.UnaryOperatorType == UnaryOperatorType.Increment || this.Emitter.UnaryOperatorType == UnaryOperatorType.PostIncrement) { this.Write(JS.Funcs.Math.INC); } else { this.Write(JS.Funcs.Math.DEC); } this.WriteOpenCloseParentheses(); } } else { this.Write(valueVar); if (this.Emitter.UnaryOperatorType == UnaryOperatorType.Increment || this.Emitter.UnaryOperatorType == UnaryOperatorType.PostIncrement) { this.Write("+"); } else { this.Write("-"); } this.Write("1"); } this.WriteCloseParentheses(); this.WriteComma(); bool isPreOp = this.Emitter.UnaryOperatorType == UnaryOperatorType.Increment || this.Emitter.UnaryOperatorType == UnaryOperatorType.Decrement; if (isPreOp) { if (targetVar != null) { this.Write(targetVar); } else { indexerExpression.Target.AcceptVisitor(this.Emitter); } if (!isInterfaceMember) { this.WriteDot(); this.Write(Helpers.GetPropertyRef(member, this.Emitter, false, ignoreInterface: !nativeImplementation)); } else { this.WriteInterfaceMember(targetVar, memberResolveResult, false, JS.Funcs.Property.GET); } this.WriteOpenParentheses(); this.Write(paramsStr); this.WriteCloseParentheses(); } else { this.Write(valueVar); } this.WriteCloseParentheses(); if (valueVar != null) { this.RemoveTempVar(valueVar); } } if (targetVar != null) { this.RemoveTempVar(targetVar); } } else { if (!isInterfaceMember) { this.Write(name); } else { this.WriteInterfaceMember(targetVar, memberResolveResult, this.Emitter.IsAssignment, Helpers.GetSetOrGet(this.Emitter.IsAssignment)); } if (isBase) { this.WriteCall(); this.WriteOpenParentheses(); this.WriteThis(); this.WriteComma(false); } else { this.WriteOpenParentheses(); } new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); this.WriteCloseParentheses(); } } else { if (this.Emitter.AssignmentType != AssignmentOperatorType.Assign) { var oldWriter = this.SaveWriter(); this.NewWriter(); new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); var paramsStr = this.Emitter.Output.ToString(); this.RestoreWriter(oldWriter); string memberStr; if (isInterfaceMember) { oldWriter = this.SaveWriter(); this.NewWriter(); this.Emitter.IsAssignment = false; this.Emitter.IsUnaryAccessor = false; this.WriteInterfaceMember(targetVar, memberResolveResult, this.Emitter.IsAssignment, Helpers.GetSetOrGet(this.Emitter.IsAssignment)); this.Emitter.IsAssignment = oldIsAssignment; this.Emitter.IsUnaryAccessor = oldUnary; memberStr = this.Emitter.Output.ToString(); this.RestoreWriter(oldWriter); } else { memberStr = name; } string getterMember; if (isInterfaceMember) { oldWriter = this.SaveWriter(); this.NewWriter(); this.Emitter.IsAssignment = false; this.Emitter.IsUnaryAccessor = false; this.WriteInterfaceMember(targetVar, memberResolveResult, false, JS.Funcs.Property.GET); this.Emitter.IsAssignment = oldIsAssignment; this.Emitter.IsUnaryAccessor = oldUnary; getterMember = this.Emitter.Output.ToString(); this.RestoreWriter(oldWriter); } else { getterMember = "." + Helpers.GetPropertyRef(memberResolveResult.Member, this.Emitter, false, ignoreInterface: !nativeImplementation); } if (targetVar != null) { this.PushWriter(string.Concat( memberStr, "(", paramsStr, ", ", targetVar, getterMember, isBase ? "." + JS.Funcs.CALL : "", "(", isBase ? "this, " : "", paramsStr, ") {0})")); this.RemoveTempVar(targetVar); } else { oldWriter = this.SaveWriter(); this.NewWriter(); this.Emitter.IsAssignment = false; this.Emitter.IsUnaryAccessor = false; indexerExpression.Target.AcceptVisitor(this.Emitter); this.Emitter.IsAssignment = oldIsAssignment; this.Emitter.IsUnaryAccessor = oldUnary; var trg = this.Emitter.Output.ToString(); this.RestoreWriter(oldWriter); this.PushWriter(string.Concat( memberStr, "(", paramsStr, ", ", trg, getterMember, isBase ? "." + JS.Funcs.CALL : "", "(", isBase ? "this, " : "", paramsStr, ") {0})")); } } else { if (!isInterfaceMember) { this.Write(name); } else { this.WriteInterfaceMember(targetVar, memberResolveResult, this.Emitter.IsAssignment, Helpers.GetSetOrGet(this.Emitter.IsAssignment)); } if (isBase) { this.WriteCall(); this.WriteOpenParentheses(); this.WriteThis(); this.WriteComma(false); } else { this.WriteOpenParentheses(); } this.Emitter.IsAssignment = false; this.Emitter.IsUnaryAccessor = false; new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); this.Emitter.IsAssignment = oldIsAssignment; this.Emitter.IsUnaryAccessor = oldUnary; this.PushWriter(", {0})"); } } } protected virtual void EmitMultiDimArrayAccess(IndexerExpression indexerExpression) { string targetVar = null; bool writeTargetVar = false; bool isStatement = false; string valueVar = null; var resolveResult = this.Emitter.Resolver.ResolveNode(indexerExpression, this.Emitter); if (this.Emitter.IsAssignment && this.Emitter.AssignmentType != AssignmentOperatorType.Assign) { writeTargetVar = true; } else if (this.Emitter.IsUnaryAccessor) { writeTargetVar = true; isStatement = indexerExpression.Parent is UnaryOperatorExpression && indexerExpression.Parent.Parent is ExpressionStatement; if (NullableType.IsNullable(resolveResult.Type)) { isStatement = false; } if (!isStatement) { this.WriteOpenParentheses(); } } if (writeTargetVar) { var targetrr = this.Emitter.Resolver.ResolveNode(indexerExpression.Target, this.Emitter); var memberTargetrr = targetrr as MemberResolveResult; bool isField = memberTargetrr != null && memberTargetrr.Member is IField && (memberTargetrr.TargetResult is ThisResolveResult || memberTargetrr.TargetResult is LocalResolveResult); if (!(targetrr is ThisResolveResult || targetrr is LocalResolveResult || isField)) { targetVar = this.GetTempVarName(); this.Write(targetVar); this.Write(" = "); } } if (this.Emitter.IsUnaryAccessor && !isStatement && targetVar == null) { valueVar = this.GetTempVarName(); this.Write(valueVar); this.Write(" = "); } var oldIsAssignment = this.Emitter.IsAssignment; var oldUnary = this.Emitter.IsUnaryAccessor; this.Emitter.IsAssignment = false; this.Emitter.IsUnaryAccessor = false; indexerExpression.Target.AcceptVisitor(this.Emitter); this.Emitter.IsAssignment = oldIsAssignment; this.Emitter.IsUnaryAccessor = oldUnary; if (targetVar != null) { if (this.Emitter.IsUnaryAccessor && !isStatement) { this.WriteComma(false); valueVar = this.GetTempVarName(); this.Write(valueVar); this.Write(" = "); this.Write(targetVar); } else { this.WriteSemiColon(); this.WriteNewLine(); this.Write(targetVar); } } if (this.isRefArg) { this.WriteComma(); } else { this.WriteDot(); } var argsInfo = new ArgumentsInfo(this.Emitter, indexerExpression); var argsExpressions = argsInfo.ArgumentsExpressions; var paramsArg = argsInfo.ParamsExpression; if (!this.Emitter.IsAssignment) { if (this.Emitter.IsUnaryAccessor) { bool isDecimal = Helpers.IsDecimalType(resolveResult.Type, this.Emitter.Resolver); bool isLong = Helpers.Is64Type(resolveResult.Type, this.Emitter.Resolver); bool isNullable = NullableType.IsNullable(resolveResult.Type); if (isStatement) { this.Write(JS.Funcs.Property.SET); this.WriteOpenParentheses(); this.WriteOpenBracket(); new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); this.WriteCloseBracket(); this.WriteComma(false); if (isDecimal || isLong) { if (isNullable) { this.Write(JS.Types.SYSTEM_NULLABLE + "." + JS.Funcs.Math.LIFT1); this.WriteOpenParentheses(); if (this.Emitter.UnaryOperatorType == UnaryOperatorType.Increment || this.Emitter.UnaryOperatorType == UnaryOperatorType.PostIncrement) { this.WriteScript(JS.Funcs.Math.INC); } else { this.WriteScript(JS.Funcs.Math.DEC); } this.WriteComma(); if (targetVar != null) { this.Write(targetVar); } else { indexerExpression.Target.AcceptVisitor(this.Emitter); } this.WriteDot(); this.Write(JS.Funcs.Property.GET); this.WriteOpenParentheses(); this.WriteOpenBracket(); new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); this.WriteCloseBracket(); this.WriteCloseParentheses(); this.WriteCloseParentheses(); } else { if (targetVar != null) { this.Write(targetVar); } else { indexerExpression.Target.AcceptVisitor(this.Emitter); } this.WriteDot(); this.Write(JS.Funcs.Property.GET); this.WriteOpenParentheses(); this.WriteOpenBracket(); new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); this.WriteCloseBracket(); this.WriteCloseParentheses(); this.WriteDot(); if (this.Emitter.UnaryOperatorType == UnaryOperatorType.Increment || this.Emitter.UnaryOperatorType == UnaryOperatorType.PostIncrement) { this.Write(JS.Funcs.Math.INC); } else { this.Write(JS.Funcs.Math.DEC); } this.WriteOpenCloseParentheses(); } } else { if (targetVar != null) { this.Write(targetVar); } else { indexerExpression.Target.AcceptVisitor(this.Emitter); } this.WriteDot(); this.Write(JS.Funcs.Property.GET); this.WriteOpenParentheses(); this.WriteOpenBracket(); new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); this.WriteCloseBracket(); this.WriteCloseParentheses(); if (this.Emitter.UnaryOperatorType == UnaryOperatorType.Increment || this.Emitter.UnaryOperatorType == UnaryOperatorType.PostIncrement) { this.Write("+"); } else { this.Write("-"); } this.Write("1"); } this.WriteCloseParentheses(); } else { this.Write(JS.Funcs.Property.GET); this.WriteOpenParentheses(); this.WriteOpenBracket(); new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); this.WriteCloseBracket(); this.WriteCloseParentheses(); this.WriteComma(); if (targetVar != null) { this.Write(targetVar); } else { indexerExpression.Target.AcceptVisitor(this.Emitter); } this.WriteDot(); this.Write(JS.Funcs.Property.SET); this.WriteOpenParentheses(); this.WriteOpenBracket(); new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); this.WriteCloseBracket(); this.WriteComma(false); if (isDecimal || isLong) { if (isNullable) { this.Write(JS.Types.SYSTEM_NULLABLE + "." + JS.Funcs.Math.LIFT1); this.WriteOpenParentheses(); if (this.Emitter.UnaryOperatorType == UnaryOperatorType.Increment || this.Emitter.UnaryOperatorType == UnaryOperatorType.PostIncrement) { this.WriteScript(JS.Funcs.Math.INC); } else { this.WriteScript(JS.Funcs.Math.DEC); } this.WriteComma(); this.Write(valueVar); this.WriteDot(); this.Write(JS.Funcs.Property.GET); this.WriteOpenParentheses(); this.WriteOpenBracket(); new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); this.WriteCloseBracket(); this.WriteCloseParentheses(); this.WriteCloseParentheses(); } else { if (targetVar != null) { this.Write(targetVar); } else { indexerExpression.Target.AcceptVisitor(this.Emitter); } this.WriteDot(); this.Write(JS.Funcs.Property.GET); this.WriteOpenParentheses(); this.WriteOpenBracket(); new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); this.WriteCloseBracket(); this.WriteCloseParentheses(); this.WriteDot(); if (this.Emitter.UnaryOperatorType == UnaryOperatorType.Increment || this.Emitter.UnaryOperatorType == UnaryOperatorType.PostIncrement) { this.Write(JS.Funcs.Math.INC); } else { this.Write(JS.Funcs.Math.DEC); } this.WriteOpenCloseParentheses(); } } else { this.Write(valueVar); if (this.Emitter.UnaryOperatorType == UnaryOperatorType.Increment || this.Emitter.UnaryOperatorType == UnaryOperatorType.PostIncrement) { this.Write("+"); } else { this.Write("-"); } this.Write("1"); } this.WriteCloseParentheses(); this.WriteComma(); var isPreOp = this.Emitter.UnaryOperatorType == UnaryOperatorType.Increment || this.Emitter.UnaryOperatorType == UnaryOperatorType.Decrement; if (isPreOp) { if (targetVar != null) { this.Write(targetVar); } else { indexerExpression.Target.AcceptVisitor(this.Emitter); } this.WriteDot(); this.Write(JS.Funcs.Property.GET); this.WriteOpenParentheses(); this.WriteOpenBracket(); new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); this.WriteCloseBracket(); this.WriteCloseParentheses(); } else { this.Write(valueVar); } this.WriteCloseParentheses(); if (valueVar != null) { this.RemoveTempVar(valueVar); } } if (targetVar != null) { this.RemoveTempVar(targetVar); } } else { if (!this.isRefArg) { this.Write(JS.Funcs.Property.GET); this.WriteOpenParentheses(); } this.WriteOpenBracket(); new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); this.WriteCloseBracket(); if (!this.isRefArg) { this.WriteCloseParentheses(); } } } else { if (this.Emitter.AssignmentType != AssignmentOperatorType.Assign) { var oldWriter = this.SaveWriter(); this.NewWriter(); new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); var paramsStr = this.Emitter.Output.ToString(); this.RestoreWriter(oldWriter); if (targetVar != null) { this.PushWriter(string.Concat( JS.Funcs.Property.SET, "([", paramsStr, "],", targetVar, ".get([", paramsStr, "]) {0})"), () => { this.RemoveTempVar(targetVar); }); } else { oldWriter = this.SaveWriter(); this.NewWriter(); this.Emitter.IsAssignment = false; this.Emitter.IsUnaryAccessor = false; indexerExpression.Target.AcceptVisitor(this.Emitter); this.Emitter.IsAssignment = oldIsAssignment; this.Emitter.IsUnaryAccessor = oldUnary; var trg = this.Emitter.Output.ToString(); this.RestoreWriter(oldWriter); this.PushWriter(string.Concat( JS.Funcs.Property.SET, "([", paramsStr, "],", trg, ".get([", paramsStr, "]) {0})")); } } else { this.Write(JS.Funcs.Property.SET); this.WriteOpenParentheses(); this.WriteOpenBracket(); new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, null, 0).Emit(); this.WriteCloseBracket(); this.PushWriter(", {0})"); } } } protected virtual void EmitSingleDimArrayIndexer(IndexerExpression indexerExpression) { var oldIsAssignment = this.Emitter.IsAssignment; var oldUnary = this.Emitter.IsUnaryAccessor; this.Emitter.IsAssignment = false; this.Emitter.IsUnaryAccessor = false; var targetrr = this.Emitter.Resolver.ResolveNode(indexerExpression.Target, this.Emitter); var memberTargetrr = targetrr as MemberResolveResult; bool isField = memberTargetrr != null && memberTargetrr.Member is IField && (memberTargetrr.TargetResult is ThisResolveResult || memberTargetrr.TargetResult is TypeResolveResult || memberTargetrr.TargetResult is LocalResolveResult); bool isArray = targetrr.Type.Kind == TypeKind.Array && !ConversionBlock.IsInUncheckedContext(this.Emitter, indexerExpression, false); bool isSimple = !isArray || (targetrr is ThisResolveResult || targetrr is LocalResolveResult || targetrr is ConstantResolveResult || isField); string targetVar = null; if (!isSimple) { this.WriteOpenParentheses(); targetVar = this.GetTempVarName(); this.Write(targetVar); this.Write(" = "); } var rr = this.Emitter.Resolver.ResolveNode(indexerExpression, this.Emitter) as MemberResolveResult; if (indexerExpression.Target is BaseReferenceExpression && rr != null && this.Emitter.Validator.IsExternalType(rr.Member.DeclaringTypeDefinition) && !this.Emitter.Validator.IsBridgeClass(rr.Member.DeclaringTypeDefinition)) { this.Write("this"); } else { indexerExpression.Target.AcceptVisitor(this.Emitter); } if (!isSimple) { this.WriteCloseParentheses(); } this.Emitter.IsAssignment = oldIsAssignment; this.Emitter.IsUnaryAccessor = oldUnary; if (indexerExpression.Arguments.Count != 1) { throw new EmitterException(indexerExpression, "Only one index is supported"); } var index = indexerExpression.Arguments.First(); var primitive = index as PrimitiveExpression; if (!isArray && primitive != null && primitive.Value != null && Regex.Match(primitive.Value.ToString(), "^[_$a-z][_$a-z0-9]*$", RegexOptions.IgnoreCase).Success) { if (this.isRefArg) { this.WriteComma(); this.WriteScript(primitive.Value); } else { this.WriteDot(); this.Write(primitive.Value); } } else { this.Emitter.IsAssignment = false; this.Emitter.IsUnaryAccessor = false; if (this.isRefArg) { this.WriteComma(); } else { this.WriteOpenBracket(); if (isArray && this.Emitter.Rules.ArrayIndex == ArrayIndexRule.Managed) { this.Write(JS.Types.System.Array.INDEX); this.WriteOpenParentheses(); } } index.AcceptVisitor(this.Emitter); if (!this.isRefArg) { if (isArray && this.Emitter.Rules.ArrayIndex == ArrayIndexRule.Managed) { this.WriteComma(); if (targetVar != null) { this.Write(targetVar); } else { indexerExpression.Target.AcceptVisitor(this.Emitter); } this.WriteCloseParentheses(); } this.WriteCloseBracket(); } this.Emitter.IsAssignment = oldIsAssignment; this.Emitter.IsUnaryAccessor = oldUnary; } } } }
using System; using System.Net; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Personalization.Drivers; using Personalization.Repository; using Personalization.ViewModels; using TestHelpers; namespace Personalization.Test.Drivers { [TestClass] public class SearchIndexGetProductDriverTest { [TestMethod] public void CtorShouldSetPropertiesCorrectly() { // Arrange var productId = 2; var repository = new Func<ProductsDbRepository>(() => new ProductsDbRepository(() => new ProductInMemoryContext())); var driver = new SearchIndexGetProductDriver(productId, repository); // Act // Assert driver.ProductId.Should().Be(productId); driver.ProductDetail.Should().BeNull(); driver.Error.Should().BeNull(); } [TestMethod] public void GetProductShouldSetProductDetail() { // Arrange const int productId = 2; var expected = Get.AnyProductDetails(productId, "AnotherBrand", "$19.99", "another/image/url.jpg", "AnotherName", "AnotherStyleId"); var products = new[] { Get.AnyProductDetails(1, "AnyBrand", "$59.99", "any/image/url.jpg", "AnyName", "AnyStyleId"), Get.AnyProductDetails(productId, "AnotherBrand", "$19.99", "another/image/url.jpg", "AnotherName", "AnotherStyleId"), Get.AnyProductDetails(3, "AnyOtherBrand", "$29.99", "any/other/image/url.jpg", "AnyOtherName", "AnyOtherStyleId"), Get.AnyProductDetails(4, "YetAnotherBrand", "$49.99", "yet/another/image/url.jpg", "YetAnotherName", "YetAnotherStyleId"), }; var context = new ProductInMemoryContext(); foreach (var product in products) { context.Products.Add(product); } var repository = new Func<ProductsDbRepository>(() => new ProductsDbRepository(() => context)); var driver = new SearchIndexGetProductDriver(productId, repository); // Act driver.GetProduct(); // Assert driver.ProductDetail.ShouldBeEquivalentTo(expected); } [TestMethod] public void GetProductWithProductNotFountShouldNotSetProductDetail() { // Arrange const int productId = 22; var expected = Get.AnyProductDetails(productId, "AnotherBrand", "$19.99", "another/image/url.jpg", "AnotherName", "AnotherStyleId"); var products = new[] { Get.AnyProductDetails(1, "AnyBrand", "$59.99", "any/image/url.jpg", "AnyName", "AnyStyleId"), Get.AnyProductDetails(2, "AnotherBrand", "$19.99", "another/image/url.jpg", "AnotherName", "AnotherStyleId"), Get.AnyProductDetails(3, "AnyOtherBrand", "$29.99", "any/other/image/url.jpg", "AnyOtherName", "AnyOtherStyleId"), Get.AnyProductDetails(4, "YetAnotherBrand", "$49.99", "yet/another/image/url.jpg", "YetAnotherName", "YetAnotherStyleId"), }; var context = new ProductInMemoryContext(); foreach (var product in products) { context.Products.Add(product); } var repository = new Func<ProductsDbRepository>(() => new ProductsDbRepository(() => context)); var driver = new SearchIndexGetProductDriver(productId, repository); // Act driver.GetProduct(); // Assert driver.ProductDetail.Should().BeNull(); } [TestMethod] public void GetProductWithExceptionShouldNotSetProductDetail() { // Arrange const int productId = 22; var expected = Get.AnyProductDetails(productId, "AnotherBrand", "$19.99", "another/image/url.jpg", "AnotherName", "AnotherStyleId"); var products = new[] { Get.AnyProductDetails(1, "AnyBrand", "$59.99", "any/image/url.jpg", "AnyName", "AnyStyleId"), Get.AnyProductDetails(2, "AnotherBrand", "$19.99", "another/image/url.jpg", "AnotherName", "AnotherStyleId"), Get.AnyProductDetails(3, "AnyOtherBrand", "$29.99", "any/other/image/url.jpg", "AnyOtherName", "AnyOtherStyleId"), Get.AnyProductDetails(4, "YetAnotherBrand", "$49.99", "yet/another/image/url.jpg", "YetAnotherName", "YetAnotherStyleId"), }; var context = new ProductInMemoryContext(); foreach (var product in products) { context.Products.Add(product); } var repository = new Func<IProductsRepository>(() => new ProductsInMemoryRepository(() => context) { ExceptionToThrow = new ArgumentException() }); var driver = new SearchIndexGetProductDriver(productId, repository); // Act driver.GetProduct(); // Assert driver.ProductDetail.Should().BeNull(); } [TestMethod] public void GetProductWithExceptionShouldSetError() { // Arrange const int productId = 22; var expected = new HttpErrorData(HttpStatusCode.InternalServerError, "Unable to communicate with database"); var products = new[] { Get.AnyProductDetails(1, "AnyBrand", "$59.99", "any/image/url.jpg", "AnyName", "AnyStyleId"), Get.AnyProductDetails(2, "AnotherBrand", "$19.99", "another/image/url.jpg", "AnotherName", "AnotherStyleId"), Get.AnyProductDetails(3, "AnyOtherBrand", "$29.99", "any/other/image/url.jpg", "AnyOtherName", "AnyOtherStyleId"), Get.AnyProductDetails(4, "YetAnotherBrand", "$49.99", "yet/another/image/url.jpg", "YetAnotherName", "YetAnotherStyleId"), }; var context = new ProductInMemoryContext(); foreach (var product in products) { context.Products.Add(product); } var repository = new Func<IProductsRepository>(() => new ProductsInMemoryRepository(() => context) { ExceptionToThrow = new ArgumentException() }); var driver = new SearchIndexGetProductDriver(productId, repository); // Act driver.GetProduct(); // Assert driver.Error.ShouldBeEquivalentTo(expected); } [TestMethod] public void CreateResponseShouldCreateResponse() { // Arrange var product = Get.AnyProductDetails(2, "AnotherBrand", "$19.99", "another/image/url.jpg", "AnotherName", "AnotherStyleId"); var expected = SearchResponseV1.FromProductDetail(product); var context = new ProductInMemoryContext(); var repository = new ProductsInMemoryRepository(() => context); var driver = new SearchIndexGetProductDriver(2, () => repository) { ProductDetail = product }; // Act driver.CreateResponse(); // Assert driver.Response.ShouldBeEquivalentTo(expected); } [TestMethod] public void CreateResponseWithNoProductDetailShouldCreateEmptyResponse() { // Arrange var context = new ProductInMemoryContext(); var repository = new ProductsInMemoryRepository(() => context); var driver = new SearchIndexGetProductDriver(1, () => repository); // Act driver.CreateResponse(); // Assert driver.Response.Should().BeNull(); } [TestMethod] public void CreateResponseWithPreviousErrorShouldNotCreateResponse() { // Arrange var context = new ProductInMemoryContext(); var repository = new ProductsInMemoryRepository(() => context); var driver = new SearchIndexGetProductDriver(1, () => repository) { Error = HttpErrorData.NotFound() }; // Act driver.CreateResponse(); // Assert driver.Response.Should().BeNull(); } } }
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using NuGet.Frameworks; using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Test.Helpers; using NuGet.Versioning; using Sleet; using Xunit; namespace SleetLib.Tests { public class CatalogTests { [Fact] public async Task CatalogTest_CreatePackageDetails() { using (var packagesFolder = new TestFolder()) using (var target = new TestFolder()) using (var cache = new LocalCache()) { // Arrange var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var settings = new LocalSettings(); var context = new SleetContext() { Token = CancellationToken.None, LocalSettings = settings, Log = log, Source = fileSystem, SourceSettings = new FeedSettings() { CatalogEnabled = true } }; var catalog = new Catalog(context); var testPackage = new TestNupkg() { Nuspec = new TestNuspec() { Id = "packageA", Version = "1.0.0-alpha.1", Authors = "authorA, authorB", Copyright = "Copyright info", Description = "Package A", IconUrl = "http://tempuri.org/icon.png", LicenseUrl = "http://tempuri.org/license.html", Language = "en-us", MinClientVersion = "3.3.0", DevelopmentDependency = "true", Owners = "ownerA, ownerB", ProjectUrl = "http://tempuri.org/project.html", ReleaseNotes = "release 1.0", RequireLicenseAcceptance = "true", Summary = "package summary.", Tags = "tagA tagB tagC", Title = "packageA title", Dependencies = new List<PackageDependencyGroup>() { new PackageDependencyGroup(NuGetFramework.AnyFramework, new List<PackageDependency>() { new PackageDependency("packageB", VersionRange.Parse("1.0.0")) }), new PackageDependencyGroup(NuGetFramework.Parse("net46"), new List<PackageDependency>()), new PackageDependencyGroup(NuGetFramework.Parse("net45"), new List<PackageDependency>() { new PackageDependency("packageAll"), new PackageDependency("packageExact", VersionRange.Parse("[2.0.0]")), }), }, FrameworkAssemblies = new List<KeyValuePair<string, List<NuGetFramework>>>() { new KeyValuePair<string, List<NuGetFramework>>("System.IO.Compression", new List<NuGetFramework>() { NuGetFramework.Parse("net45"), NuGetFramework.Parse("win8") }), new KeyValuePair<string, List<NuGetFramework>>("System.Threading", new List<NuGetFramework>() { NuGetFramework.Parse("net40") }), new KeyValuePair<string, List<NuGetFramework>>("System.All", new List<NuGetFramework>() { }) }, } }; var zipFile = testPackage.Save(packagesFolder.Root); using (var zip = new ZipArchive(File.OpenRead(zipFile.FullName), ZipArchiveMode.Read, false)) { var input = PackageInput.Create(zipFile.FullName); var nupkgUri = UriUtility.CreateUri("http://tempuri.org/flatcontainer/packageA/1.0.0-alpha.1/packageA.1.0.0-alpha.1.nupkg"); var iconUri = UriUtility.CreateUri("http://tempuri.org/flatcontainer/packageA/1.0.0/icon"); // Act var actual = await CatalogUtility.CreatePackageDetailsAsync(input, catalog.CatalogBaseURI, nupkgUri, iconUri, context.CommitId, writeFileList: true); var dependencyGroups = actual["dependencyGroups"] as JArray; var frameworkAssemblyGroups = actual["frameworkAssemblyGroup"] as JArray; // Assert Assert.EndsWith(".json", actual["@id"].ToString()); Assert.Contains("/catalog/data/", actual["@id"].ToString()); Assert.Equal(testPackage.Nuspec.Authors, actual["authors"].ToString()); Assert.Equal(testPackage.Nuspec.Copyright, actual["copyright"].ToString()); Assert.Equal(testPackage.Nuspec.Description, actual["description"].ToString()); Assert.Equal(iconUri.AbsoluteUri, actual["iconUrl"].ToString()); Assert.Equal(testPackage.Nuspec.LicenseUrl, actual["licenseUrl"].ToString()); Assert.Equal(testPackage.Nuspec.MinClientVersion, actual["minClientVersion"].ToString()); Assert.Equal(testPackage.Nuspec.ProjectUrl, actual["projectUrl"].ToString()); Assert.True(actual["requireLicenseAcceptance"].ToObject<bool>()); Assert.Equal(testPackage.Nuspec.Title, actual["title"].ToString()); Assert.Equal(testPackage.Nuspec.Id, actual["id"].ToString()); Assert.Equal(testPackage.Nuspec.Version, actual["version"].ToString()); Assert.Equal("tagA", ((JArray)actual["tags"])[0].ToString()); Assert.Equal("tagB", ((JArray)actual["tags"])[1].ToString()); Assert.Equal("tagC", ((JArray)actual["tags"])[2].ToString()); Assert.EndsWith(".nupkg", actual["packageContent"].ToString()); Assert.Null(dependencyGroups[0]["targetFramework"]); Assert.Equal("packageB", ((JArray)dependencyGroups[0]["dependencies"]).Single()["id"]); Assert.Equal("[1.0.0, )", ((JArray)dependencyGroups[0]["dependencies"]).Single()["range"]); Assert.Equal("net45", dependencyGroups[1]["targetFramework"]); Assert.NotNull(dependencyGroups[1]["dependencies"]); Assert.Equal("net46", dependencyGroups[2]["targetFramework"]); Assert.Null(dependencyGroups[2]["dependencies"]); Assert.Null(frameworkAssemblyGroups[0]["targetFramework"]); Assert.Equal("net40", frameworkAssemblyGroups[1]["targetFramework"]); Assert.Equal("net45", frameworkAssemblyGroups[2]["targetFramework"]); Assert.Equal("win8", frameworkAssemblyGroups[3]["targetFramework"]); Assert.Equal("System.All", ((JArray)frameworkAssemblyGroups[0]["assembly"]).Single()); Assert.Equal("System.Threading", ((JArray)frameworkAssemblyGroups[1]["assembly"]).Single()); Assert.Equal("System.IO.Compression", ((JArray)frameworkAssemblyGroups[2]["assembly"]).Single()); Assert.Equal("System.IO.Compression", ((JArray)frameworkAssemblyGroups[3]["assembly"]).Single()); } } } [Fact] public async Task CatalogTest_CreatePackageDetails_Minimal() { using (var packagesFolder = new TestFolder()) using (var target = new TestFolder()) using (var cache = new LocalCache()) { // Arrange var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var settings = new LocalSettings(); var context = new SleetContext() { Token = CancellationToken.None, LocalSettings = settings, Log = log, Source = fileSystem, SourceSettings = new FeedSettings() { CatalogEnabled = true } }; var catalog = new Catalog(context); var testPackage = new TestNupkg("packageA", "1.0.0"); var zipFile = testPackage.Save(packagesFolder.Root); using (var zip = new ZipArchive(File.OpenRead(zipFile.FullName), ZipArchiveMode.Read, false)) { var input = PackageInput.Create(zipFile.FullName); var nupkgUri = UriUtility.CreateUri("http://tempuri.org/flatcontainer/packageA/1.0.0/packageA.1.0.0.nupkg"); Uri iconUri = null; // Act var actual = await CatalogUtility.CreatePackageDetailsAsync(input, catalog.CatalogBaseURI, nupkgUri, iconUri, context.CommitId, writeFileList: true); var dependencyGroups = actual["dependencyGroups"] as JArray; var frameworkAssemblyGroups = actual["frameworkAssemblyGroup"] as JArray; var tags = actual["tags"] as JArray; // Assert Assert.EndsWith(".json", actual["@id"].ToString()); Assert.Equal(string.Empty, actual["authors"].ToString()); Assert.Equal(string.Empty, actual["copyright"].ToString()); Assert.Equal(string.Empty, actual["description"].ToString()); Assert.Equal(string.Empty, actual["iconUrl"].ToString()); Assert.Equal(string.Empty, actual["licenseUrl"].ToString()); Assert.Null(actual["minClientVersion"]); Assert.Equal(string.Empty, actual["projectUrl"].ToString()); Assert.False(actual["requireLicenseAcceptance"].ToObject<bool>()); Assert.Null(actual["title"]); Assert.Equal(testPackage.Nuspec.Id, actual["id"].ToString()); Assert.Equal(testPackage.Nuspec.Version, actual["version"].ToString()); Assert.EndsWith(".nupkg", actual["packageContent"].ToString()); Assert.Empty(dependencyGroups); Assert.Empty(frameworkAssemblyGroups); Assert.Empty(tags); } } } [Fact] public async Task CatalogTest_AddPackageAsync_SupportsWritingMultiplePages() { using (var packagesFolder = new TestFolder()) using (var target = new TestFolder()) using (var cache = new LocalCache()) { // Arrange var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var settings = new LocalSettings(); var context = new SleetContext() { Token = CancellationToken.None, LocalSettings = settings, Log = log, Source = fileSystem, SourceSettings = new FeedSettings() { CatalogEnabled = true, CatalogPageSize = 1, } }; var catalog = new Catalog(context); var catalogIndex = await TemplateUtility.LoadTemplate( "CatalogIndex", DateTimeOffset.UtcNow, fileSystem.BaseURI); await fileSystem.Get("catalog/index.json").Write( JObject.Parse(catalogIndex), log, context.Token); var testPackageA = new TestNupkg("packageA", "1.0.0"); var testPackageB = new TestNupkg("packageB", "1.0.0"); var zipFileA = testPackageA.Save(packagesFolder.Root); var zipFileB = testPackageB.Save(packagesFolder.Root); using (var zipA = new ZipArchive(File.OpenRead(zipFileA.FullName), ZipArchiveMode.Read, false)) using (var zipB = new ZipArchive(File.OpenRead(zipFileB.FullName), ZipArchiveMode.Read, false)) { var inputA = PackageInput.Create(zipFileA.FullName); var inputB = PackageInput.Create(zipFileB.FullName); // Act await catalog.AddPackageAsync(inputA); await catalog.AddPackageAsync(inputB); await fileSystem.Commit(context.Log, context.Token); // Assert Assert.True( await fileSystem.Get("catalog/page.0.json").Exists(context.Log, context.Token), "The first catalog page should exist."); Assert.True( await fileSystem.Get("catalog/page.1.json").Exists(context.Log, context.Token), "The second catalog page should exist."); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection; using System.Diagnostics; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: Type handler for empty or unsupported types. /// </summary> internal sealed class NullTypeInfo : TraceLoggingTypeInfo { public NullTypeInfo() : base(typeof(EmptyStruct)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddGroup(name); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { return; } public override object GetData(object value) { return null; } } /// <summary> /// Type handler for simple scalar types. /// </summary> sealed class ScalarTypeInfo : TraceLoggingTypeInfo { Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc; TraceLoggingDataType nativeFormat; private ScalarTypeInfo( Type type, Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc, TraceLoggingDataType nativeFormat) : base(type) { this.formatFunc = formatFunc; this.nativeFormat = nativeFormat; } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, formatFunc(format, nativeFormat)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar(value); } public static TraceLoggingTypeInfo Boolean() { return new ScalarTypeInfo(typeof(bool), Statics.Format8, TraceLoggingDataType.Boolean8); } public static TraceLoggingTypeInfo Byte() { return new ScalarTypeInfo(typeof(byte), Statics.Format8, TraceLoggingDataType.UInt8); } public static TraceLoggingTypeInfo SByte() { return new ScalarTypeInfo(typeof(sbyte), Statics.Format8, TraceLoggingDataType.Int8); } public static TraceLoggingTypeInfo Char() { return new ScalarTypeInfo(typeof(char), Statics.Format16, TraceLoggingDataType.Char16); } public static TraceLoggingTypeInfo Int16() { return new ScalarTypeInfo(typeof(short), Statics.Format16, TraceLoggingDataType.Int16); } public static TraceLoggingTypeInfo UInt16() { return new ScalarTypeInfo(typeof(ushort), Statics.Format16, TraceLoggingDataType.UInt16); } public static TraceLoggingTypeInfo Int32() { return new ScalarTypeInfo(typeof(int), Statics.Format32, TraceLoggingDataType.Int32); } public static TraceLoggingTypeInfo UInt32() { return new ScalarTypeInfo(typeof(uint), Statics.Format32, TraceLoggingDataType.UInt32); } public static TraceLoggingTypeInfo Int64() { return new ScalarTypeInfo(typeof(long), Statics.Format64, TraceLoggingDataType.Int64); } public static TraceLoggingTypeInfo UInt64() { return new ScalarTypeInfo(typeof(ulong), Statics.Format64, TraceLoggingDataType.UInt64); } public static TraceLoggingTypeInfo IntPtr() { return new ScalarTypeInfo(typeof(IntPtr), Statics.FormatPtr, Statics.IntPtrType); } public static TraceLoggingTypeInfo UIntPtr() { return new ScalarTypeInfo(typeof(UIntPtr), Statics.FormatPtr, Statics.UIntPtrType); } public static TraceLoggingTypeInfo Single() { return new ScalarTypeInfo(typeof(float), Statics.Format32, TraceLoggingDataType.Float); } public static TraceLoggingTypeInfo Double() { return new ScalarTypeInfo(typeof(double), Statics.Format64, TraceLoggingDataType.Double); } public static TraceLoggingTypeInfo Guid() { return new ScalarTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid); } } /// <summary> /// Type handler for arrays of scalars /// </summary> internal sealed class ScalarArrayTypeInfo : TraceLoggingTypeInfo { Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc; TraceLoggingDataType nativeFormat; int elementSize; private ScalarArrayTypeInfo( Type type, Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc, TraceLoggingDataType nativeFormat, int elementSize) : base(type) { this.formatFunc = formatFunc; this.nativeFormat = nativeFormat; this.elementSize = elementSize; } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddArray(name, formatFunc(format, nativeFormat)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddArray(value, elementSize); } public static TraceLoggingTypeInfo Boolean() { return new ScalarArrayTypeInfo(typeof(bool[]), Statics.Format8, TraceLoggingDataType.Boolean8, sizeof(bool)); } public static TraceLoggingTypeInfo Byte() { return new ScalarArrayTypeInfo(typeof(byte[]), Statics.Format8, TraceLoggingDataType.UInt8, sizeof(byte)); } public static TraceLoggingTypeInfo SByte() { return new ScalarArrayTypeInfo(typeof(sbyte[]), Statics.Format8, TraceLoggingDataType.Int8, sizeof(sbyte)); } public static TraceLoggingTypeInfo Char() { return new ScalarArrayTypeInfo(typeof(char[]), Statics.Format16, TraceLoggingDataType.Char16, sizeof(char)); } public static TraceLoggingTypeInfo Int16() { return new ScalarArrayTypeInfo(typeof(short[]), Statics.Format16, TraceLoggingDataType.Int16, sizeof(short)); } public static TraceLoggingTypeInfo UInt16() { return new ScalarArrayTypeInfo(typeof(ushort[]), Statics.Format16, TraceLoggingDataType.UInt16, sizeof(ushort)); } public static TraceLoggingTypeInfo Int32() { return new ScalarArrayTypeInfo(typeof(int[]), Statics.Format32, TraceLoggingDataType.Int32, sizeof(int)); } public static TraceLoggingTypeInfo UInt32() { return new ScalarArrayTypeInfo(typeof(uint[]), Statics.Format32, TraceLoggingDataType.UInt32, sizeof(uint)); } public static TraceLoggingTypeInfo Int64() { return new ScalarArrayTypeInfo(typeof(long[]), Statics.Format64, TraceLoggingDataType.Int64, sizeof(long)); } public static TraceLoggingTypeInfo UInt64() { return new ScalarArrayTypeInfo(typeof(ulong[]), Statics.Format64, TraceLoggingDataType.UInt64, sizeof(ulong)); } public static TraceLoggingTypeInfo IntPtr() { return new ScalarArrayTypeInfo(typeof(IntPtr[]), Statics.FormatPtr, Statics.IntPtrType, System.IntPtr.Size); } public static TraceLoggingTypeInfo UIntPtr() { return new ScalarArrayTypeInfo(typeof(UIntPtr[]), Statics.FormatPtr, Statics.UIntPtrType, System.IntPtr.Size); } public static TraceLoggingTypeInfo Single() { return new ScalarArrayTypeInfo(typeof(float[]), Statics.Format32, TraceLoggingDataType.Float, sizeof(float)); } public static TraceLoggingTypeInfo Double() { return new ScalarArrayTypeInfo(typeof(double[]), Statics.Format64, TraceLoggingDataType.Double, sizeof(double)); } public static unsafe TraceLoggingTypeInfo Guid() { return new ScalarArrayTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid, sizeof(Guid)); } } /// <summary> /// TraceLogging: Type handler for String. /// </summary> internal sealed class StringTypeInfo : TraceLoggingTypeInfo { public StringTypeInfo() : base(typeof(string)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddNullTerminatedString(name, Statics.MakeDataType(TraceLoggingDataType.Utf16String, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddNullTerminatedString((string)value.ReferenceValue); } public override object GetData(object value) { if(value == null) { return ""; } return value; } } /// <summary> /// TraceLogging: Type handler for DateTime. /// </summary> internal sealed class DateTimeTypeInfo : TraceLoggingTypeInfo { public DateTimeTypeInfo() : base(typeof(DateTime)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.FileTime, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { DateTime dateTime = value.ScalarValue.AsDateTime; const long UTCMinTicks = 504911232000000000; long dateTimeTicks = 0; // We cannot translate dates sooner than 1/1/1601 in UTC. // To avoid getting an ArgumentOutOfRangeException we compare with 1/1/1601 DateTime ticks if (dateTime.Ticks > UTCMinTicks) dateTimeTicks = dateTime.ToFileTimeUtc(); collector.AddScalar(dateTimeTicks); } } /// <summary> /// TraceLogging: Type handler for DateTimeOffset. /// </summary> internal sealed class DateTimeOffsetTypeInfo : TraceLoggingTypeInfo { public DateTimeOffsetTypeInfo() : base(typeof(DateTimeOffset)) { } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { var group = collector.AddGroup(name); group.AddScalar("Ticks", Statics.MakeDataType(TraceLoggingDataType.FileTime, format)); group.AddScalar("Offset", TraceLoggingDataType.Int64); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { var dateTimeOffset = value.ScalarValue.AsDateTimeOffset; var ticks = dateTimeOffset.Ticks; collector.AddScalar(ticks < 504911232000000000 ? 0 : ticks - 504911232000000000); collector.AddScalar(dateTimeOffset.Offset.Ticks); } } /// <summary> /// TraceLogging: Type handler for TimeSpan. /// </summary> internal sealed class TimeSpanTypeInfo : TraceLoggingTypeInfo { public TimeSpanTypeInfo() : base(typeof(TimeSpan)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Int64, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar(value.ScalarValue.AsTimeSpan.Ticks); } } /// <summary> /// TraceLogging: Type handler for decimal. (Note: not full-fidelity, exposed as Double.) /// </summary> internal sealed class DecimalTypeInfo : TraceLoggingTypeInfo { public DecimalTypeInfo() : base(typeof(decimal)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Double, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar((double)value.ScalarValue.AsDecimal); } } /// <summary> /// TraceLogging: Type handler for Nullable. /// </summary> internal sealed class NullableTypeInfo : TraceLoggingTypeInfo { private readonly TraceLoggingTypeInfo valueInfo; private readonly Func<PropertyValue, PropertyValue> valueGetter; public NullableTypeInfo(Type type, List<Type> recursionCheck) : base(type) { var typeArgs = type.GenericTypeArguments; Debug.Assert(typeArgs.Length == 1); this.valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck); this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value")); } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { var group = collector.AddGroup(name); group.AddScalar("HasValue", TraceLoggingDataType.Boolean8); this.valueInfo.WriteMetadata(group, "Value", format); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { // It's not currently possible to get the HasValue property of a nullable type through reflection when the // value is null. Instead, we simply check that the nullable is not null. var hasValue = value.ReferenceValue != null; collector.AddScalar(hasValue); var val = hasValue ? valueGetter(value) : valueInfo.PropertyValueFactory(Activator.CreateInstance(valueInfo.DataType)); this.valueInfo.WriteData(collector, val); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type decimal with 2 columns and 2 rows. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct decmat2 : IEnumerable<decimal>, IEquatable<decmat2> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> public decimal m00; /// <summary> /// Column 0, Rows 1 /// </summary> public decimal m01; /// <summary> /// Column 1, Rows 0 /// </summary> public decimal m10; /// <summary> /// Column 1, Rows 1 /// </summary> public decimal m11; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public decmat2(decimal m00, decimal m01, decimal m10, decimal m11) { this.m00 = m00; this.m01 = m01; this.m10 = m10; this.m11 = m11; } /// <summary> /// Constructs this matrix from a decmat2. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat2(decmat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a decmat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat2(decmat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a decmat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat2(decmat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a decmat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat2(decmat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a decmat3. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat2(decmat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a decmat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat2(decmat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a decmat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat2(decmat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a decmat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat2(decmat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a decmat4. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat2(decmat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat2(decvec2 c0, decvec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public decimal[,] Values => new[,] { { m00, m01 }, { m10, m11 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public decimal[] Values1D => new[] { m00, m01, m10, m11 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public decvec2 Column0 { get { return new decvec2(m00, m01); } set { m00 = value.x; m01 = value.y; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public decvec2 Column1 { get { return new decvec2(m10, m11); } set { m10 = value.x; m11 = value.y; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public decvec2 Row0 { get { return new decvec2(m00, m10); } set { m00 = value.x; m10 = value.y; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public decvec2 Row1 { get { return new decvec2(m01, m11); } set { m01 = value.x; m11 = value.y; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static decmat2 Zero { get; } = new decmat2(0m, 0m, 0m, 0m); /// <summary> /// Predefined all-ones matrix /// </summary> public static decmat2 Ones { get; } = new decmat2(1m, 1m, 1m, 1m); /// <summary> /// Predefined identity matrix /// </summary> public static decmat2 Identity { get; } = new decmat2(1m, 0m, 0m, 1m); /// <summary> /// Predefined all-MaxValue matrix /// </summary> public static decmat2 AllMaxValue { get; } = new decmat2(decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue); /// <summary> /// Predefined diagonal-MaxValue matrix /// </summary> public static decmat2 DiagonalMaxValue { get; } = new decmat2(decimal.MaxValue, 0m, 0m, decimal.MaxValue); /// <summary> /// Predefined all-MinValue matrix /// </summary> public static decmat2 AllMinValue { get; } = new decmat2(decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue); /// <summary> /// Predefined diagonal-MinValue matrix /// </summary> public static decmat2 DiagonalMinValue { get; } = new decmat2(decimal.MinValue, 0m, 0m, decimal.MinValue); /// <summary> /// Predefined all-MinusOne matrix /// </summary> public static decmat2 AllMinusOne { get; } = new decmat2(decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne); /// <summary> /// Predefined diagonal-MinusOne matrix /// </summary> public static decmat2 DiagonalMinusOne { get; } = new decmat2(decimal.MinusOne, 0m, 0m, decimal.MinusOne); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<decimal> GetEnumerator() { yield return m00; yield return m01; yield return m10; yield return m11; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (2 x 2 = 4). /// </summary> public int Count => 4; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public decimal this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m10; case 3: return m11; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m10 = value; break; case 3: this.m11 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public decimal this[int col, int row] { get { return this[col * 2 + row]; } set { this[col * 2 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(decmat2 rhs) => ((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is decmat2 && Equals((decmat2) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(decmat2 lhs, decmat2 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(decmat2 lhs, decmat2 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public decmat2 Transposed => new decmat2(m00, m10, m01, m11); /// <summary> /// Returns the minimal component of this matrix. /// </summary> public decimal MinElement => Math.Min(Math.Min(Math.Min(m00, m01), m10), m11); /// <summary> /// Returns the maximal component of this matrix. /// </summary> public decimal MaxElement => Math.Max(Math.Max(Math.Max(m00, m01), m10), m11); /// <summary> /// Returns the euclidean length of this matrix. /// </summary> public decimal Length => (decimal)(((m00*m00 + m01*m01) + (m10*m10 + m11*m11))).Sqrt(); /// <summary> /// Returns the squared euclidean length of this matrix. /// </summary> public decimal LengthSqr => ((m00*m00 + m01*m01) + (m10*m10 + m11*m11)); /// <summary> /// Returns the sum of all fields. /// </summary> public decimal Sum => ((m00 + m01) + (m10 + m11)); /// <summary> /// Returns the euclidean norm of this matrix. /// </summary> public decimal Norm => (decimal)(((m00*m00 + m01*m01) + (m10*m10 + m11*m11))).Sqrt(); /// <summary> /// Returns the one-norm of this matrix. /// </summary> public decimal Norm1 => ((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m10) + Math.Abs(m11))); /// <summary> /// Returns the two-norm of this matrix. /// </summary> public decimal Norm2 => (decimal)(((m00*m00 + m01*m01) + (m10*m10 + m11*m11))).Sqrt(); /// <summary> /// Returns the max-norm of this matrix. /// </summary> public decimal NormMax => Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m10)), Math.Abs(m11)); /// <summary> /// Returns the p-norm of this matrix. /// </summary> public double NormP(double p) => Math.Pow(((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p))), 1 / p); /// <summary> /// Returns determinant of this matrix. /// </summary> public decimal Determinant => m00 * m11 - m10 * m01; /// <summary> /// Returns the adjunct of this matrix. /// </summary> public decmat2 Adjugate => new decmat2(m11, -m01, -m10, m00); /// <summary> /// Returns the inverse of this matrix (use with caution). /// </summary> public decmat2 Inverse => Adjugate / Determinant; /// <summary> /// Executes a matrix-matrix-multiplication decmat2 * decmat2 -> decmat2. /// </summary> public static decmat2 operator*(decmat2 lhs, decmat2 rhs) => new decmat2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11)); /// <summary> /// Executes a matrix-matrix-multiplication decmat2 * decmat3x2 -> decmat3x2. /// </summary> public static decmat3x2 operator*(decmat2 lhs, decmat3x2 rhs) => new decmat3x2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21)); /// <summary> /// Executes a matrix-matrix-multiplication decmat2 * decmat4x2 -> decmat4x2. /// </summary> public static decmat4x2 operator*(decmat2 lhs, decmat4x2 rhs) => new decmat4x2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31)); /// <summary> /// Executes a matrix-vector-multiplication. /// </summary> public static decvec2 operator*(decmat2 m, decvec2 v) => new decvec2((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y)); /// <summary> /// Executes a matrix-matrix-divison A / B == A * B^-1 (use with caution). /// </summary> public static decmat2 operator/(decmat2 A, decmat2 B) => A * B.Inverse; /// <summary> /// Executes a component-wise * (multiply). /// </summary> public static decmat2 CompMul(decmat2 A, decmat2 B) => new decmat2(A.m00 * B.m00, A.m01 * B.m01, A.m10 * B.m10, A.m11 * B.m11); /// <summary> /// Executes a component-wise / (divide). /// </summary> public static decmat2 CompDiv(decmat2 A, decmat2 B) => new decmat2(A.m00 / B.m00, A.m01 / B.m01, A.m10 / B.m10, A.m11 / B.m11); /// <summary> /// Executes a component-wise + (add). /// </summary> public static decmat2 CompAdd(decmat2 A, decmat2 B) => new decmat2(A.m00 + B.m00, A.m01 + B.m01, A.m10 + B.m10, A.m11 + B.m11); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static decmat2 CompSub(decmat2 A, decmat2 B) => new decmat2(A.m00 - B.m00, A.m01 - B.m01, A.m10 - B.m10, A.m11 - B.m11); /// <summary> /// Executes a component-wise + (add). /// </summary> public static decmat2 operator+(decmat2 lhs, decmat2 rhs) => new decmat2(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static decmat2 operator+(decmat2 lhs, decimal rhs) => new decmat2(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m10 + rhs, lhs.m11 + rhs); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static decmat2 operator+(decimal lhs, decmat2 rhs) => new decmat2(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m10, lhs + rhs.m11); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static decmat2 operator-(decmat2 lhs, decmat2 rhs) => new decmat2(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static decmat2 operator-(decmat2 lhs, decimal rhs) => new decmat2(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m10 - rhs, lhs.m11 - rhs); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static decmat2 operator-(decimal lhs, decmat2 rhs) => new decmat2(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m10, lhs - rhs.m11); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static decmat2 operator/(decmat2 lhs, decimal rhs) => new decmat2(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m10 / rhs, lhs.m11 / rhs); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static decmat2 operator/(decimal lhs, decmat2 rhs) => new decmat2(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m10, lhs / rhs.m11); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static decmat2 operator*(decmat2 lhs, decimal rhs) => new decmat2(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m10 * rhs, lhs.m11 * rhs); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static decmat2 operator*(decimal lhs, decmat2 rhs) => new decmat2(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m10, lhs * rhs.m11); /// <summary> /// Executes a component-wise lesser-than comparison. /// </summary> public static bmat2 operator<(decmat2 lhs, decmat2 rhs) => new bmat2(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat2 operator<(decmat2 lhs, decimal rhs) => new bmat2(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m10 < rhs, lhs.m11 < rhs); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat2 operator<(decimal lhs, decmat2 rhs) => new bmat2(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m10, lhs < rhs.m11); /// <summary> /// Executes a component-wise lesser-or-equal comparison. /// </summary> public static bmat2 operator<=(decmat2 lhs, decmat2 rhs) => new bmat2(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat2 operator<=(decmat2 lhs, decimal rhs) => new bmat2(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat2 operator<=(decimal lhs, decmat2 rhs) => new bmat2(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m10, lhs <= rhs.m11); /// <summary> /// Executes a component-wise greater-than comparison. /// </summary> public static bmat2 operator>(decmat2 lhs, decmat2 rhs) => new bmat2(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat2 operator>(decmat2 lhs, decimal rhs) => new bmat2(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m10 > rhs, lhs.m11 > rhs); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat2 operator>(decimal lhs, decmat2 rhs) => new bmat2(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m10, lhs > rhs.m11); /// <summary> /// Executes a component-wise greater-or-equal comparison. /// </summary> public static bmat2 operator>=(decmat2 lhs, decmat2 rhs) => new bmat2(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat2 operator>=(decmat2 lhs, decimal rhs) => new bmat2(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat2 operator>=(decimal lhs, decmat2 rhs) => new bmat2(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m10, lhs >= rhs.m11); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Security.Cryptography { using System.Security.AccessControl; using System.Security.Permissions; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum KeyNumber { Exchange = 1, Signature = 2 } [System.Runtime.InteropServices.ComVisible(true)] public sealed class CspKeyContainerInfo { private CspParameters m_parameters; private bool m_randomKeyContainer; private CspKeyContainerInfo () {} [System.Security.SecurityCritical] // auto-generated internal CspKeyContainerInfo (CspParameters parameters, bool randomKeyContainer) { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open); kp.AccessEntries.Add(entry); kp.Demand(); } m_parameters = new CspParameters(parameters); if (m_parameters.KeyNumber == -1) { if (m_parameters.ProviderType == Constants.PROV_RSA_FULL || m_parameters.ProviderType == Constants.PROV_RSA_AES) m_parameters.KeyNumber = Constants.AT_KEYEXCHANGE; else if (m_parameters.ProviderType == Constants.PROV_DSS_DH) m_parameters.KeyNumber = Constants.AT_SIGNATURE; } m_randomKeyContainer = randomKeyContainer; } [System.Security.SecuritySafeCritical] // auto-generated public CspKeyContainerInfo (CspParameters parameters) : this (parameters, false) {} public bool MachineKeyStore { get { return (m_parameters.Flags & CspProviderFlags.UseMachineKeyStore) == CspProviderFlags.UseMachineKeyStore ? true : false; } } public string ProviderName { get { return m_parameters.ProviderName; } } public int ProviderType { get { return m_parameters.ProviderType; } } public string KeyContainerName { get { return m_parameters.KeyContainerName; } } public string UniqueKeyContainerName { [System.Security.SecuritySafeCritical] // auto-generated get { SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle; int hr = Utils._OpenCSP(m_parameters, Constants.CRYPT_SILENT, ref safeProvHandle); if (hr != Constants.S_OK) throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_NotFound")); string uniqueContainerName = (string) Utils._GetProviderParameter(safeProvHandle, m_parameters.KeyNumber, Constants.CLR_UNIQUE_CONTAINER); safeProvHandle.Dispose(); return uniqueContainerName; } } public KeyNumber KeyNumber { get { return (KeyNumber) m_parameters.KeyNumber; } } public bool Exportable { [System.Security.SecuritySafeCritical] // auto-generated get { // Assume hardware keys are not exportable. if (this.HardwareDevice) return false; SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle; int hr = Utils._OpenCSP(m_parameters, Constants.CRYPT_SILENT, ref safeProvHandle); if (hr != Constants.S_OK) throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_NotFound")); byte[] isExportable = (byte[]) Utils._GetProviderParameter(safeProvHandle, m_parameters.KeyNumber, Constants.CLR_EXPORTABLE); safeProvHandle.Dispose(); return (isExportable[0] == 1); } } public bool HardwareDevice { [System.Security.SecuritySafeCritical] // auto-generated get { SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle; CspParameters parameters = new CspParameters(m_parameters); parameters.KeyContainerName = null; parameters.Flags = (parameters.Flags & CspProviderFlags.UseMachineKeyStore) != 0 ? CspProviderFlags.UseMachineKeyStore : 0; uint flags = Constants.CRYPT_VERIFYCONTEXT; int hr = Utils._OpenCSP(parameters, flags, ref safeProvHandle); if (hr != Constants.S_OK) throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_NotFound")); byte[] isHardwareDevice = (byte[]) Utils._GetProviderParameter(safeProvHandle, parameters.KeyNumber, Constants.CLR_HARDWARE); safeProvHandle.Dispose(); return (isHardwareDevice[0] == 1); } } public bool Removable { [System.Security.SecuritySafeCritical] // auto-generated get { SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle; CspParameters parameters = new CspParameters(m_parameters); parameters.KeyContainerName = null; parameters.Flags = (parameters.Flags & CspProviderFlags.UseMachineKeyStore) != 0 ? CspProviderFlags.UseMachineKeyStore : 0; uint flags = Constants.CRYPT_VERIFYCONTEXT; int hr = Utils._OpenCSP(parameters, flags, ref safeProvHandle); if (hr != Constants.S_OK) throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_NotFound")); byte[] isRemovable = (byte[]) Utils._GetProviderParameter(safeProvHandle, parameters.KeyNumber, Constants.CLR_REMOVABLE); safeProvHandle.Dispose(); return (isRemovable[0] == 1); } } public bool Accessible { [System.Security.SecuritySafeCritical] // auto-generated get { // This method will pop-up a UI for hardware keys. SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle; int hr = Utils._OpenCSP(m_parameters, Constants.CRYPT_SILENT, ref safeProvHandle); if (hr != Constants.S_OK) return false; byte[] isAccessible = (byte[]) Utils._GetProviderParameter(safeProvHandle, m_parameters.KeyNumber, Constants.CLR_ACCESSIBLE); safeProvHandle.Dispose(); return (isAccessible[0] == 1); } } public bool Protected { [System.Security.SecuritySafeCritical] // auto-generated get { // Assume hardware keys are protected. if (this.HardwareDevice == true) return true; SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle; int hr = Utils._OpenCSP(m_parameters, Constants.CRYPT_SILENT, ref safeProvHandle); if (hr != Constants.S_OK) throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_NotFound")); byte[] isProtected = (byte[]) Utils._GetProviderParameter(safeProvHandle, m_parameters.KeyNumber, Constants.CLR_PROTECTED); safeProvHandle.Dispose(); return (isProtected[0] == 1); } } #if FEATURE_MACL public CryptoKeySecurity CryptoKeySecurity { [System.Security.SecuritySafeCritical] // auto-generated get { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(m_parameters, KeyContainerPermissionFlags.ChangeAcl | KeyContainerPermissionFlags.ViewAcl); kp.AccessEntries.Add(entry); kp.Demand(); SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle; int hr = Utils._OpenCSP(m_parameters, Constants.CRYPT_SILENT, ref safeProvHandle); if (hr != Constants.S_OK) throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_NotFound")); using (safeProvHandle) { return Utils.GetKeySetSecurityInfo(safeProvHandle, AccessControlSections.All); } } } #endif //FEATURE_MACL public bool RandomlyGenerated { get { return m_randomKeyContainer; } } } [System.Runtime.InteropServices.ComVisible(true)] public interface ICspAsymmetricAlgorithm { CspKeyContainerInfo CspKeyContainerInfo { get; } #if FEATURE_LEGACYNETCFCRYPTO [SecurityCritical] #endif byte[] ExportCspBlob (bool includePrivateParameters); #if FEATURE_LEGACYNETCFCRYPTO [SecurityCritical] #endif void ImportCspBlob (byte[] rawData); } }
using System; using System.Runtime.InteropServices; using WinForms = System.Windows.Forms; // 29/6/03 namespace NBM { /// <summary> /// Flags for the PlaySound() method /// </summary> public enum PlaySoundFlags { /// <summary> /// The sound is played using an application-specific association. /// </summary> Application = 0x80, /// <summary> /// The pszSound parameter is a system-event alias in the registry or the WIN.INI file. /// Do not use with either SND_FILENAME or SND_RESOURCE. /// </summary> Alias = 0x10000, /// <summary> /// The pszSound parameter is a predefined sound identifier. /// </summary> AliasId = 0x110000, /// <summary> /// The sound is played asynchronously and PlaySound returns immediately /// after beginning the sound. To terminate an asynchronously played waveform sound, /// call PlaySound with pszSound set to NULL. /// </summary> Asynchronous = 0x01, /// <summary> /// The sound plays repeatedly until PlaySound is called again with the pszSound parameter /// set to NULL. You must also specify the SND_ASYNC flag to indicate an asynchronous /// sound event. /// </summary> Loop = 0x08, /// <summary> /// No default sound event is used. If the sound cannot be found, /// PlaySound returns silently without playing the default sound. /// </summary> NoDefault = 0x02, /// <summary> /// The specified sound event will yield to another sound event that is already playing. /// If a sound cannot be played because the resource needed to generate that sound /// is busy playing another sound, the function immediately returns FALSE without /// playing the requested sound. /// If this flag is not specified, /// PlaySound attempts to stop the currently playing sound so that the device /// can be used to play the new sound. /// </summary> NoStop = 0x10, /// <summary> /// If the driver is busy, return immediately without playing the sound. /// </summary> NoWait = 0x2000, /// <summary> /// Sounds are to be stopped for the calling task. /// If pszSound is not NULL, all instances of the specified sound are stopped. /// If pszSound is NULL, all sounds that are playing on behalf of the calling task are stopped. /// You must also specify the instance handle to stop SND_RESOURCE events. /// </summary> Purge = 0x40, /// <summary> /// Synchronous playback of a sound event. PlaySound returns after the sound event completes. /// </summary> Synchronous = 0x00 } /// <summary> /// Flags for the FlashWindow() method /// </summary> public enum FlashWindowFlags { /// <summary> /// Flash the taskbar button /// </summary> FlashTray = 0x00000002, /// <summary> /// Flash the window caption /// </summary> FlashCaption = 0x00000001, /// <summary> /// Flash both the window caption and taskbar button /// </summary> FlashBoth = FlashTray | FlashCaption, } /// <summary> /// Holds all Windows native methods. /// </summary> public class NativeMethods { #region SendMessage methods [DllImport("user32.dll")] private static extern Int32 SendMessage(IntPtr hwnd, Int32 msg, Int32 wparam, Int32 lparam); /// <summary> /// /// </summary> /// <param name="control"></param> /// <param name="msg"></param> /// <param name="wparam"></param> /// <param name="lparam"></param> /// <returns></returns> public static Int32 SendMessage(WinForms.Control control, Int32 msg, Int32 wparam, Int32 lparam) { return SendMessage(control.Handle, msg, wparam, lparam); } /// <summary> /// /// </summary> /// <param name="control"></param> /// <param name="msg"></param> /// <param name="wparam"></param> /// <returns></returns> public static Int32 SendMessage(WinForms.Control control, Int32 msg, Int32 wparam) { return SendMessage(control, msg, wparam, 0); } /// <summary> /// /// </summary> /// <param name="control"></param> /// <param name="msg"></param> /// <returns></returns> public static Int32 SendMessage(WinForms.Control control, Int32 msg) { return SendMessage(control, msg, 0); } #endregion #region PlaySound methods [DllImport("winmm.dll")] private static extern bool PlaySound(string fileName, IntPtr hmodule, Int32 flags); /// <summary> /// /// </summary> /// <param name="fileName"></param> /// <param name="flags"></param> /// <returns></returns> public static bool PlaySoundFromFile(string fileName, PlaySoundFlags flags) { return PlaySound(fileName, (IntPtr)0, 0x20000 | (int)flags); } /// <summary> /// /// </summary> /// <param name="resourceName"></param> /// <param name="module"></param> /// <param name="flags"></param> /// <returns></returns> public static bool PlaySoundFromResource(string resourceName, IntPtr module, PlaySoundFlags flags) { return PlaySound(resourceName, module, 0x40004 | (int)flags); } /// <summary> /// /// </summary> /// <param name="memoryPtr"></param> /// <param name="flags"></param> /// <returns></returns> public static bool PlaySoundFromMemory(IntPtr memoryPtr, PlaySoundFlags flags) { return PlaySound(string.Empty, memoryPtr, 0x04 | (int)flags); } #endregion #region Flash window methods [DllImport("user32.dll")] private static extern bool FlashWindowEx(ref FlashWindowInfo info); [StructLayout(LayoutKind.Sequential)] private struct FlashWindowInfo { public UInt32 cbSize; public IntPtr hwnd; public UInt32 dwFlags; public UInt32 uCount; public UInt32 dwTimeout; } /// <summary> /// /// </summary> /// <param name="form"></param> /// <param name="count"></param> /// <param name="flags"></param> /// <returns></returns> public static bool FlashWindow(WinForms.Form form, uint count, FlashWindowFlags flags) { return FlashWindow(form, count, flags, 0); } /// <summary> /// /// </summary> /// <param name="form"></param> /// <param name="count"></param> /// <param name="flags"></param> /// <param name="timeout"></param> /// <returns></returns> public static bool FlashWindow(WinForms.Form form, uint count, FlashWindowFlags flags, uint timeout) { FlashWindowInfo info = new FlashWindowInfo(); info.cbSize = 20; info.dwFlags = 0x0000000C | (uint)flags; // FLASHW_TIMERNOFG info.dwTimeout = timeout; info.hwnd = form.Handle; info.uCount = count; return FlashWindowEx(ref info); } /// <summary> /// /// </summary> /// <param name="form"></param> /// <param name="count"></param> /// <param name="flags"></param> /// <returns></returns> public static bool FlashWindowUntilStop(WinForms.Form form, uint count, FlashWindowFlags flags) { return FlashWindowUntilStop(form, count, flags, 0); } /// <summary> /// /// </summary> /// <param name="form"></param> /// <param name="count"></param> /// <param name="flags"></param> /// <param name="timeout"></param> /// <returns></returns> public static bool FlashWindowUntilStop(WinForms.Form form, uint count, FlashWindowFlags flags, uint timeout) { if (flags == 0) throw new ArgumentException("Flags cannot be zero", "flags"); FlashWindowInfo info = new FlashWindowInfo(); info.cbSize = 20; info.dwFlags = 0x00000004 | (uint)flags; // FLASHW_TIMER info.dwTimeout = timeout; info.hwnd = form.Handle; info.uCount = count; return FlashWindowEx(ref info); } /// <summary> /// /// </summary> /// <param name="form"></param> /// <returns></returns> public static bool FlashWindowStop(WinForms.Form form) { FlashWindowInfo info = new FlashWindowInfo(); info.cbSize = 20; info.dwFlags = 0; // FLASHW_STOP info.dwTimeout = 0; info.hwnd = form.Handle; info.uCount = 0; return FlashWindowEx(ref info); } #endregion /// <summary> /// /// </summary> /// <param name="control"></param> public static void VerticalScrollToBottom(WinForms.Control control) { if (control.Created) { SendMessage(control.Handle, 0x0115 /* WM_VSCROLL */, 7 /* VB_BOTTOM */, 0); } } private NativeMethods() {} } }
using System; using System.Collections; using System.Drawing; using System.Drawing.Text; using System.Drawing.Drawing2D; using System.ComponentModel; using System.Windows.Forms; using Oranikle.Studio.Controls.NWin32; namespace Oranikle.Studio.Controls.General { #region 3D Styles Enums public enum Canvas3DStyle { Single, Raised, Upped, Title, Flat } public enum HightlightStyle { Active, Selected } #endregion public sealed class GDIUtils { #region Class Members static StringFormat format = new StringFormat(); // store brushes to optimize memory managment private SolidBrush m_brushDark = null; private SolidBrush m_brushDarkDark = null; private SolidBrush m_brushLight = null; private SolidBrush m_brushLightLight = null; // colors on which brushes are based private Color m_clrDark; private Color m_clrDarkDark; private Color m_clrLight; private Color m_clrLightLight; // pens used by class for drawing Pen m_penDark = null; Pen m_penDarkDark = null; Pen m_penLight = null; Pen m_penLightLight = null; #endregion #region Class Properties public Color Dark { get{ return m_clrDark; } set { if( value == m_clrDark ) return; m_clrDark = value; // destoroy old values if( m_brushDark != null ) m_brushDark.Dispose(); if( m_penDark != null ) m_penDark.Dispose(); m_brushDark = new SolidBrush( m_clrDark ); m_penDark = new Pen( m_brushDark ); } } public Color DarkDark { get{ return m_clrDarkDark; } set { if( value == m_clrDarkDark ) return; m_clrDarkDark = value; // destoroy old values if( m_brushDarkDark != null ) m_brushDarkDark.Dispose(); if( m_penDarkDark != null ) m_penDarkDark.Dispose(); m_brushDarkDark = new SolidBrush( m_clrDarkDark ); m_penDarkDark = new Pen( m_brushDarkDark ); } } public Color Light { get{ return m_clrLight; } set { if( value == m_clrLight ) return; m_clrLight = value; // destoroy old values if( m_brushLight != null ) m_brushLight.Dispose(); if( m_penLight != null ) m_penLight.Dispose(); m_brushLight = new SolidBrush( m_clrLight ); m_penLight = new Pen( m_brushLight ); } } public Color LightLight { get{ return m_clrLightLight; } set { if( value == m_clrLightLight ) return; m_clrLightLight = value; // destoroy old values if( m_brushLightLight != null ) m_brushLightLight.Dispose(); if( m_penLightLight != null ) m_penLightLight.Dispose(); m_brushLightLight = new SolidBrush( m_clrLightLight ); m_penLightLight = new Pen( m_brushLightLight ); } } public Brush DarkBrush{ get{ return m_brushDark; } } public Brush DarkDarkBrush{ get{ return m_brushDarkDark; } } public Brush LightBrush{ get{ return m_brushLight; } } public Brush LightLightBrush{ get{ return m_brushLightLight; } } public Pen DarkPen{ get{ return m_penDark; } } public Pen DarkDarkPen{ get{ return m_penDarkDark; } } public Pen LightPen{ get{ return m_penLight; } } public Pen LightLightPen{ get{ return m_penLightLight; } } static public StringFormat OneLineFormat { get { format.Alignment = StringAlignment.Center; format.LineAlignment = StringAlignment.Center; format.Trimming = StringTrimming.EllipsisCharacter; format.FormatFlags = StringFormatFlags.LineLimit; format.HotkeyPrefix = HotkeyPrefix.Show; return format; } } static public StringFormat OneLineNoTrimming { get { format.Alignment = StringAlignment.Center; format.LineAlignment = StringAlignment.Center; format.Trimming = StringTrimming.None; format.FormatFlags = StringFormatFlags.LineLimit; format.HotkeyPrefix = HotkeyPrefix.Show; return format; } } #endregion #region Initialize/Finilize functions /// <summary> /// Default Constructor /// </summary> public GDIUtils() { this.Dark = SystemColors.ControlDark; this.DarkDark = SystemColors.ControlDarkDark; this.Light = SystemColors.ControlLight; this.LightLight = SystemColors.ControlLightLight; } /// <summary> /// Constructor used to override default colors used by class /// </summary> public GDIUtils( Color Dark, Color DarkDark, Color Light, Color LightLight ) { this.Dark = Dark; this.DarkDark = DarkDark; this.Light = Light; this.LightLight = LightLight; } /// <summary> /// Destroy all pens and brushes used by class /// </summary> public void Dispose() { if( m_brushDark != null ) m_brushDark.Dispose(); if( m_penDark != null ) m_penDark.Dispose(); if( m_brushDarkDark != null ) m_brushDarkDark.Dispose(); if( m_penDarkDark != null ) m_penDarkDark.Dispose(); if( m_brushLight != null ) m_brushLight.Dispose(); if( m_penLight != null ) m_penLight.Dispose(); if( m_brushLightLight != null ) m_brushLightLight.Dispose(); if( m_penLightLight != null ) m_penLightLight.Dispose(); } #endregion #region Custom Drawing functions /// <summary> /// Draw 3d Line. 3D Line is a simple line wich contains one dark and one light line. /// By dark and light line we create optical 3D effect. /// </summary> /// <param name="graph">Graphics object which used by function to draw</param> /// <param name="pnt1">Start point</param> /// <param name="pnt2">End point</param> public void Draw3DLine( Graphics graph, Point pnt1, Point pnt2 ) { Pen penDark = new Pen( m_brushDark ); Pen penLight = new Pen( m_brushLightLight ); Point[] arrPoint = { pnt1, pnt2 }; // create copy of Point input params graph.DrawLine( penLight, pnt1, pnt2 ); // draw first line if( pnt1.X == pnt2.X ) { arrPoint[0].X--; arrPoint[1].X--; } else if( pnt1.Y == pnt2.Y ) { arrPoint[0].Y--; arrPoint[1].Y--; } else { arrPoint[0].X--; arrPoint[0].Y--; arrPoint[1].X--; arrPoint[1].Y--; } graph.DrawLine( penDark, arrPoint[0], arrPoint[1] ); penDark.Dispose(); penLight.Dispose(); } /// <summary> /// Draw 3D box according to style specification. There are four styles which our /// function know how to draw. /// </summary> /// <param name="graph">Graphics object used for drawing</param> /// <param name="rect">Box rectangle</param> /// <param name="style">Style of Box</param> public void Draw3DBox( Graphics graph, Rectangle rect, Canvas3DStyle style ) { Point pnt1 = Point.Empty, pnt2 = Point.Empty, pnt4 = Point.Empty; Point[] arrPoints = { pnt1, pnt2, pnt1, pnt4 }; switch( style ) { case Canvas3DStyle.Flat: graph.DrawRectangle( m_penDark, rect ); break; case Canvas3DStyle.Title: #region Canvas 3DStyle - Title graph.DrawRectangle( m_penDark, rect ); pnt1.X = rect.X+1; pnt1.Y = rect.Y+1; pnt2.X = rect.X+1; pnt2.Y = rect.Height-1; pnt4.X = rect.Width-1; pnt4.Y = rect.Y+1; // set new values to array of pointers arrPoints[0] = arrPoints[2] = pnt1; arrPoints[1] = pnt2; arrPoints[3] = pnt4; graph.DrawLines( m_penLightLight, arrPoints ); #endregion break; case Canvas3DStyle.Raised: #region Canvas 3DStyle Raised // draw left upper corner pnt1.X = rect.X; pnt1.Y = rect.Y; pnt2.X = rect.X + rect.Width; pnt2.Y = rect.Y; pnt4.X = rect.X; pnt4.Y = rect.Y + rect.Height; // set new values to array of pointers arrPoints[0] = arrPoints[2] = pnt1; arrPoints[1] = pnt2; arrPoints[3] = pnt4; graph.DrawLines( m_penDark, arrPoints ); pnt1.X++; pnt1.Y++; pnt2.X-=2; pnt2.Y++; pnt4.X++; pnt4.Y-=2; // set new values to array of pointers arrPoints[0] = arrPoints[2] = pnt1; arrPoints[1] = pnt2; arrPoints[3] = pnt4; graph.DrawLines( m_penDarkDark, arrPoints ); pnt1.X = rect.X + rect.Width; pnt1.Y = rect.Y + rect.Height; pnt2.X = rect.X; pnt2.Y = rect.Y + rect.Height; pnt4.X = rect.X + rect.Width; pnt4.Y = rect.Y; // set new values to array of pointers arrPoints[0] = arrPoints[2] = pnt1; arrPoints[1] = pnt2; arrPoints[3] = pnt4; graph.DrawLines( m_penLightLight, arrPoints ); pnt1.X--; pnt1.Y--; pnt2.X++; pnt2.Y--; pnt4.X--; pnt4.Y++; // set new values to array of pointers arrPoints[0] = arrPoints[2] = pnt1; arrPoints[1] = pnt2; arrPoints[3] = pnt4; graph.DrawLines( m_penLight, arrPoints ); #endregion break; case Canvas3DStyle.Upped: #region Canvas 3D Style Upped // draw left upper corner pnt1.X = rect.X; pnt1.Y = rect.Y; pnt2.X = rect.X + rect.Width; pnt2.Y = rect.Y; pnt4.X = rect.X; pnt4.Y = rect.Y + rect.Height; // set new values to array of pointers arrPoints[0] = arrPoints[2] = pnt1; arrPoints[1] = pnt2; arrPoints[3] = pnt4; graph.DrawLines( m_penLightLight, arrPoints ); pnt1.X++; pnt1.Y++; pnt2.X-=2; pnt2.Y++; pnt4.X++; pnt4.Y-=2; // set new values to array of pointers arrPoints[0] = arrPoints[2] = pnt1; arrPoints[1] = pnt2; arrPoints[3] = pnt4; graph.DrawLines( m_penLight, arrPoints ); pnt1.X = rect.X + rect.Width; pnt1.Y = rect.Y + rect.Height; pnt2.X = rect.X; pnt2.Y = rect.Y + rect.Height; pnt4.X = rect.X + rect.Width; pnt4.Y = rect.Y; // set new values to array of pointers arrPoints[0] = arrPoints[2] = pnt1; arrPoints[1] = pnt2; arrPoints[3] = pnt4; graph.DrawLines( m_penDarkDark, arrPoints ); pnt1.X--; pnt1.Y--; pnt2.X++; pnt2.Y--; pnt4.X--; pnt4.Y++; // set new values to array of pointers arrPoints[0] = arrPoints[2] = pnt1; arrPoints[1] = pnt2; arrPoints[3] = pnt4; graph.DrawLines( m_penDark, arrPoints ); #endregion break; case Canvas3DStyle.Single: #region Canvas 3D Style Single // draw left upper corner pnt1.X = rect.X; pnt1.Y = rect.Y; pnt2.X = rect.Width; pnt2.Y = rect.Y; pnt4.X = rect.X; pnt4.Y = rect.Height; // set new values to array of pointers arrPoints[0] = arrPoints[2] = pnt1; arrPoints[1] = pnt2; arrPoints[3] = pnt4; graph.DrawLines( m_penDark, arrPoints ); // draw right low corner pnt1.X = rect.Width; pnt1.Y = rect.Height; pnt2.X = rect.X; pnt2.Y = rect.Height; pnt4.X = rect.Width; pnt4.Y = rect.Y; // set new values to array of pointers arrPoints[0] = arrPoints[2] = pnt1; arrPoints[1] = pnt2; arrPoints[3] = pnt4; graph.DrawLines( m_penLightLight, arrPoints ); #endregion break; } } /// <summary> /// Draw Active rectangle by blue colors /// </summary> /// <param name="graph">Graphic context where premitive must be draw</param> /// <param name="rect">Destination Rectangle</param> /// <param name="state">State of rectangle. Influence on colors by which rectangle /// will be drawed</param> public void DrawActiveRectangle( Graphics graph, Rectangle rect, HightlightStyle state ) { Color highlight = ( state == HightlightStyle.Active ) ? ColorUtil.VSNetBackgroundColor : ColorUtil.VSNetSelectionColor; // Color.FromArgb( 182, 189, 210 ) : Color.FromArgb(212,213,216); Color highBorder = SystemColors.Highlight; //Color.FromArgb( 10, 36, 106 ); SolidBrush high = new SolidBrush( highlight ); SolidBrush bord = new SolidBrush( highBorder ); Pen penBord = new Pen( bord ); graph.FillRectangle( high, rect ); graph.DrawRectangle( penBord, rect ); penBord.Dispose(); bord.Dispose(); high.Dispose(); } /// <summary> /// Draw Active rectangle. /// </summary> /// <param name="graph">Graphic context where premitive must be draw</param> /// <param name="rect">Destination Rectangle</param> /// <param name="state">State of rectangle. Influence on colors by which rectangle /// will be drawed</param> /// <param name="bSubRect">Indicate do we need rectangle width and height fix</param> public void DrawActiveRectangle( Graphics graph, Rectangle rect, HightlightStyle state, bool bSubRect ) { Rectangle rc = ( bSubRect ) ? FixRectangleHeightWidth( rect ) : rect; DrawActiveRectangle( graph, rc, state ); } /// <summary> /// Make rectangle width and height less on one pixel. This useful beacause /// in some cases rectangle last pixels does not shown. /// </summary> /// <param name="rect">Rectangle which context must be fixed</param> /// <returns>Return new Rectangle object which contains fixed values</returns> static public Rectangle FixRectangleHeightWidth( Rectangle rect ) { return new Rectangle( rect.X, rect.Y, rect.Width - 1, rect.Height - 1 ); } #endregion #region Class Helper Functions /// <summary> /// Calculate X and Y coordiante to place object in center of Rectangle /// </summary> /// <param name="rect">Destination Rectangle</param> /// <param name="sz">Object Size</param> /// <returns>Point class with X and Y coordinate of center</returns> static public Point CalculateCenter( Rectangle rect, Size sz ) { Point pnt1 = new Point( 0 ); pnt1.X = rect.X + ( rect.Width - sz.Width ) / 2; pnt1.Y = rect.Y + ( rect.Height - sz.Height ) / 2; return pnt1; } #endregion #region Methods /// <summary> /// Draw 3D styled Rectangle. /// </summary> /// <param name="g">Graphics canvas where rectangle must drawed</param> /// <param name="rc">Rectangle coordinates</param> /// <param name="clrTL">Color of Top Left corner of rectangle</param> /// <param name="clrBR">Color of Bottom Right corner of rectangle</param> static public void Draw3DRect( Graphics g, Rectangle rc, Color clrTL, Color clrBR ) { Draw3DRect( g, rc.Left, rc.Top, rc.Width, rc.Height, clrTL, clrBR ); } static public void Draw3DRect( Graphics g, int x, int y, int width, int height, Color clrTL, Color clrBR ) { using( Brush brushTL = new SolidBrush( clrTL ) ) { using( Brush brushBR = new SolidBrush( clrBR ) ) { g.FillRectangle( brushTL, x, y, width - 1, 1 ); g.FillRectangle( brushTL, x, y, 1, height - 1 ); g.FillRectangle( brushBR, x + width, y, -1, height ); g.FillRectangle( brushBR, x, y + height, width, -1 ); } } } static public void StrechBitmap( Graphics gDest, Rectangle rcDest, Bitmap bitmap ) { // Draw From bitmap IntPtr hDCTo = gDest.GetHdc(); WindowsAPI.SetStretchBltMode(hDCTo, (int)StrechModeFlags.HALFTONE); IntPtr hDCFrom = WindowsAPI.CreateCompatibleDC(hDCTo); IntPtr hOldFromBitmap = WindowsAPI.SelectObject(hDCFrom, bitmap.GetHbitmap()); WindowsAPI.StretchBlt(hDCTo, rcDest.Left , rcDest.Top, rcDest.Width, rcDest.Height, hDCFrom, 0 , 0, bitmap.Width, bitmap.Height, (int)PatBltTypes.SRCCOPY); // Cleanup WindowsAPI.SelectObject(hDCFrom, hOldFromBitmap); gDest.ReleaseHdc(hDCTo); } static public void StrechBitmap( Graphics gDest, Rectangle rcDest, Rectangle rcSource, Bitmap bitmap ) { // Draw From bitmap IntPtr hDCTo = gDest.GetHdc(); WindowsAPI.SetStretchBltMode(hDCTo, (int)StrechModeFlags.COLORONCOLOR); IntPtr hDCFrom = WindowsAPI.CreateCompatibleDC(hDCTo); IntPtr hOldFromBitmap = WindowsAPI.SelectObject(hDCFrom, bitmap.GetHbitmap()); WindowsAPI.StretchBlt(hDCTo, rcDest.Left , rcDest.Top, rcDest.Width, rcDest.Height, hDCFrom, rcSource.Left , rcSource.Top, rcSource.Width, rcSource.Height, (int)PatBltTypes.SRCCOPY); // Cleanup WindowsAPI.SelectObject(hDCFrom, hOldFromBitmap); gDest.ReleaseHdc(hDCTo); } static public Bitmap GetStrechedBitmap( Graphics gDest, Rectangle rcDest, Bitmap bitmap ) { // Draw To bitmap Bitmap newBitmap = new Bitmap(rcDest.Width, rcDest.Height); Graphics gBitmap = Graphics.FromImage(newBitmap); IntPtr hDCTo = gBitmap.GetHdc(); WindowsAPI.SetStretchBltMode(hDCTo, (int)StrechModeFlags.COLORONCOLOR); IntPtr hDCFrom = WindowsAPI.CreateCompatibleDC(hDCTo); IntPtr hOldFromBitmap = WindowsAPI.SelectObject(hDCFrom, bitmap.GetHbitmap()); WindowsAPI.StretchBlt(hDCTo, rcDest.Left , rcDest.Top, rcDest.Width, rcDest.Height, hDCFrom, 0 , 0, bitmap.Width, bitmap.Height, (int)PatBltTypes.SRCCOPY); // Cleanup WindowsAPI.SelectObject(hDCFrom, hOldFromBitmap); gBitmap.ReleaseHdc(hDCTo); return newBitmap; } static public Bitmap GetTileBitmap( Rectangle rcDest, Bitmap bitmap ) { Bitmap tiledBitmap = new Bitmap( rcDest.Width, rcDest.Height ); using( Graphics g = Graphics.FromImage(tiledBitmap) ) { for ( int i = 0; i < tiledBitmap.Width; i += bitmap.Width ) { for ( int j = 0; j < tiledBitmap.Height; j += bitmap.Height ) { g.DrawImage( bitmap, new Point( i, j ) ); } } } return tiledBitmap; } static public void DrawArrowGlyph( Graphics g, Rectangle rc, bool up, Brush brush ) { // Draw arrow glyph with the default size of 5 pixel wide and 3 pixel high DrawArrowGlyph( g, rc, 5, 3, up, brush ); } static public void DrawArrowGlyph( Graphics g, Rectangle rc, int arrowWidth, int arrowHeight, bool up, Brush brush ) { // TIP: use an odd number for the arrowWidth and // arrowWidth/2+1 for the arrowHeight // so that the arrow gets the same pixel number // on the left and on the right and get symetrically painted Point[] pts = new Point[3]; int yMiddle = rc.Top + rc.Height/2 - arrowHeight/2+1; int xMiddle = rc.Left + rc.Width/2; int yArrowHeight = yMiddle + arrowHeight; int xArrowWidthR = xMiddle + arrowWidth/2; int xArrowWidthL = xMiddle - arrowWidth/2; if( up ) { pts[0] = new Point( xMiddle, yMiddle-2 ); pts[1] = new Point( xArrowWidthL - 1, yArrowHeight - 1 ); pts[2] = new Point( xArrowWidthR + 1, yArrowHeight - 1 ); } else { pts[0] = new Point( xArrowWidthL, yMiddle ); pts[1] = new Point( xArrowWidthR + 1, yMiddle ); pts[2] = new Point( xMiddle, yArrowHeight ); } g.FillPolygon( brush, pts ); } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mail; using System.Net.Mime; using System.Security.Cryptography; using System.Security.Principal; using System.ServiceModel.Web; using System.Web.Configuration; using CALI.Database.Logic.Auth; using CALI.Database.Contracts.Auth; namespace CALI.WebSite.Services { /// <summary> /// The set of permissions available /// </summary> public enum PermissionEnum : int { None, Client_Users_SelectByUser_Current, Client_Users_SelectByUser_UpdateProfile, Client_Users_Exists, Client_Users_Search, Client_Users_SelectAll } /// <summary> /// The authentication base class provides the logic for handling permissions and authentication /// </summary> public abstract partial class AuthenticationBase { protected List<PermissionEnum> _readPermissions = new List<PermissionEnum> { PermissionEnum.Client_Users_SelectByUser_Current, PermissionEnum.Client_Users_SelectByUser_UpdateProfile, PermissionEnum.Client_Users_Exists, PermissionEnum.Client_Users_Search, PermissionEnum.Client_Users_SelectAll }; public const string AnonymousAuthId = "ANON"; public const string WindowsAuthId = "_"; public const string ServiceAuthTokenCookieName = "ServiceAuthToken"; public const string CreateFail_UserNameExists = "FAIL_USERNAMEEXISTS"; public const string CreateFail_EmailExists = "FAIL_EMAILEXISTS"; public const string CreateFail_CantEmail = "FAIL_CANTEMAIL"; public const string CreateFail_Exception = "FAIL_EXCEPTION"; public const string CreateSuccess = "SUCCESS"; /// <summary> /// Override this and return false to prevent auto enrollment of windows users /// when the Check(.) service call is made. /// </summary> public virtual bool AutoEnrollWindowsUsersOnCheck { get { return true; } } public virtual List<PermissionEnum> ReadPermissions { get { return _readPermissions; } } //The following will be implemented by the end coder... //Copy and paste from the generated ServiceRegister front class. public virtual List<PermissionEnum> AnonymousPermissions { get { return ReadPermissions; } } public Dictionary<string, int> UserIdCache = new Dictionary<string, int>(); public Dictionary<string, UserContract> UserCache = new Dictionary<string, UserContract>(); public SpecificCacheContainer<int,List<int>> UserPermissionCache = new SpecificCacheContainer<int, List<int>>(); /// <summary> /// This is where you provide a PIPE (|) delimited list of domains for cross script calling. /// </summary> public virtual string AllowedOrigins { get { return "*"; } } /// <summary> /// Gets a user by the providing auth id. AuthID can be the GUID, or "_" for windows auth. /// </summary> /// <param name="authId">The value of UserToken or "." for windows auth.</param> public UserContract GetUser(string authId) { if(authId == AnonymousAuthId) return null; var id = authId; if(id == WindowsAuthId) id = GetCurrentWindowsId(); lock(UserCache) if(UserCache.ContainsKey(id)) return UserCache[id]; var results = (authId) == WindowsAuthId ? UserLogic.SelectBy_WINSIDNow(id) : UserLogic.SelectBy_UserTokenNow(new Guid(authId)); if(results.Count == 0) return null; var user = results[0]; lock (UserCache) UserCache[id] = user; lock (UserIdCache) UserIdCache[id] = user.UserId ?? 0; return user; } /// <summary> /// Gets a user id by the providing auth id. AuthID can be the GUID, or "_" for windows auth. /// </summary> /// <param name="authId">The value of UserToken or "." for windows auth.</param> public int GetUserId(string authId) { var id = authId; if(id == ".") id = GetCurrentWindowsId(); if(UserIdCache.ContainsKey(id)) return UserIdCache[id]; var usr = GetUser(authId); return usr == null ? 0 : usr.UserId ?? 0; } /// <summary> /// Check if the provided authentication id is valid /// This method is called when a service call fails, to double check authorized use. /// </summary> /// <param name="authId">The authentication id</param> /// <returns>True if the auth id is still valid.</returns> public virtual bool CheckAuthId(string authId) { if(authId == AnonymousAuthId) return false; var id = authId; if(id == WindowsAuthId) id = GetCurrentWindowsId(); var results = authId == WindowsAuthId ? UserLogic.SelectBy_WINSIDNow(id) : UserLogic.SelectBy_UserTokenNow(new Guid(authId)); //Auto Enroll windows auth? if(AutoEnrollWindowsUsersOnCheck && results.Count == 0 && authId == WindowsAuthId) { var user = CreateAccountForCurrentWindowsUser(); if(user != null) results.Add(user); } //Fail check if user is not active if(results.Count > 0) { if(!results[0].IsActive) return false; } return (results.Count > 0); } /// <summary> /// Authenticate the provided username and password, return a unique identifier for the user. /// </summary> /// <param name="userName">The username</param> /// <param name="password">The password, as MD5[GetAuthTokenForHash+PasswordHashHex]</param> /// <returns>A unique id for the user, or "NO Auth" for failed auth.</returns> public virtual string Authenticate(string userName, string password) { var success = false; var results = UserLogic.SelectBy_UserNameNow(userName); if (results.Count == 0) return "NO Auth"; var user = results[0]; if (user.IsActive == false) return "NO Auth"; var newUserToken = Guid.NewGuid(); var oldToken = user.AuthToken; var pwBytes = oldToken + BitConverter.ToString(user.Password).Replace("-", ""); var pwHashTokenBytes = MD5.Create().ComputeHash(System.Text.Encoding.ASCII.GetBytes(pwBytes)); var pwHashToken = BitConverter.ToString(pwHashTokenBytes).Replace("-",""); user.FailedLogins += 1; //Increase logon attempts. (note: this is reset to 0 on success below) user.AuthToken = Guid.NewGuid(); //Reset auth token. if (pwHashToken == password) { user.UserToken = newUserToken; user.FailedLogins = 0; success = true; } UserLogic.UpdateNow(user); return success ? newUserToken.ToString() : "NO Auth"; } /// <summary> /// Generate an auth token that the client will combine and hash with his password before /// calling the Authenticate method. /// </summary> /// <param name="userName">The username</param> /// <returns>A generated token to be combined with the password hash client side.</returns> public virtual string GetAuthTokenForHash(string userName) { var newAuthToken = Guid.NewGuid(); var results = UserLogic.SelectBy_UserNameNow(userName); if (results.Count == 0) { newAuthToken = Guid.Empty; } else { var user = results[0]; user.AuthToken = newAuthToken; UserLogic.UpdateNow(user); } return newAuthToken.ToString(); } /// <summary> /// Get the username associated with an email /// </summary> /// <param name="email">The email</param> /// <returns>The first username associated with an email.</returns> public virtual string GetUserNameForEmail(string email) { var results = UserLogic.SelectBy_EmailNow(email); if (results.Count == 0) return string.Empty; return results[0].UserName.ToString(); } /// <summary> /// Gets the permissions for the provided auth id, against the service name. /// </summary> /// <param name="authorizationId">The unique authorization id</param> /// <param name="permissionId">The requested permission id</param> /// <returns>True if the user has the requested permission.</returns> public virtual bool HasPermissions(string authorizationId, int permissionId) { var userId = 0; if(authorizationId != AnonymousAuthId) { var user = GetUser(authorizationId); if (user != null) { userId = user.UserId ?? 0; if(user.IsActive == false) userId = 0; // Inactive users have anonymous permissions. } } return HasPermissions(userId, permissionId); } /// <summary> /// Checks if the provided user id has the requested permission /// </summary> /// <param name="userId">The user id</param> /// <param name="permissionId">The requested permission id</param> /// <returns>True if the user has the requested permission.</returns> public virtual bool HasPermissions(int userId, int permissionId) { var cached = UserPermissionCache.Get(userId); if (cached != null && cached.Contains(permissionId)) return true; var permissionList = PermissionLogic.SelectBy_UserIdNow(userId); var permIdList = (from p in permissionList select p.PermissionId??0).ToList(); //Cache results for 10 minutes 10*60*1000 UserPermissionCache.Cache(userId,permIdList,600000); return permIdList.Contains(permissionId); } /// <summary> /// This method is called by the AuthSvc when it receives a request to create a user. /// </summary> /// <param name="displayName">The display name</param> /// <param name="userName">The user name</param> /// <param name="passwordHash">The hashed password bytes</param> public virtual string CreateNewUserRequest(string displayName, string email, string userName, byte[] passwordHash) { var existingUser = UserLogic.SelectBy_UserNameNow(userName); if(existingUser.Count > 0) return CreateFail_UserNameExists; existingUser = UserLogic.SelectBy_EmailNow(email); if(existingUser.Count > 0) return CreateFail_EmailExists; var user = new UserContract { DisplayName = displayName, UserName = userName, Email = email, Password = passwordHash, AuthToken = Guid.NewGuid(), UserToken = Guid.NewGuid(), IsActive = true }; var emailSent = SendActivationEmail(user); if(emailSent) UserLogic.InsertNow(user); return emailSent ? CreateSuccess: CreateFail_CantEmail; } /// <summary> /// Send an activation email to the user to have them activate their account /// </summary> /// <param name="user">the user to send an email to</param> /// <returns>true if there were no errors</returns> public virtual bool SendActivationEmail(UserContract user) { //TODO: Override this method, and use the code below with your own email message / landing page //- Send activation link in email, use user.UserToken as the authId //- Set user.IsActive = false to prevent account use until activated //For now, we don't need activation user.IsActive = true; return true; //Return false if you fail to send email (error) } /// <summary> /// Activate a user by their provided user token. /// </summary> /// <param name="userToken">The user token</param> public virtual bool ActivateUserByUserToken(string userToken) { //TODO: Potentially override this to have your system create //other default data on successful user activation after activating var tokenGuid = new Guid(userToken); var userResult = UserLogic.SelectBy_UserTokenNow(tokenGuid); if(userResult.Count > 0) { var user = userResult[0]; user.IsActive = true; UserLogic.SaveNow(user); //Update cached entity if (UserIdCache.ContainsKey(userToken)) UserIdCache[userToken] = user.UserId??0; if (UserCache.ContainsKey(userToken)) UserCache[userToken] = user; } return (userResult.Count > 0); } /// <summary> /// Creates an account for the current windows/forms auth user /// </summary> public virtual UserContract CreateAccountForCurrentWindowsUser() { var currentUserName = GetCurrentUserName(); var currentDisplayUserName = GetCurrentDisplayName(); var currentWinSid = GetCurrentWindowsId(); var currentEmail = GetCurrentEmail(); if(string.IsNullOrEmpty(currentWinSid)) return null; // Can't enroll anonymous. var user = new UserContract { DisplayName = currentDisplayUserName, UserName = currentUserName, Email = currentEmail, WINSID = currentWinSid, IsActive = true, Password = new byte[16] }; // ensure does not exist before saving new var existing = UserLogic.SelectBy_WINSIDNow(currentWinSid); if (existing.Count == 0) { UserLogic.SaveNow(user); return user; } return null; //User already exists, we didn't make one. } /// <summary> /// Returns the email address of the current windows user. /// </summary> /// <returns></returns> public virtual string GetCurrentEmail() { //Note: For sharepoint, override and uncomment the following //try //{ // if (SPContext.Current != null) return SPContext.Current.Web.CurrentUser.Email; //} //catch { } return "temp@email.com"; } /// <summary> /// Returns the current username of the windows authenticated user /// </summary> /// <returns>The user name of the windows auth user</returns> public virtual string GetCurrentUserName() { //Note: For sharepoint, override and uncomment the following //try //{ // if (SPContext.Current != null) return SPContext.Current.Web.CurrentUser.LoginName; //} //catch { } var currentIdentity = WindowsIdentity.GetCurrent(); if (currentIdentity != null) { if (currentIdentity.IsAnonymous) return string.Empty; if (currentIdentity.IsAuthenticated == false) return string.Empty; //Go by ID, unless we have a windows id, instead use SID. return currentIdentity.Name; } return string.Empty; } /// <summary> /// This method returns either the user name or the winsid depending on what is available. /// Anonymous is returned as an empty string. /// </summary> /// <returns>Current WINSID of windows auth user</returns> public virtual string GetCurrentWindowsId() { //NOTE: Override and uncomment this for sharepoint //try //{ // if (SPContext.Current != null) return SPContext.Current.Web.CurrentUser.Sid; //} catch { } var currentIdentity = WindowsIdentity.GetCurrent(); if (currentIdentity != null) { if (currentIdentity.IsAnonymous) return string.Empty; if (currentIdentity.IsAuthenticated == false) return string.Empty; if (currentIdentity.IsGuest) return string.Empty; if (currentIdentity.IsSystem) return string.Empty; if (currentIdentity.Name.ToLower().Contains("apppool")) return string.Empty; //Go by ID, unless we have a windows id, instead use SID. return (currentIdentity.User != null) ? currentIdentity.User.Value : currentIdentity.Name; } return string.Empty; } /// <summary> /// Use this to get the current windows/forms auth context display name /// </summary> /// <returns>Current display name of windows auth user</returns> public virtual string GetCurrentDisplayName() { //NOTE: Override and uncomment this for sharepoint //try //{ // if(SPContext.Current != null) return SPContext.Current.Web.CurrentUser.Name; //} catch { } var currentIdentity = WindowsIdentity.GetCurrent(); if (currentIdentity != null) { if (currentIdentity.IsAnonymous) return string.Empty; if (currentIdentity.IsAuthenticated == false) return string.Empty; //Go by ID, unless we have a windows id, instead use SID. return currentIdentity.Name; } return string.Empty; } /// <summary> /// This method is called when a password reset is requested /// </summary> /// <param name="userName"></param> /// <returns></returns> public virtual bool RequestPasswordReset(string userName) { var users = UserLogic.SelectBy_UserNameNow(userName); if(users.Count > 0) { var user = users[0]; if(user.UserId != 1) //Protect admin account { return SendPasswordResetEmail(user); } } return false; } /// <summary> /// Send a password reset email to the user /// </summary> /// <param name="user"></param> /// <returns>true if the email was sent</returns> public virtual bool SendPasswordResetEmail(UserContract user) { var bodyHtmlPath = System.Web.HttpContext.Current.Server.MapPath("/Scripts/Views/ResetEmailTemplate.html"); if (!File.Exists(bodyHtmlPath)) bodyHtmlPath = System.Web.HttpContext.Current.Server.MapPath("/Scripts/Views/gen/ResetEmailTemplate.html"); if (!File.Exists(bodyHtmlPath)) { throw new Exception("/Scripts/Views/gen/ResetEmailTemplate.html or /Scripts/Views/ResetEmailTemplate.html not found."); } var serverRootUrl = ""; if (WebOperationContext.Current != null) { var uri = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri; serverRootUrl = uri.OriginalString.Substring(0, uri.OriginalString.Length - uri.PathAndQuery.Length); } var mailFromEmail = WebConfigurationManager.AppSettings["MailFromEmail"]; var mailServer = WebConfigurationManager.AppSettings["MailServer"]; var mailFromName = WebConfigurationManager.AppSettings["MailFromName"]; if (string.IsNullOrEmpty(mailFromEmail)) { throw new Exception("Cannot send reset password email. Missing <configuration><appSettings><add key=\"MailFromEmail\" value=\"noreply@CALI.com\"/></appSettings></confiuration> in web.config"); } if (string.IsNullOrEmpty(mailServer)) { throw new Exception("Cannot send reset password email. Missing <configuration><appSettings><add key=\"MailServer\" value=\"smtp.CALI.com\"/></appSettings></confiuration> in web.config"); } if (string.IsNullOrEmpty(mailFromName)) { throw new Exception("Cannot send reset password email. Missing <configuration><appSettings><add key=\"MailFromName\" value=\"CALI Password Reset\"/></appSettings></confiuration> in web.config"); } var bodyHtml = File.ReadAllText(bodyHtmlPath); bodyHtml = bodyHtml .Replace("{UserToken}", string.Format("{0:D}", user.UserToken)) .Replace("{DisplayName}", user.DisplayName) .Replace("{ServerRootUrl}", serverRootUrl); var from = new MailAddress(mailFromEmail, mailFromName, System.Text.Encoding.UTF8); var to = new MailAddress(user.Email); // Specify the message content. using (var client = new SmtpClient(mailServer)) { using (var message = new MailMessage(from, to)) { message.Subject = "CALI Password Reset"; message.ReplyToList.Add(new MailAddress(mailFromEmail)); message.Body = bodyHtml; message.BodyEncoding = System.Text.Encoding.UTF8; message.SubjectEncoding = System.Text.Encoding.UTF8; message.IsBodyHtml = true; var htmlView = AlternateView.CreateAlternateViewFromString(bodyHtml, new ContentType("text/html")); message.AlternateViews.Add(htmlView); try { client.Send(message); } catch (Exception ex) { var realException = string.Format( "Failed to send PW reset email. <{0}>" + Environment.NewLine + "TO: {1}" + Environment.NewLine + "FROM: {2}" + Environment.NewLine + "SERVER: {3}" + Environment.NewLine + "Exception detail:" + Environment.NewLine + " {4}", ex.Message, user.Email, mailFromEmail, mailServer, ex ); throw new Exception(realException,ex); } } } return true; } /// <summary> /// Use this method to change the user's password by their auth id to a new password /// </summary> /// <param name="authId"></param> /// <param name="newPasswordHash"></param> /// <returns></returns> public virtual bool ChangePassword(string authId, byte[] newPasswordHash) { var user = GetUser(authId); if(user != null) { user.Password = newPasswordHash; UserLogic.SaveNow(user); } return user != null; } } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Text; using System.Windows.Forms; using TheArtOfDev.HtmlRenderer.Core; using TheArtOfDev.HtmlRenderer.Core.Entities; using TheArtOfDev.HtmlRenderer.Core.Utils; using TheArtOfDev.HtmlRenderer.WinForms.Utilities; namespace TheArtOfDev.HtmlRenderer.WinForms { /// <summary> /// Provides HTML rendering using the text property.<br/> /// WinForms control that will render html content in it's client rectangle.<br/> /// If <see cref="AutoScroll"/> is true and the layout of the html resulted in its content beyond the client bounds /// of the panel it will show scrollbars (horizontal/vertical) allowing to scroll the content.<br/> /// If <see cref="AutoScroll"/> is false html content outside the client bounds will be clipped.<br/> /// The control will handle mouse and keyboard events on it to support html text selection, copy-paste and mouse clicks.<br/> /// <para> /// The major differential to use HtmlPanel or HtmlLabel is size and scrollbars.<br/> /// If the size of the control depends on the html content the HtmlLabel should be used.<br/> /// If the size is set by some kind of layout then HtmlPanel is more suitable, also shows scrollbars if the html contents is larger than the control client rectangle.<br/> /// </para> /// <para> /// <h4>AutoScroll:</h4> /// Allows showing scrollbars if html content is placed outside the visible boundaries of the panel. /// </para> /// <para> /// <h4>LinkClicked event:</h4> /// Raised when the user clicks on a link in the html.<br/> /// Allows canceling the execution of the link. /// </para> /// <para> /// <h4>StylesheetLoad event:</h4> /// Raised when a stylesheet is about to be loaded by file path or URI by link element.<br/> /// This event allows to provide the stylesheet manually or provide new source (file or uri) to load from.<br/> /// If no alternative data is provided the original source will be used.<br/> /// </para> /// <para> /// <h4>ImageLoad event:</h4> /// Raised when an image is about to be loaded by file path or URI.<br/> /// This event allows to provide the image manually, if not handled the image will be loaded from file or download from URI. /// </para> /// <para> /// <h4>RenderError event:</h4> /// Raised when an error occurred during html rendering.<br/> /// </para> /// </summary> public class HtmlPanel : ScrollableControl { #region Fields and Consts /// <summary> /// Underline html container instance. /// </summary> protected HtmlContainer _htmlContainer; /// <summary> /// The current border style of the control /// </summary> protected BorderStyle _borderStyle; /// <summary> /// the raw base stylesheet data used in the control /// </summary> protected string _baseRawCssData; /// <summary> /// the base stylesheet data used in the control /// </summary> protected CssData _baseCssData; /// <summary> /// the current html text set in the control /// </summary> protected string _text; /// <summary> /// If to use cursors defined by the operating system or .NET cursors /// </summary> protected bool _useSystemCursors; /// <summary> /// The text rendering hint to be used for text rendering. /// </summary> protected TextRenderingHint _textRenderingHint = TextRenderingHint.SystemDefault; /// <summary> /// The last position of the scrollbars to know if it has changed to update mouse /// </summary> protected Point _lastScrollOffset; #endregion /// <summary> /// Creates a new HtmlPanel and sets a basic css for it's styling. /// </summary> public HtmlPanel() { AutoScroll = true; BackColor = SystemColors.Window; DoubleBuffered = true; SetStyle(ControlStyles.ResizeRedraw, true); SetStyle(ControlStyles.SupportsTransparentBackColor, true); _htmlContainer = new HtmlContainer(); _htmlContainer.LoadComplete += OnLoadComplete; _htmlContainer.LinkClicked += OnLinkClicked; _htmlContainer.RenderError += OnRenderError; _htmlContainer.Refresh += OnRefresh; _htmlContainer.ScrollChange += OnScrollChange; _htmlContainer.StylesheetLoad += OnStylesheetLoad; _htmlContainer.ImageLoad += OnImageLoad; } /// <summary> /// Raised when the BorderStyle property value changes. /// </summary> [Category("Property Changed")] public event EventHandler BorderStyleChanged; /// <summary> /// Raised when the set html document has been fully loaded.<br/> /// Allows manipulation of the html dom, scroll position, etc. /// </summary> public event EventHandler LoadComplete; /// <summary> /// Raised when the user clicks on a link in the html.<br/> /// Allows canceling the execution of the link. /// </summary> public event EventHandler<HtmlLinkClickedEventArgs> LinkClicked; /// <summary> /// Raised when an error occurred during html rendering.<br/> /// </summary> public event EventHandler<HtmlRenderErrorEventArgs> RenderError; /// <summary> /// Raised when a stylesheet is about to be loaded by file path or URI by link element.<br/> /// This event allows to provide the stylesheet manually or provide new source (file or uri) to load from.<br/> /// If no alternative data is provided the original source will be used.<br/> /// </summary> public event EventHandler<HtmlStylesheetLoadEventArgs> StylesheetLoad; /// <summary> /// Raised when an image is about to be loaded by file path or URI.<br/> /// This event allows to provide the image manually, if not handled the image will be loaded from file or download from URI. /// </summary> public event EventHandler<HtmlImageLoadEventArgs> ImageLoad; /// <summary> /// Gets or sets a value indicating if anti-aliasing should be avoided for geometry like backgrounds and borders (default - false). /// </summary> [Category("Behavior")] [DefaultValue(false)] [Description("If anti-aliasing should be avoided for geometry like backgrounds and borders")] public virtual bool AvoidGeometryAntialias { get { return _htmlContainer.AvoidGeometryAntialias; } set { _htmlContainer.AvoidGeometryAntialias = value; } } /// <summary> /// Gets or sets a value indicating if image loading only when visible should be avoided (default - false).<br/> /// True - images are loaded as soon as the html is parsed.<br/> /// False - images that are not visible because of scroll location are not loaded until they are scrolled to. /// </summary> /// <remarks> /// Images late loading improve performance if the page contains image outside the visible scroll area, especially if there is large /// amount of images, as all image loading is delayed (downloading and loading into memory).<br/> /// Late image loading may effect the layout and actual size as image without set size will not have actual size until they are loaded /// resulting in layout change during user scroll.<br/> /// Early image loading may also effect the layout if image without known size above the current scroll location are loaded as they /// will push the html elements down. /// </remarks> [Category("Behavior")] [DefaultValue(false)] [Description("If image loading only when visible should be avoided")] public virtual bool AvoidImagesLateLoading { get { return _htmlContainer.AvoidImagesLateLoading; } set { _htmlContainer.AvoidImagesLateLoading = value; } } /// <summary> /// Use GDI+ text rendering to measure/draw text.<br/> /// </summary> /// <remarks> /// <para> /// GDI+ text rendering is less smooth than GDI text rendering but it natively supports alpha channel /// thus allows creating transparent images. /// </para> /// <para> /// While using GDI+ text rendering you can control the text rendering using <see cref="Graphics.TextRenderingHint"/>, note that /// using <see cref="System.Drawing.Text.TextRenderingHint.ClearTypeGridFit"/> doesn't work well with transparent background. /// </para> /// </remarks> [Category("Behavior")] [DefaultValue(false)] [EditorBrowsable(EditorBrowsableState.Always)] [Description("If to use GDI+ text rendering to measure/draw text, false - use GDI")] public bool UseGdiPlusTextRendering { get { return _htmlContainer.UseGdiPlusTextRendering; } set { _htmlContainer.UseGdiPlusTextRendering = value; } } /// <summary> /// The text rendering hint to be used for text rendering. /// </summary> [Category("Behavior")] [EditorBrowsable(EditorBrowsableState.Always)] [DefaultValue(TextRenderingHint.SystemDefault)] [Description("The text rendering hint to be used for text rendering.")] public TextRenderingHint TextRenderingHint { get { return _textRenderingHint; } set { _textRenderingHint = value; } } /// <summary> /// If to use cursors defined by the operating system or .NET cursors /// </summary> [Category("Behavior")] [EditorBrowsable(EditorBrowsableState.Always)] [DefaultValue(false)] [Description("If to use cursors defined by the operating system or .NET cursors")] public bool UseSystemCursors { get { return _useSystemCursors; } set { _useSystemCursors = value; } } /// <summary> /// Gets or sets the border style. /// </summary> /// <value>The border style.</value> [Category("Appearance")] [DefaultValue(typeof(BorderStyle), "None")] public virtual BorderStyle BorderStyle { get { return _borderStyle; } set { if (BorderStyle != value) { _borderStyle = value; OnBorderStyleChanged(EventArgs.Empty); } } } /// <summary> /// Is content selection is enabled for the rendered html (default - true).<br/> /// If set to 'false' the rendered html will be static only with ability to click on links. /// </summary> [Browsable(true)] [DefaultValue(true)] [Category("Behavior")] [EditorBrowsable(EditorBrowsableState.Always)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Description("Is content selection is enabled for the rendered html.")] public virtual bool IsSelectionEnabled { get { return _htmlContainer.IsSelectionEnabled; } set { _htmlContainer.IsSelectionEnabled = value; } } /// <summary> /// Is the build-in context menu enabled and will be shown on mouse right click (default - true) /// </summary> [Browsable(true)] [DefaultValue(true)] [Category("Behavior")] [EditorBrowsable(EditorBrowsableState.Always)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Description("Is the build-in context menu enabled and will be shown on mouse right click.")] public virtual bool IsContextMenuEnabled { get { return _htmlContainer.IsContextMenuEnabled; } set { _htmlContainer.IsContextMenuEnabled = value; } } /// <summary> /// Set base stylesheet to be used by html rendered in the panel. /// </summary> [Browsable(true)] [Category("Appearance")] [Description("Set base stylesheet to be used by html rendered in the control.")] [Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public virtual string BaseStylesheet { get { return _baseRawCssData; } set { _baseRawCssData = value; _baseCssData = HtmlRender.ParseStyleSheet(value); _htmlContainer.SetHtml(_text, _baseCssData); } } /// <summary> /// Gets or sets a value indicating whether the container enables the user to scroll to any controls placed outside of its visible boundaries. /// </summary> [Browsable(true)] [Description("Sets a value indicating whether the container enables the user to scroll to any controls placed outside of its visible boundaries.")] public override bool AutoScroll { get { return base.AutoScroll; } set { base.AutoScroll = value; } } /// <summary> /// Gets or sets the text of this panel /// </summary> [Browsable(true)] [Description("Sets the html of this control.")] public override string Text { get { return _text; } set { _text = value; base.Text = value; if (!IsDisposed) { VerticalScroll.Value = VerticalScroll.Minimum; _htmlContainer.SetHtml(_text, _baseCssData); PerformLayout(); Invalidate(); InvokeMouseMove(); } } } /// <summary> /// Get the currently selected text segment in the html. /// </summary> [Browsable(false)] public virtual string SelectedText { get { return _htmlContainer.SelectedText; } } /// <summary> /// Copy the currently selected html segment with style. /// </summary> [Browsable(false)] public virtual string SelectedHtml { get { return _htmlContainer.SelectedHtml; } } /// <summary> /// Get html from the current DOM tree with inline style. /// </summary> /// <returns>generated html</returns> public virtual string GetHtml() { return _htmlContainer != null ? _htmlContainer.GetHtml() : null; } /// <summary> /// Get the rectangle of html element as calculated by html layout.<br/> /// Element if found by id (id attribute on the html element).<br/> /// Note: to get the screen rectangle you need to adjust by the hosting control.<br/> /// </summary> /// <param name="elementId">the id of the element to get its rectangle</param> /// <returns>the rectangle of the element or null if not found</returns> public virtual RectangleF? GetElementRectangle(string elementId) { return _htmlContainer != null ? _htmlContainer.GetElementRectangle(elementId) : null; } /// <summary> /// Adjust the scrollbar of the panel on html element by the given id.<br/> /// The top of the html element rectangle will be at the top of the panel, if there /// is not enough height to scroll to the top the scroll will be at maximum.<br/> /// </summary> /// <param name="elementId">the id of the element to scroll to</param> public virtual void ScrollToElement(string elementId) { ArgChecker.AssertArgNotNullOrEmpty(elementId, "elementId"); if (_htmlContainer != null) { var rect = _htmlContainer.GetElementRectangle(elementId); if (rect.HasValue) { UpdateScroll(Point.Round(rect.Value.Location)); _htmlContainer.HandleMouseMove(this, new MouseEventArgs(MouseButtons, 0, MousePosition.X, MousePosition.Y, 0)); } } } /// <summary> /// Clear the current selection. /// </summary> public void ClearSelection() { if (_htmlContainer != null) _htmlContainer.ClearSelection(); } #region Private methods #if !MONO /// <summary> /// Override to support border for the control. /// </summary> protected override CreateParams CreateParams { get { CreateParams createParams = base.CreateParams; switch (_borderStyle) { case BorderStyle.FixedSingle: createParams.Style |= Win32Utils.WsBorder; break; case BorderStyle.Fixed3D: createParams.ExStyle |= Win32Utils.WsExClientEdge; break; } return createParams; } } #endif /// <summary> /// Perform the layout of the html in the control. /// </summary> protected override void OnLayout(LayoutEventArgs levent) { PerformHtmlLayout(); base.OnLayout(levent); // to handle if vertical scrollbar is appearing or disappearing if (_htmlContainer != null && Math.Abs(_htmlContainer.MaxSize.Width - ClientSize.Width) > 0.1) { PerformHtmlLayout(); base.OnLayout(levent); } } /// <summary> /// Perform html container layout by the current panel client size. /// </summary> protected void PerformHtmlLayout() { if (_htmlContainer != null) { _htmlContainer.MaxSize = new SizeF(ClientSize.Width - Padding.Horizontal, 0); Graphics g = Utils.CreateGraphics(this); if (g != null) { using (g) { _htmlContainer.PerformLayout(g); } } AutoScrollMinSize = Size.Round(new SizeF(_htmlContainer.ActualSize.Width + Padding.Horizontal, _htmlContainer.ActualSize.Height)); } } /// <summary> /// Perform paint of the html in the control. /// </summary> protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (_htmlContainer != null) { e.Graphics.TextRenderingHint = _textRenderingHint; e.Graphics.SetClip(ClientRectangle); _htmlContainer.Location = new PointF(Padding.Left, Padding.Top); _htmlContainer.ScrollOffset = AutoScrollPosition; _htmlContainer.PerformPaint(e.Graphics); if (!_lastScrollOffset.Equals(_htmlContainer.ScrollOffset)) { _lastScrollOffset = _htmlContainer.ScrollOffset; InvokeMouseMove(); } } } /// <summary> /// Set focus on the control for keyboard scrollbars handling. /// </summary> protected override void OnClick(EventArgs e) { base.OnClick(e); Focus(); } /// <summary> /// Handle mouse move to handle hover cursor and text selection. /// </summary> protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (_htmlContainer != null) _htmlContainer.HandleMouseMove(this, e); } /// <summary> /// Handle mouse leave to handle cursor change. /// </summary> protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); if (_htmlContainer != null) _htmlContainer.HandleMouseLeave(this); } /// <summary> /// Handle mouse down to handle selection. /// </summary> protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (_htmlContainer != null) _htmlContainer.HandleMouseDown(this, e); } /// <summary> /// Handle mouse up to handle selection and link click. /// </summary> protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (_htmlContainer != null) _htmlContainer.HandleMouseUp(this, e); } /// <summary> /// Handle mouse double click to select word under the mouse. /// </summary> protected override void OnMouseDoubleClick(MouseEventArgs e) { base.OnMouseDoubleClick(e); if (_htmlContainer != null) _htmlContainer.HandleMouseDoubleClick(this, e); } /// <summary> /// Handle key down event for selection, copy and scrollbars handling. /// </summary> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (_htmlContainer != null) _htmlContainer.HandleKeyDown(this, e); if (e.KeyCode == Keys.Up) { VerticalScroll.Value = Math.Max(VerticalScroll.Value - 70, VerticalScroll.Minimum); PerformLayout(); } else if (e.KeyCode == Keys.Down) { VerticalScroll.Value = Math.Min(VerticalScroll.Value + 70, VerticalScroll.Maximum); PerformLayout(); } else if (e.KeyCode == Keys.PageDown) { VerticalScroll.Value = Math.Min(VerticalScroll.Value + 400, VerticalScroll.Maximum); PerformLayout(); } else if (e.KeyCode == Keys.PageUp) { VerticalScroll.Value = Math.Max(VerticalScroll.Value - 400, VerticalScroll.Minimum); PerformLayout(); } else if (e.KeyCode == Keys.End) { VerticalScroll.Value = VerticalScroll.Maximum; PerformLayout(); } else if (e.KeyCode == Keys.Home) { VerticalScroll.Value = VerticalScroll.Minimum; PerformLayout(); } } /// <summary> /// Raises the <see cref="BorderStyleChanged" /> event. /// </summary> protected virtual void OnBorderStyleChanged(EventArgs e) { UpdateStyles(); var handler = BorderStyleChanged; if (handler != null) { handler(this, e); } } /// <summary> /// Propagate the LoadComplete event from root container. /// </summary> protected virtual void OnLoadComplete(EventArgs e) { var handler = LoadComplete; if (handler != null) handler(this, e); } /// <summary> /// Propagate the LinkClicked event from root container. /// </summary> protected virtual void OnLinkClicked(HtmlLinkClickedEventArgs e) { var handler = LinkClicked; if (handler != null) handler(this, e); } /// <summary> /// Propagate the Render Error event from root container. /// </summary> protected virtual void OnRenderError(HtmlRenderErrorEventArgs e) { var handler = RenderError; if (handler != null) handler(this, e); } /// <summary> /// Propagate the stylesheet load event from root container. /// </summary> protected virtual void OnStylesheetLoad(HtmlStylesheetLoadEventArgs e) { var handler = StylesheetLoad; if (handler != null) handler(this, e); } /// <summary> /// Propagate the image load event from root container. /// </summary> protected virtual void OnImageLoad(HtmlImageLoadEventArgs e) { var handler = ImageLoad; if (handler != null) handler(this, e); } /// <summary> /// Handle html renderer invalidate and re-layout as requested. /// </summary> protected virtual void OnRefresh(HtmlRefreshEventArgs e) { if (e.Layout) PerformLayout(); Invalidate(); } /// <summary> /// On html renderer scroll request adjust the scrolling of the panel to the requested location. /// </summary> protected virtual void OnScrollChange(HtmlScrollEventArgs e) { UpdateScroll(new Point((int)e.X, (int)e.Y)); } /// <summary> /// Adjust the scrolling of the panel to the requested location. /// </summary> /// <param name="location">the location to adjust the scroll to</param> protected virtual void UpdateScroll(Point location) { AutoScrollPosition = location; _htmlContainer.ScrollOffset = AutoScrollPosition; } /// <summary> /// call mouse move to handle paint after scroll or html change affecting mouse cursor. /// </summary> protected virtual void InvokeMouseMove() { try { // mono has issue throwing exception for no reason var mp = PointToClient(MousePosition); _htmlContainer.HandleMouseMove(this, new MouseEventArgs(MouseButtons.None, 0, mp.X, mp.Y, 0)); } catch { #if !MONO throw; #endif } } /// <summary> /// Used to add arrow keys to the handled keys in <see cref="OnKeyDown"/>. /// </summary> protected override bool IsInputKey(Keys keyData) { switch (keyData) { case Keys.Right: case Keys.Left: case Keys.Up: case Keys.Down: return true; case Keys.Shift | Keys.Right: case Keys.Shift | Keys.Left: case Keys.Shift | Keys.Up: case Keys.Shift | Keys.Down: return true; } return base.IsInputKey(keyData); } #if !MONO /// <summary> /// Override the proc processing method to set OS specific hand cursor. /// </summary> /// <param name="m">The Windows <see cref="T:System.Windows.Forms.Message"/> to process. </param> [DebuggerStepThrough] protected override void WndProc(ref Message m) { if (_useSystemCursors && m.Msg == Win32Utils.WmSetCursor && Cursor == Cursors.Hand) { try { // Replace .NET's hand cursor with the OS cursor Win32Utils.SetCursor(Win32Utils.LoadCursor(0, Win32Utils.IdcHand)); m.Result = IntPtr.Zero; return; } catch (Exception ex) { OnRenderError(this, new HtmlRenderErrorEventArgs(HtmlRenderErrorType.General, "Failed to set OS hand cursor", ex)); } } base.WndProc(ref m); } #endif /// <summary> /// Release the html container resources. /// </summary> protected override void Dispose(bool disposing) { if (_htmlContainer != null) { _htmlContainer.LoadComplete -= OnLoadComplete; _htmlContainer.LinkClicked -= OnLinkClicked; _htmlContainer.RenderError -= OnRenderError; _htmlContainer.Refresh -= OnRefresh; _htmlContainer.ScrollChange -= OnScrollChange; _htmlContainer.StylesheetLoad -= OnStylesheetLoad; _htmlContainer.ImageLoad -= OnImageLoad; _htmlContainer.Dispose(); _htmlContainer = null; } base.Dispose(disposing); } #region Private event handlers private void OnLoadComplete(object sender, EventArgs e) { OnLoadComplete(e); } private void OnLinkClicked(object sender, HtmlLinkClickedEventArgs e) { OnLinkClicked(e); } private void OnRenderError(object sender, HtmlRenderErrorEventArgs e) { if (InvokeRequired) Invoke(new MethodInvoker(() => OnRenderError(e))); else OnRenderError(e); } private void OnStylesheetLoad(object sender, HtmlStylesheetLoadEventArgs e) { OnStylesheetLoad(e); } private void OnImageLoad(object sender, HtmlImageLoadEventArgs e) { OnImageLoad(e); } private void OnRefresh(object sender, HtmlRefreshEventArgs e) { if (InvokeRequired) Invoke(new MethodInvoker(() => OnRefresh(e))); else OnRefresh(e); } private void OnScrollChange(object sender, HtmlScrollEventArgs e) { OnScrollChange(e); } #endregion #region Hide not relevant properties from designer /// <summary> /// Not applicable. /// </summary> [Browsable(false)] public override Font Font { get { return base.Font; } set { base.Font = value; } } /// <summary> /// Not applicable. /// </summary> [Browsable(false)] public override Color ForeColor { get { return base.ForeColor; } set { base.ForeColor = value; } } /// <summary> /// Not applicable. /// </summary> [Browsable(false)] public override bool AllowDrop { get { return base.AllowDrop; } set { base.AllowDrop = value; } } /// <summary> /// Not applicable. /// </summary> [Browsable(false)] public override RightToLeft RightToLeft { get { return base.RightToLeft; } set { base.RightToLeft = value; } } /// <summary> /// Not applicable. /// </summary> [Browsable(false)] public override Cursor Cursor { get { return base.Cursor; } set { base.Cursor = value; } } /// <summary> /// Not applicable. /// </summary> [Browsable(false)] public new bool UseWaitCursor { get { return base.UseWaitCursor; } set { base.UseWaitCursor = value; } } #endregion #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Analyzer.Utilities.FlowAnalysis.Analysis.PropertySetAnalysis; using Analyzer.Utilities.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.NetCore.Analyzers.Security.Helpers; namespace Microsoft.NetCore.Analyzers.Security { using static MicrosoftNetCoreAnalyzersResources; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class UseSecureCookiesASPNetCore : DiagnosticAnalyzer { internal static readonly DiagnosticDescriptor DefinitelyUseSecureCookiesASPNetCoreRule = SecurityHelpers.CreateDiagnosticDescriptor( "CA5382", nameof(DefinitelyUseSecureCookiesASPNetCore), nameof(DefinitelyUseSecureCookiesASPNetCoreMessage), RuleLevel.Disabled, isPortedFxCopRule: false, isDataflowRule: true, isReportedAtCompilationEnd: true, descriptionResourceStringName: nameof(UseSecureCookiesASPNetCoreDescription)); internal static readonly DiagnosticDescriptor MaybeUseSecureCookiesASPNetCoreRule = SecurityHelpers.CreateDiagnosticDescriptor( "CA5383", nameof(MaybeUseSecureCookiesASPNetCore), nameof(MaybeUseSecureCookiesASPNetCoreMessage), RuleLevel.Disabled, isPortedFxCopRule: false, isDataflowRule: true, isReportedAtCompilationEnd: true, descriptionResourceStringName: nameof(UseSecureCookiesASPNetCoreDescription)); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create( DefinitelyUseSecureCookiesASPNetCoreRule, MaybeUseSecureCookiesASPNetCoreRule); private static readonly ConstructorMapper constructorMapper = new( ImmutableArray.Create<PropertySetAbstractValueKind>( PropertySetAbstractValueKind.Flagged)); private static readonly PropertyMapperCollection PropertyMappers = new( new PropertyMapper( "Secure", (ValueContentAbstractValue valueContentAbstractValue) => { return PropertySetCallbacks.EvaluateLiteralValues(valueContentAbstractValue, o => o != null && o.Equals(false)); })); private static HazardousUsageEvaluationResult HazardousUsageCallback(IMethodSymbol methodSymbol, PropertySetAbstractValue propertySetAbstractValue) { return propertySetAbstractValue[0] switch { PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, _ => HazardousUsageEvaluationResult.Unflagged, }; } public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); // Security analyzer - analyze and report diagnostics on generated code. context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); // If there are more classes implement IResponseCookies, add them here later. HazardousUsageEvaluatorCollection hazardousUsageEvaluators = new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( WellKnownTypeNames.MicrosoftAspNetCoreHttpInternalResponseCookies, "Append", "options", HazardousUsageCallback)); context.RegisterCompilationStartAction( (CompilationStartAnalysisContext compilationStartAnalysisContext) => { var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilationStartAnalysisContext.Compilation); if (!wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName( WellKnownTypeNames.MicrosoftAspNetCoreHttpIResponseCookies, out var iResponseCookiesTypeSymbol)) { return; } wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName( WellKnownTypeNames.MicrosoftAspNetCoreHttpCookieOptions, out var cookieOptionsTypeSymbol); var rootOperationsNeedingAnalysis = PooledHashSet<(IOperation, ISymbol)>.GetInstance(); compilationStartAnalysisContext.RegisterOperationBlockStartAction( (OperationBlockStartAnalysisContext operationBlockStartAnalysisContext) => { // TODO: Handle case when exactly one of the below rules is configured to skip analysis. if (operationBlockStartAnalysisContext.Options.IsConfiguredToSkipAnalysis(DefinitelyUseSecureCookiesASPNetCoreRule, operationBlockStartAnalysisContext.OwningSymbol, operationBlockStartAnalysisContext.Compilation) && operationBlockStartAnalysisContext.Options.IsConfiguredToSkipAnalysis(MaybeUseSecureCookiesASPNetCoreRule, operationBlockStartAnalysisContext.OwningSymbol, operationBlockStartAnalysisContext.Compilation)) { return; } operationBlockStartAnalysisContext.RegisterOperationAction( (OperationAnalysisContext operationAnalysisContext) => { var invocationOperation = (IInvocationOperation)operationAnalysisContext.Operation; var methodSymbol = invocationOperation.TargetMethod; if (methodSymbol.ContainingType is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.Interfaces.Contains(iResponseCookiesTypeSymbol) && invocationOperation.TargetMethod.Name == "Append") { if (methodSymbol.Parameters.Length < 3) { operationAnalysisContext.ReportDiagnostic( invocationOperation.CreateDiagnostic( DefinitelyUseSecureCookiesASPNetCoreRule)); } else { lock (rootOperationsNeedingAnalysis) { rootOperationsNeedingAnalysis.Add((invocationOperation.GetRoot(), operationAnalysisContext.ContainingSymbol)); } } } }, OperationKind.Invocation); operationBlockStartAnalysisContext.RegisterOperationAction( (OperationAnalysisContext operationAnalysisContext) => { var argumentOperation = (IArgumentOperation)operationAnalysisContext.Operation; if (argumentOperation.Parameter.Type.Equals(cookieOptionsTypeSymbol)) { lock (rootOperationsNeedingAnalysis) { rootOperationsNeedingAnalysis.Add((argumentOperation.GetRoot(), operationAnalysisContext.ContainingSymbol)); } } }, OperationKind.Argument); }); compilationStartAnalysisContext.RegisterCompilationEndAction( (CompilationAnalysisContext compilationAnalysisContext) => { PooledDictionary<(Location Location, IMethodSymbol? Method), HazardousUsageEvaluationResult>? allResults = null; try { lock (rootOperationsNeedingAnalysis) { if (!rootOperationsNeedingAnalysis.Any()) { return; } allResults = PropertySetAnalysis.BatchGetOrComputeHazardousUsages( compilationAnalysisContext.Compilation, rootOperationsNeedingAnalysis, compilationAnalysisContext.Options, WellKnownTypeNames.MicrosoftAspNetCoreHttpCookieOptions, constructorMapper, PropertyMappers, hazardousUsageEvaluators, InterproceduralAnalysisConfiguration.Create( compilationAnalysisContext.Options, SupportedDiagnostics, rootOperationsNeedingAnalysis.First().Item1, compilationAnalysisContext.Compilation, defaultInterproceduralAnalysisKind: InterproceduralAnalysisKind.ContextSensitive)); } if (allResults == null) { return; } foreach (KeyValuePair<(Location Location, IMethodSymbol? Method), HazardousUsageEvaluationResult> kvp in allResults) { DiagnosticDescriptor descriptor; switch (kvp.Value) { case HazardousUsageEvaluationResult.Flagged: descriptor = DefinitelyUseSecureCookiesASPNetCoreRule; break; case HazardousUsageEvaluationResult.MaybeFlagged: descriptor = MaybeUseSecureCookiesASPNetCoreRule; break; default: Debug.Fail($"Unhandled result value {kvp.Value}"); continue; } RoslynDebug.Assert(kvp.Key.Method != null); // HazardousUsageEvaluations only for invocations. compilationAnalysisContext.ReportDiagnostic( Diagnostic.Create( descriptor, kvp.Key.Location, kvp.Key.Method.ToDisplayString( SymbolDisplayFormat.MinimallyQualifiedFormat))); } } finally { rootOperationsNeedingAnalysis.Free(compilationAnalysisContext.CancellationToken); allResults?.Free(compilationAnalysisContext.CancellationToken); } }); }); } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework.Graphics; namespace FlatRedBall.ManagedSpriteGroups { public class TextureGrid<T> { #region Fields internal List<List<T>> mTextures; internal T mBaseTexture; List<float> mFirstPaintedX = new List<float>(); List<float> mLastPaintedX = new List<float>(); float mFirstPaintedY; float mLastPaintedY; internal float mXOffset; internal float mYOffset; float mGridSpacingX; float mGridSpacingY; float mSpaceHalfX; float mSpaceHalfY; float mSpaceFourthX; float mSpaceFourthY; #endregion #region Properties public T BaseTexture { get { return mBaseTexture; } set { mBaseTexture = value; } } public float GridSpacingX { get { return mGridSpacingX; } set { mGridSpacingX = value; mSpaceFourthX = mGridSpacingX / 4.0f; mSpaceHalfX = mGridSpacingX / 2.0f; } } public float GridSpacingY { get { return mGridSpacingY; } set { mGridSpacingY = value; mSpaceFourthY = mGridSpacingY / 4.0f; mSpaceHalfY = mGridSpacingY / 2.0f; } } public List<T> this[int i] { get { return mTextures[i]; } } public List<float> FirstPaintedX { get { return mFirstPaintedX; } set { mFirstPaintedX = value; } } public List<float> LastPaintedX { get { return mLastPaintedX; } set { mLastPaintedX = value; } } public float FirstPaintedY { get { return mFirstPaintedY; } set { mFirstPaintedY = value; } } public float LastPaintedY { get { return mLastPaintedY; } set { mLastPaintedY = value; } } public List<List<T>> Textures { get { return mTextures; } set { mTextures = value; } } #endregion #region Methods #region Constructor public TextureGrid() { mTextures = new List<List<T>>(); mFirstPaintedX = new List<float>(); mLastPaintedX = new List<float>(); } #endregion public void Initialize(T baseTexture, float xOffset, float yOffset, float gridSpacingX, float gridSpacingY) { this.mBaseTexture = baseTexture; mXOffset = xOffset; mYOffset = yOffset; mGridSpacingX = gridSpacingX; mGridSpacingY = gridSpacingY; this.mFirstPaintedY = float.NaN; this.mLastPaintedY = float.NaN; } public void InvertZ() { // Actually, Y is Z when the SpriteGrid that uses this goes into the Z plane mFirstPaintedY = -mFirstPaintedY; mLastPaintedY = -mLastPaintedY; } public void Clear() { mFirstPaintedX.Clear(); mLastPaintedX.Clear(); mFirstPaintedY = float.NaN; mLastPaintedY = float.NaN; mTextures.Clear(); } #region XML Docs /// <summary> /// Shifts the position of all textures in the TextureGrid. /// </summary> /// <param name="x">The distance along the x axis to shift the grid.</param> /// <param name="y">The distance along the y axis to shift the grid.</param> #endregion public void ChangeGrid(float x, float y) { mFirstPaintedY += y; mLastPaintedY += y; for (int i = 0; i < mFirstPaintedX.Count; i++) { if (float.IsNaN(this.mFirstPaintedX[i]) == false) { mFirstPaintedX[i] += x; mLastPaintedX[i] += x; } } mXOffset += x; mYOffset += y; } public TextureGrid<T> Clone() { TextureGrid<T> gridToReturn = (TextureGrid<T>)(MemberwiseClone()); gridToReturn.mTextures = new List<List<T>>(); foreach (List<T> array in mTextures) { List<T> ta = new List<T>(); gridToReturn.mTextures.Add(ta); foreach (T texture in array) ta.Add(texture); } gridToReturn.mFirstPaintedX = new List<float>(); foreach (float f in mFirstPaintedX) gridToReturn.mFirstPaintedX.Add(f); gridToReturn.mLastPaintedX = new List<float>(); foreach (float f in mLastPaintedX) gridToReturn.mLastPaintedX.Add(f); return gridToReturn; } public T GetTextureAt(double x, double y) { if (mTextures.Count == 0) return mBaseTexture; //#if FRB_MDX if (y - mSpaceHalfY < mLastPaintedY && y + mSpaceHalfY > mFirstPaintedY) { int yOn = (int)System.Math.Round((y - mFirstPaintedY) / mGridSpacingY); if (mFirstPaintedX.Count > 0 && x > mFirstPaintedX[yOn] - mSpaceHalfX && x <= mLastPaintedX[yOn] + mSpaceHalfX) { int xOn = (int)System.Math.Round((x - mFirstPaintedX[yOn]) / mGridSpacingX); if(xOn > mTextures[yOn].Count - 1) return mTextures[yOn][mTextures[yOn].Count - 1]; else return mTextures[yOn][xOn]; } } //#elif FRB_XNA // if (y + mSpaceHalfY > mLastPaintedY && y - mSpaceHalfY < mFirstPaintedY) // { // int yOn = -(int)System.Math.Round((y - mFirstPaintedY) / mGridSpacingY); // if (mFirstPaintedX.Count > 0 && // x > mFirstPaintedX[yOn] - mSpaceHalfX && x <= mLastPaintedX[yOn] + mSpaceHalfX) // { // return mTextures[yOn][(int)System.Math.Round((x - mFirstPaintedX[yOn]) / mGridSpacingX)]; // } // } //#endif return mBaseTexture; } public List<TextureLocation<T>> GetTextureLocationDifferences(TextureGrid<T> originalGrid) { List<TextureLocation<T>> textureLocationArray = new List<TextureLocation<T>>(); // These are empty grids, so there's no changes. if (this.FirstPaintedX.Count == 0 && originalGrid.FirstPaintedX.Count == 0) { return textureLocationArray; } int thisYOn = 0; int originalYOn = 0; #region Get minY which is the smallest painted Y float minY = (float)System.Math.Min(mFirstPaintedY, originalGrid.mFirstPaintedY); if (originalGrid.mTextures.Count == 0) { minY = mFirstPaintedY; } else if (this.mTextures.Count == 0) { minY = originalGrid.mFirstPaintedY; } if (float.IsNaN(originalGrid.mFirstPaintedY)) minY = mFirstPaintedY; #endregion #region Get maxY which is the largest painted Y float maxY = (float)System.Math.Max(mLastPaintedY, originalGrid.mLastPaintedY); if (originalGrid.mTextures.Count == 0) { maxY = mLastPaintedY; } else if (this.mTextures.Count == 0) { maxY = originalGrid.mLastPaintedY; } if (float.IsNaN(originalGrid.mLastPaintedY)) maxY = mLastPaintedY; #endregion if (originalGrid.mTextures.Count == 0) { originalYOn = 0; thisYOn = 0; } else if (originalGrid.mFirstPaintedY - mFirstPaintedY > mSpaceHalfY) { thisYOn = 0; originalYOn = (int)System.Math.Round((mFirstPaintedY - originalGrid.mFirstPaintedY) / mGridSpacingY); } else if (mFirstPaintedY - originalGrid.mFirstPaintedY > mSpaceHalfY) {// if the this instance begins below originalGrid originalYOn = 0; thisYOn = (int)System.Math.Round((mFirstPaintedY - originalGrid.mFirstPaintedY) / mGridSpacingY); } // float minX = 0; float maxX = 0; T originalTexture = default(T); for (float y = minY; y - mSpaceFourthY < maxY; y += mGridSpacingY) { if (originalGrid.mTextures.Count == 0 || originalYOn < 0) {// if the this instance begins below originalGrid for (float x = this.mFirstPaintedX[thisYOn]; x - mSpaceFourthX < this.mLastPaintedX[thisYOn]; x += mGridSpacingX) { textureLocationArray.Add(new TextureLocation<T>(originalGrid.mBaseTexture, x, y)); } } else if (thisYOn < 0) {// the original grid is below this grid for (float x = originalGrid.mFirstPaintedX[originalYOn]; x - mSpaceFourthX < originalGrid.mLastPaintedX[originalYOn]; x += mGridSpacingX) { textureLocationArray.Add(new TextureLocation<T>(this.mBaseTexture, x, y)); } } else {// y is above the bottom border of both grids if (thisYOn > this.mTextures.Count - 1) { // y is above the this instance top for (float x = originalGrid.mFirstPaintedX[originalYOn]; x - mSpaceFourthX < originalGrid.mLastPaintedX[originalYOn]; x += mGridSpacingX) { textureLocationArray.Add(new TextureLocation<T>(this.mBaseTexture, x, y)); } } else if (originalYOn > originalGrid.mTextures.Count - 1) { // Y is above the originalGrid's top for (float x = this.mFirstPaintedX[thisYOn]; x - mSpaceFourthX < this.mLastPaintedX[thisYOn]; x += mGridSpacingX) { textureLocationArray.Add(new TextureLocation<T>(originalGrid.mBaseTexture, x, y)); } } else { // y is between the top and bottom of both grids maxX = System.Math.Max(this.mLastPaintedX[thisYOn], originalGrid.mLastPaintedX[originalYOn]); for (float x = System.Math.Min(this.mFirstPaintedX[thisYOn], originalGrid.mFirstPaintedX[originalYOn]); x - mSpaceFourthX < maxX; x += mGridSpacingX) { originalTexture = originalGrid.GetTextureAt(x, y); T newTexture = this.GetTextureAt(x, y); bool areBothNull = newTexture == null && originalTexture == null; if (!areBothNull) { if ((originalTexture == null && newTexture != null) || originalTexture.Equals(this.GetTextureAt(x, y)) == false) textureLocationArray.Add(new TextureLocation<T>(originalTexture, x, y)); } } } } // moving up one row, so increment the y value originalYOn++; thisYOn++; } return textureLocationArray; } public List<T> GetUsedTextures() { List<T> arrayToReturn = new List<T>(); if (mBaseTexture != null) { arrayToReturn.Add(mBaseTexture); } foreach (List<T> ta in mTextures) { foreach (T tex in ta) { if (tex != null && !arrayToReturn.Contains(tex)) arrayToReturn.Add(tex); } } return arrayToReturn; } public bool IsTextureReferenced(T texture) { if (mBaseTexture.Equals(texture)) return true; foreach (List<T> fta in mTextures) { if (fta.Contains(texture)) return true; } return false; } public void PaintGridAtPosition(float x, float y, T textureToPaint) { T textureAtXY = this.GetTextureAt(x, y); if ( (textureAtXY == null && textureToPaint == null) || (textureToPaint != null && textureToPaint.Equals(textureAtXY))) return; #region locate the center position of this texture. // float x = XOffset + (int)(System.Math.Round( (xFloat)/mGridSpacing)) * mGridSpacing; // float y = YOffset + (int)(System.Math.Round( (yFloat)/mGridSpacing)) * mGridSpacing; #endregion #region this is the first texture we are painting if (mTextures.Count == 0) { // this is the first texture, so we mark it mFirstPaintedX.Add(x); mFirstPaintedY = y; mLastPaintedX.Add(x); mLastPaintedY = y; mTextures.Add(new List<T>()); mTextures[0].Add(textureToPaint); } #endregion else { int yOn = (int)(System.Math.Round((y - mFirstPaintedY) / mGridSpacingY)); #region If the position we are painting is higher than all others, Add to the ArrayLists so they include this high if (yOn > mFirstPaintedX.Count - 1) { while (yOn > mFirstPaintedX.Count - 1) { mFirstPaintedX.Add(float.NaN); mLastPaintedX.Add(float.NaN); mTextures.Add(new List<T>()); mLastPaintedY += mGridSpacingY; } } #endregion #region if the position we are painting is lower than all others, insert on the ArrayLists so they include this low else if (yOn < 0) { while (yOn < 0) { mFirstPaintedX.Insert(0, float.NaN); mLastPaintedX.Insert(0, float.NaN); mFirstPaintedY -= mGridSpacingY; mTextures.Insert(0, new List<T>()); yOn++; } } #endregion #region the position is on an already-existing row else { int xOn = (int)System.Math.Round((x - mFirstPaintedX[yOn]) / mGridSpacingX); if (float.IsNaN(mFirstPaintedX[yOn])) { // first texture mFirstPaintedX[yOn] = x; mLastPaintedX[yOn] = x; mTextures[yOn].Add(textureToPaint); } #region this is the furthest right on this row else if (xOn > mTextures[yOn].Count - 1) { while (xOn > mTextures[yOn].Count - 1) { mLastPaintedX[yOn] += mGridSpacingX; mTextures[yOn].Add(mBaseTexture); } mTextures[yOn][xOn] = textureToPaint; } #endregion #region this is the furthest left on this row else if (xOn < 0) { while (xOn < 0) { mFirstPaintedX[yOn] -= mGridSpacingX; mTextures[yOn].Insert(0, mBaseTexture); xOn++; } mTextures[yOn][0] = textureToPaint; } #endregion else { // reduce the textures 2D array here if painting the base texture mTextures[yOn][xOn] = textureToPaint; if ( (textureToPaint == null && mBaseTexture == null) || (textureToPaint != null && textureToPaint.Equals(mBaseTexture))) { this.ReduceGridAtIndex(yOn, xOn); } } } #endregion /* Since we may have painted the baseTexture, the grid may have contracted. If that's the case * we need to make sure that it's not completely contracted so that firstPainted.Count == 0 */ if (mFirstPaintedX.Count != 0 && yOn < mFirstPaintedX.Count && float.IsNaN(mFirstPaintedX[yOn])) { // first texture mFirstPaintedX[yOn] = x; mLastPaintedX[yOn] = x; mTextures[yOn].Add(textureToPaint); } } } #region XML Docs /// <summary> /// This "shrinks" the grid if its edges are the same as its baseTexture /// </summary> /// <remarks> /// To use the least amount of memory, TextureGrids only store non-baseTexture strips. /// If the ends of a horizontal strip are the baseTexture, then the strip should be contracted /// inward. If an entire horizontal strip is the baseTexture, then it should be removed. /// /// Usually, tests should begin from a specific location, as it is usually called after the /// grid is painted. This method will first check to see if the arguments are on the left or /// right side of a strip. Then a loop will move inward as long as it continues to encounter /// the base texture. Once it encounters a non-baseTexture, then it stops, and reduces the /// particular horizontal strip. /// /// If an entire strip is cleared and it is either the top or bottom strip, then it will /// be removed, and the strip above or below (depending on position) will be tested as well. /// If the strip is in the center (not the top or bottom), then it will be reduced, but cannot /// be removed. /// </remarks> /// <param name="yFloat">The y location in absolute coordinates to start the tests at.</param> /// <param name="xFloat">The x location in absolute coordinates to start the tests at.</param> #endregion public void ReduceGrid(float yFloat, float xFloat) { // float x = XOffset + (int)(System.Math.Round( (xFloat)/mGridSpacing)) * mGridSpacing; // float y = YOffset + (int)(System.Math.Round( (yFloat)/mGridSpacing)) * mGridSpacing; float x = (int)(System.Math.Round((xFloat) / mGridSpacingX)) * mGridSpacingX; float y = (int)(System.Math.Round((yFloat) / mGridSpacingY)) * mGridSpacingY; int yOn = (int)(System.Math.Round((y - mFirstPaintedY) / mGridSpacingY)); int xOn = (int)System.Math.Round((x - mFirstPaintedX[yOn]) / mGridSpacingX); ReduceGridAtIndex(yOn, xOn); } #region XML Docs /// <summary> /// This "shrinks" the grid if its edges are the same as its baseTexture /// </summary> /// <remarks> /// To use the least amount of memory, TextureGrids only store non-baseTexture strips. /// If the ends of a horizontal strip are the baseTexture, then the strip should be contracted /// inward. If an entire horizontal strip is the baseTexture, then it should be removed. /// /// Usually, tests should begin from a specific location, as it is usually called after the /// grid is painted. This method will first check to see if the arguments are on the left or /// right side of a strip. Then a loop will move inward as long as it continues to encounter /// the base texture. Once it encounters a non-baseTexture, then it stops, and reduces the /// particular horizontal strip. /// /// If an entire strip is cleared and it is either the top or bottom strip, then it will /// be removed, and the strip above or below (depending on position) will be tested as well. /// If the strip is in the center (not the top or bottom), then it will be reduced, but cannot /// be removed. /// </remarks> /// <param name="yOn">The y index start the tests at.</param> /// <param name="xOn">The x index to start the tests at.</param> #endregion public void ReduceGridAtIndex(int yOn, int xOn) { if (mTextures.Count == 0) return; // on the left side of the row #region move right along the row, remove textures and changing firstPaintedX[yOn] if (xOn == 0) { while (mTextures[yOn].Count > 0) { T objectAt = this.mTextures[yOn][0]; if ((objectAt == null && mBaseTexture == null) || (objectAt != null && objectAt.Equals(mBaseTexture))) { mTextures[yOn].RemoveAt(0); mFirstPaintedX[yOn] += this.mGridSpacingX; } else break; } } #endregion // on the right side of the row #region move left along the row, remove textures and changing lastPaintedX[yOn] else if (xOn == mTextures[yOn].Count - 1) { while (mTextures[yOn].Count > 0) { T objectAt = mTextures[yOn][mTextures[yOn].Count - 1]; if ((objectAt == null && mBaseTexture == null) || (objectAt != null && objectAt.Equals(mBaseTexture))) { mTextures[yOn].RemoveAt(mTextures[yOn].Count - 1); mLastPaintedX[yOn] -= this.mGridSpacingX; } else break; } } #endregion #region if we removed the entire row, and it is the top or bottom if (mTextures[yOn].Count == 0 && (yOn == mFirstPaintedX.Count - 1 || yOn == 0)) { mTextures.RemoveAt(yOn); mFirstPaintedX.RemoveAt(yOn); mLastPaintedX.RemoveAt(yOn); if (yOn == 0 && mTextures.Count != 0) { mFirstPaintedY += mGridSpacingY; ReduceGridAtIndex(0, 0); } else { mLastPaintedY -= mGridSpacingY; ReduceGridAtIndex(yOn - 1, 0); } } #endregion } public void ReplaceTexture(T oldTexture, T newTexture) { if ((mBaseTexture == null && oldTexture == null) || (mBaseTexture != null && mBaseTexture.Equals(oldTexture))) { mBaseTexture = newTexture; } for (int k = 0; k < mTextures.Count; k++) { List<T> fta = mTextures[k]; for (int i = 0; i < fta.Count; i++) { if ((fta[i] == null && oldTexture == null ) || (fta[i] != null && fta[i].Equals(oldTexture))) fta[i] = newTexture; } } TrimGrid(); } /* public void ReplaceTexture(string oldTexture, string newTexture) { if (mBaseTexture.fileName == oldTexture) { mBaseTexture = spriteManager.AddTexture(newTexture); } foreach (List<Texture2D> fta in mTextures) { for (int i = 0; i < fta.Count; i++) { if (fta[i].fileName == oldTexture) fta[i] = spriteManager.AddTexture(newTexture); } } TrimGrid(); } */ public void ScaleBy(double scaleValue) { GridSpacingX = (float)(mGridSpacingX * scaleValue); GridSpacingY = (float)(mGridSpacingY * scaleValue); mFirstPaintedY = (float)(mFirstPaintedY * scaleValue); mLastPaintedY = (float)(mLastPaintedY * scaleValue); mXOffset = (float)(mXOffset * scaleValue); mYOffset = (float)(mYOffset * scaleValue); for (int i = 0; i < mFirstPaintedX.Count; i++) { mFirstPaintedX[i] = (float)(mFirstPaintedX[i] * scaleValue); mLastPaintedX[i] = (float)(mLastPaintedX[i] * scaleValue); } } public void SetFrom(TextureGrid<T> instanceToSetFrom) { mBaseTexture = instanceToSetFrom.mBaseTexture; mTextures = new List<List<T>>(); for (int i = 0; i < instanceToSetFrom.mTextures.Count; i++ ) { mTextures.Add(new List<T>(instanceToSetFrom.mTextures[i])); } mFirstPaintedX = new List<float>(instanceToSetFrom.mFirstPaintedX); mLastPaintedX = new List<float>(instanceToSetFrom.mLastPaintedX); mFirstPaintedY = instanceToSetFrom.mFirstPaintedY; mLastPaintedY = instanceToSetFrom.mLastPaintedY; mXOffset = instanceToSetFrom.mXOffset; mYOffset = instanceToSetFrom.mYOffset; mGridSpacingX = instanceToSetFrom.mGridSpacingX; mGridSpacingY = instanceToSetFrom.mGridSpacingY; mSpaceHalfX = instanceToSetFrom.mSpaceHalfX; mSpaceHalfY = instanceToSetFrom.mSpaceHalfY; mSpaceFourthX = instanceToSetFrom.mSpaceFourthX; mSpaceFourthY = instanceToSetFrom.mSpaceFourthY; } #region XML Docs /// <summary> /// Checks the boundaries of the grid and removes any references to textures that match the base Texture2D. /// </summary> /// <remarks> /// This method is called automatically by the ReplaceTexture method so that the structure /// stays as small as possible afterchanges have been made. /// </remarks> #endregion public void TrimGrid() { TrimGrid(float.NegativeInfinity, float.PositiveInfinity); } public void TrimGrid(float minimumX, float maximumX) { // begin at the top of the grid and move down for (int yOn = mTextures.Count - 1; yOn > -1; yOn--) { /* The ReduceGridAtIndex will not only reduce off of the left and right side, but * it will remove entire rows. If a row is removed, the method will recur and move * down one row. It will continue doing so until it no longer removes an enire row or until * all rows have been remvoed. * * Because of this, it is possible that more than one row will be removed during the method call. * Therefore, there needs to be an if statement making sure that row[yOn] exists */ while (yOn < mTextures.Count && mTextures[yOn].Count > 0 && mFirstPaintedX[yOn] < minimumX) { mTextures[yOn].RemoveAt(0); mFirstPaintedX[yOn] += this.mGridSpacingX; } while (yOn < mTextures.Count && mTextures[yOn].Count > 0 && mLastPaintedX[yOn] > maximumX) { mTextures[yOn].RemoveAt(mTextures[yOn].Count - 1); mLastPaintedX[yOn] -= this.mGridSpacingX; } if (yOn < mTextures.Count && mTextures.Count > 0) { ReduceGridAtIndex(yOn, 0); } if (yOn < mTextures.Count && mTextures.Count > 0 && mTextures[yOn].Count > 0) ReduceGridAtIndex(yOn, mTextures[yOn].Count - 1); } } public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append("BaseTexture:").Append(mBaseTexture.ToString()); sb.Append("\nNumTextureRows:").Append(mTextures.Count); sb.Append("\nfirstPaintedY:").Append(mFirstPaintedY); sb.Append("\nlastPaintedY:").Append(mLastPaintedY).Append("\n"); return sb.ToString(); //return base.ToString(); } #endregion internal void ChopOffBottom() { mTextures.RemoveAt(0); mFirstPaintedX.RemoveAt(0); mLastPaintedX.RemoveAt(0); mFirstPaintedY += mGridSpacingY; } internal void ChopOffTop() { int lastIndex = mTextures.Count - 1; mTextures.RemoveAt(lastIndex); mFirstPaintedX.RemoveAt(lastIndex); mLastPaintedX.RemoveAt(lastIndex); mLastPaintedY -= mGridSpacingY; } } }
namespace XenAdmin.TabPages { partial class AlertSummaryPage { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing) { DeregisterEventHandlers(); DeregisterCheckForUpdatesEvents(); 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.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AlertSummaryPage)); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle7 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle6 = new System.Windows.Forms.DataGridViewCellStyle(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.LabelCappingEntries = new System.Windows.Forms.Label(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.toolStrip1 = new XenAdmin.Controls.ToolStripEx(); this.toolStripDropDownSeveritiesFilter = new XenAdmin.Controls.FilterSeveritiesToolStripDropDownButton(); this.toolStripDropDownButtonServerFilter = new XenAdmin.Controls.FilterLocationToolStripDropDownButton(); this.toolStripDropDownButtonDateFilter = new XenAdmin.Controls.FilterDatesToolStripDropDownButton(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButtonRefresh = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButtonExportAll = new System.Windows.Forms.ToolStripButton(); this.toolStripSplitButtonDismiss = new System.Windows.Forms.ToolStripSplitButton(); this.tsmiDismissAll = new System.Windows.Forms.ToolStripMenuItem(); this.tsmiDismissSelected = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripLabelFiltersOnOff = new System.Windows.Forms.ToolStripLabel(); this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); this.GridViewAlerts = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx(); this.ColumnExpand = new System.Windows.Forms.DataGridViewImageColumn(); this.ColumnSeverity = new System.Windows.Forms.DataGridViewImageColumn(); this.ColumnMessage = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnLocation = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnDate = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnActions = new System.Windows.Forms.DataGridViewTextBoxColumn(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.tableLayoutPanel1.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.tableLayoutPanel3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.GridViewAlerts)).BeginInit(); this.SuspendLayout(); // // pictureBox1 // resources.ApplyResources(this.pictureBox1, "pictureBox1"); this.pictureBox1.Image = global::XenAdmin.Properties.Resources._000_Info3_h32bit_16; this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.TabStop = false; // // LabelCappingEntries // resources.ApplyResources(this.LabelCappingEntries, "LabelCappingEntries"); this.LabelCappingEntries.ForeColor = System.Drawing.SystemColors.ControlText; this.LabelCappingEntries.Name = "LabelCappingEntries"; // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.BackColor = System.Drawing.Color.Gainsboro; this.tableLayoutPanel1.Controls.Add(this.toolStrip1, 0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // toolStrip1 // resources.ApplyResources(this.toolStrip1, "toolStrip1"); this.toolStrip1.BackColor = System.Drawing.Color.WhiteSmoke; this.toolStrip1.ClickThrough = true; this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripDropDownSeveritiesFilter, this.toolStripDropDownButtonServerFilter, this.toolStripDropDownButtonDateFilter, this.toolStripSeparator3, this.toolStripButtonRefresh, this.toolStripSeparator1, this.toolStripButtonExportAll, this.toolStripSplitButtonDismiss, this.toolStripLabelFiltersOnOff}); this.toolStrip1.Name = "toolStrip1"; // // toolStripDropDownSeveritiesFilter // this.toolStripDropDownSeveritiesFilter.AutoToolTip = false; resources.ApplyResources(this.toolStripDropDownSeveritiesFilter, "toolStripDropDownSeveritiesFilter"); this.toolStripDropDownSeveritiesFilter.Name = "toolStripDropDownSeveritiesFilter"; this.toolStripDropDownSeveritiesFilter.FilterChanged += new System.Action(this.toolStripDropDownSeveritiesFilter_FilterChanged); // // toolStripDropDownButtonServerFilter // this.toolStripDropDownButtonServerFilter.AutoToolTip = false; resources.ApplyResources(this.toolStripDropDownButtonServerFilter, "toolStripDropDownButtonServerFilter"); this.toolStripDropDownButtonServerFilter.Margin = new System.Windows.Forms.Padding(2, 1, 0, 2); this.toolStripDropDownButtonServerFilter.Name = "toolStripDropDownButtonServerFilter"; this.toolStripDropDownButtonServerFilter.FilterChanged += new System.Action(this.toolStripDropDownButtonServerFilter_FilterChanged); // // toolStripDropDownButtonDateFilter // this.toolStripDropDownButtonDateFilter.AutoToolTip = false; this.toolStripDropDownButtonDateFilter.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; resources.ApplyResources(this.toolStripDropDownButtonDateFilter, "toolStripDropDownButtonDateFilter"); this.toolStripDropDownButtonDateFilter.Name = "toolStripDropDownButtonDateFilter"; this.toolStripDropDownButtonDateFilter.FilterChanged += new System.Action(this.toolStripDropDownButtonDateFilter_FilterChanged); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3"); // // toolStripButtonRefresh // this.toolStripButtonRefresh.AutoToolTip = false; resources.ApplyResources(this.toolStripButtonRefresh, "toolStripButtonRefresh"); this.toolStripButtonRefresh.Name = "toolStripButtonRefresh"; this.toolStripButtonRefresh.Click += new System.EventHandler(this.toolStripButtonRefresh_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1"); // // toolStripButtonExportAll // this.toolStripButtonExportAll.AutoToolTip = false; resources.ApplyResources(this.toolStripButtonExportAll, "toolStripButtonExportAll"); this.toolStripButtonExportAll.Name = "toolStripButtonExportAll"; this.toolStripButtonExportAll.Click += new System.EventHandler(this.toolStripButtonExportAll_Click); // // toolStripSplitButtonDismiss // this.toolStripSplitButtonDismiss.AutoToolTip = false; this.toolStripSplitButtonDismiss.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripSplitButtonDismiss.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tsmiDismissAll, this.tsmiDismissSelected}); resources.ApplyResources(this.toolStripSplitButtonDismiss, "toolStripSplitButtonDismiss"); this.toolStripSplitButtonDismiss.Name = "toolStripSplitButtonDismiss"; this.toolStripSplitButtonDismiss.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.toolStripSplitButtonDismiss_DropDownItemClicked); // // tsmiDismissAll // this.tsmiDismissAll.Name = "tsmiDismissAll"; resources.ApplyResources(this.tsmiDismissAll, "tsmiDismissAll"); this.tsmiDismissAll.Click += new System.EventHandler(this.tsmiDismissAll_Click); // // tsmiDismissSelected // this.tsmiDismissSelected.Name = "tsmiDismissSelected"; resources.ApplyResources(this.tsmiDismissSelected, "tsmiDismissSelected"); this.tsmiDismissSelected.Click += new System.EventHandler(this.tsmiDismissSelected_Click); // // toolStripLabelFiltersOnOff // this.toolStripLabelFiltersOnOff.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; resources.ApplyResources(this.toolStripLabelFiltersOnOff, "toolStripLabelFiltersOnOff"); this.toolStripLabelFiltersOnOff.Name = "toolStripLabelFiltersOnOff"; // // tableLayoutPanel3 // resources.ApplyResources(this.tableLayoutPanel3, "tableLayoutPanel3"); this.tableLayoutPanel3.Controls.Add(this.pictureBox1, 0, 0); this.tableLayoutPanel3.Controls.Add(this.LabelCappingEntries, 1, 0); this.tableLayoutPanel3.Name = "tableLayoutPanel3"; // // GridViewAlerts // dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Window; this.GridViewAlerts.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1; resources.ApplyResources(this.GridViewAlerts, "GridViewAlerts"); this.GridViewAlerts.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells; this.GridViewAlerts.BackgroundColor = System.Drawing.SystemColors.Window; this.GridViewAlerts.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.GridViewAlerts.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.GridViewAlerts.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.ColumnExpand, this.ColumnSeverity, this.ColumnMessage, this.ColumnLocation, this.ColumnDate, this.ColumnActions}); dataGridViewCellStyle7.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft; dataGridViewCellStyle7.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle7.Font = new System.Drawing.Font("Segoe UI", 9F); dataGridViewCellStyle7.ForeColor = System.Drawing.SystemColors.ControlText; dataGridViewCellStyle7.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle7.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle7.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.GridViewAlerts.DefaultCellStyle = dataGridViewCellStyle7; this.GridViewAlerts.GridColor = System.Drawing.SystemColors.ControlDark; this.GridViewAlerts.MultiSelect = true; this.GridViewAlerts.Name = "GridViewAlerts"; this.GridViewAlerts.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.GridViewAlerts_CellClick); this.GridViewAlerts.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.GridViewAlerts_CellDoubleClick); this.GridViewAlerts.ColumnHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.GridViewAlerts_ColumnHeaderMouseClick); this.GridViewAlerts.SelectionChanged += new System.EventHandler(this.GridViewAlerts_SelectionChanged); this.GridViewAlerts.SortCompare += new System.Windows.Forms.DataGridViewSortCompareEventHandler(this.GridViewAlerts_SortCompare); this.GridViewAlerts.KeyDown += new System.Windows.Forms.KeyEventHandler(this.GridViewAlerts_KeyDown); // // ColumnExpand // this.ColumnExpand.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopCenter; dataGridViewCellStyle2.NullValue = null; dataGridViewCellStyle2.Padding = new System.Windows.Forms.Padding(0, 5, 0, 0); this.ColumnExpand.DefaultCellStyle = dataGridViewCellStyle2; resources.ApplyResources(this.ColumnExpand, "ColumnExpand"); this.ColumnExpand.Name = "ColumnExpand"; this.ColumnExpand.ReadOnly = true; this.ColumnExpand.Resizable = System.Windows.Forms.DataGridViewTriState.False; // // ColumnSeverity // this.ColumnSeverity.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopCenter; dataGridViewCellStyle3.NullValue = null; dataGridViewCellStyle3.Padding = new System.Windows.Forms.Padding(0, 2, 0, 0); this.ColumnSeverity.DefaultCellStyle = dataGridViewCellStyle3; resources.ApplyResources(this.ColumnSeverity, "ColumnSeverity"); this.ColumnSeverity.Name = "ColumnSeverity"; this.ColumnSeverity.ReadOnly = true; this.ColumnSeverity.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.ColumnSeverity.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic; // // ColumnMessage // dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft; dataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.ColumnMessage.DefaultCellStyle = dataGridViewCellStyle4; this.ColumnMessage.FillWeight = 200F; resources.ApplyResources(this.ColumnMessage, "ColumnMessage"); this.ColumnMessage.Name = "ColumnMessage"; this.ColumnMessage.ReadOnly = true; // // ColumnLocation // dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft; this.ColumnLocation.DefaultCellStyle = dataGridViewCellStyle5; resources.ApplyResources(this.ColumnLocation, "ColumnLocation"); this.ColumnLocation.Name = "ColumnLocation"; this.ColumnLocation.ReadOnly = true; // // ColumnDate // dataGridViewCellStyle6.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft; this.ColumnDate.DefaultCellStyle = dataGridViewCellStyle6; resources.ApplyResources(this.ColumnDate, "ColumnDate"); this.ColumnDate.Name = "ColumnDate"; this.ColumnDate.ReadOnly = true; this.ColumnDate.Resizable = System.Windows.Forms.DataGridViewTriState.True; // // ColumnActions // this.ColumnActions.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.ColumnActions, "ColumnActions"); this.ColumnActions.Name = "ColumnActions"; this.ColumnActions.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.ColumnActions.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; // // AlertSummaryPage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.SystemColors.Window; this.Controls.Add(this.GridViewAlerts); this.Controls.Add(this.tableLayoutPanel1); this.Controls.Add(this.tableLayoutPanel3); this.Name = "AlertSummaryPage"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.tableLayoutPanel1.ResumeLayout(false); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.tableLayoutPanel3.ResumeLayout(false); this.tableLayoutPanel3.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.GridViewAlerts)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox pictureBox1; private XenAdmin.Controls.DataGridViewEx.DataGridViewEx GridViewAlerts; private System.Windows.Forms.Label LabelCappingEntries; private XenAdmin.Controls.ToolStripEx toolStrip1; private XenAdmin.Controls.FilterDatesToolStripDropDownButton toolStripDropDownButtonDateFilter; private System.Windows.Forms.ToolStripButton toolStripButtonExportAll; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private XenAdmin.Controls.FilterLocationToolStripDropDownButton toolStripDropDownButtonServerFilter; private System.Windows.Forms.ToolStripButton toolStripButtonRefresh; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private XenAdmin.Controls.FilterSeveritiesToolStripDropDownButton toolStripDropDownSeveritiesFilter; private System.Windows.Forms.ToolStripLabel toolStripLabelFiltersOnOff; private System.Windows.Forms.ToolStripSplitButton toolStripSplitButtonDismiss; private System.Windows.Forms.ToolStripMenuItem tsmiDismissAll; private System.Windows.Forms.ToolStripMenuItem tsmiDismissSelected; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; private System.Windows.Forms.DataGridViewImageColumn ColumnExpand; private System.Windows.Forms.DataGridViewImageColumn ColumnSeverity; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnMessage; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnLocation; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDate; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnActions; } }
using System; using Microsoft.SPOT.Hardware; using System.Threading; using Microsoft.SPOT; namespace BeranekCZ.NETMF.Displays { //SSD1306 driver public class SSD1306 { private readonly int _width; private readonly int _height; private readonly int _pages; private byte[] buffer; private int _timeout = 200; private bool _externalVcc = false; private I2CDevice _device; public int Width { get { return _width; } } public int Height { get { return _height; } } public SSD1306(I2CDevice device,int width = 128,int height = 64) { this._device = device; this._width = width; this._height = height; this._pages = _height / 8; buffer = new byte[width * _pages]; } public void Clear() { for (int i = 0; i < buffer.Length; i++) { buffer[i] = 0; } } private void send(byte data) { this._device.Execute( new I2CDevice.I2CTransaction[] { I2CDevice.CreateWriteTransaction(new byte[] { data }) }, _timeout ); } private void send(byte[] data) { this._device.Execute( new I2CDevice.I2CTransaction[] { I2CDevice.CreateWriteTransaction(data) }, _timeout ); } private void sendCommand(byte cmd) { // Co = 0, D/C = 0 send(new byte[] { 0x00, cmd }); } private void sendData(byte data) { // Co = 0, D/C = 1 send(new byte[] { 0x40, data }); } public void Init() { // Init sequence for 128x64 OLED module sendCommand(0xae); // 0xAE display off sendCommand(0xD5); // 0xD5 set display clock div. sendCommand(0x80); // the suggested ratio 0x80 sendCommand(0xA8); // 0xA8 set multiplex sendCommand(0x3F); sendCommand(0xD3); // 0xD3 set display offset sendCommand(0x0); // no offset sendCommand(0x40 | 0x0); // line #0 set display start line sendCommand(0x8D); // 0x8D charge pump if (_externalVcc) { sendCommand(0x10); } //disable charge pump else { sendCommand(0x14); } //enable charge pump sendCommand(0x20); // 0x20 set memory address mode sendCommand(0x00); // 0x0 horizontal addressing mode sendCommand(0xA0 | 0x1); // set segment re-map sendCommand(0xc8); // set com output scan direction sendCommand(0xDA); // 0xDA set COM pins HW configuration sendCommand(0x12); sendCommand(0x81); // 0x81 Set Contrast Control for BANK0 if (_externalVcc) { sendCommand(0x9F); } else { sendCommand(0xCF); } sendCommand(0xd9); // 0xd9 Set Pre-charge Period if (_externalVcc) { sendCommand(0x22); } else { sendCommand(0xF1); } sendCommand(0xDB); // 0xDB Set VCOMH Deselect Level sendCommand(0x40); // set display start line sendCommand(0xA4); // 0xA4 display ON sendCommand(0xA6); // 0xA6 set normal display sendCommand(0xAF); //--turn on oled panel //Thread.Sleep(100); } /// <summary> /// Send buffer to display /// </summary> public void Display() { //set column address sendCommand(0x21); sendCommand(0); sendCommand((byte)(_width - 1)); //set page address sendCommand(0x22); sendCommand(0); sendCommand((byte)(_pages - 1)); for (ushort i = 0; i < buffer.Length; i = (ushort)(i + 16)) { sendCommand(0x40); SendArray(buffer, i, (ushort)(i + 16)); } } /// <summary> /// Coordinates start with index 0 /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="colored">True = turn on pixel, false = turn off pixel</param> public void DrawPixel(int x, int y, bool colored) { DrawPixel((byte)x, (byte)y, colored); } /// <summary> /// Coordinates start with index 0 /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="colored">True = turn on pixel, false = turn off pixel</param> public void DrawPixel(byte x, byte y, bool colored) { if (x < 0 || x >= _width || y < 0 || y >= _height) { Debug.Print("DrawPixel error: Out of borders"); return; } int index = y / 8 * _width + x; if (colored) buffer[index] = (byte)(buffer[index] | (byte)(1 << (y % 8))); else buffer[index] = (byte)(buffer[index] & ~(byte)(1 << (y % 8))); } //public void DrawLine(int x0, int y0, int x1, int y1, bool colored = true) //{ // DrawLine(x0, y0, x1, y1, colored); //} public void DrawHLine(int x0, int y0, int w, bool colored = true) { DrawLine(x0, y0, x0 + w - 1, y0, colored); } public void DrawVLine(int x0, int y0, int h, bool colored = true) { DrawLine(x0, y0, x0, y0 + h - 1, colored); } /// <summary> /// Source http://ericw.ca/notes/bresenhams-line-algorithm-in-csharp.html /// </summary> /// <param name="x0"></param> /// <param name="y0"></param> /// <param name="x1"></param> /// <param name="y1"></param> /// <param name="colored"></param> public void DrawLine(int x0, int y0, int x1, int y1, bool colored = true) { bool steep = System.Math.Abs(y1 - y0) > System.Math.Abs(x1 - x0); if (steep) { int t; t = x0; // swap x0 and y0 x0 = y0; y0 = t; t = x1; // swap x1 and y1 x1 = y1; y1 = t; } if (x0 > x1) { int t; t = x0; // swap x0 and x1 x0 = x1; x1 = t; t = y0; // swap y0 and y1 y0 = y1; y1 = t; } int dx = x1 - x0; int dy = System.Math.Abs(y1 - y0); int error = dx / 2; int ystep = (y0 < y1) ? 1 : -1; int y = y0; for (int x = x0; x <= x1; x++) { DrawPixel((steep ? y : x), (steep ? x : y), colored); error = error - dy; if (error < 0) { y += ystep; error += dx; } } } public void DrawCircle(int centerX, int centerY, int radius, bool colored = true) { radius--; int d = (5 - radius * 4) / 4; int x = 0; int y = radius; do { DrawPixel(centerX + x, centerY + y, colored); DrawPixel(centerX + x, centerY - y, colored); DrawPixel(centerX - x, centerY + y, colored); DrawPixel(centerX - x, centerY - y, colored); DrawPixel(centerX + y, centerY + x, colored); DrawPixel(centerX + y, centerY - x, colored); DrawPixel(centerX - y, centerY + x, colored); DrawPixel(centerX - y, centerY - x, colored); if (d < 0) { d += 2 * x + 1; } else { d += 2 * (x - y) + 1; y--; } x++; } while (x <= y); } public void DrawFilledCircle(int centerX, int centerY, int radius, bool colored = true) { radius--; int d = (5 - radius * 4) / 4; int x = 0; int y = radius; do { DrawLine(centerX + x, centerY + y, centerX - x, centerY + y, colored); DrawLine(centerX + x, centerY - y, centerX - x, centerY - y, colored); DrawLine(centerX - y, centerY + x, centerX + y,centerY + x, colored); DrawLine(centerX - y, centerY - x, centerX + y, centerY - x, colored); if (d < 0) { d += 2 * x + 1; } else { d += 2 * (x - y) + 1; y--; } x++; } while (x <= y); } public void DrawRectangle(int xLeft, int yTop, int width, int height, bool colored = true) { width--; height--; DrawLine(xLeft, yTop, xLeft + width, yTop, colored); DrawLine(xLeft + width, yTop, xLeft + width, yTop + height, colored); DrawLine(xLeft + width, yTop + height, xLeft, yTop + height, colored); DrawLine(xLeft, yTop, xLeft, yTop + height, colored); } public void DrawFilledRectangle(int xLeft, int yTop, int width, int height, bool colored = true) { width--; height--; for (int i = 0; i <= height; i++) { DrawLine(xLeft, yTop + i, xLeft + width, yTop + i, colored); } } //Draw a rounded rectangle public void DrawRoundRect(int x, int y, int w, int h, int r, bool colored = true) { // smarter version DrawHLine(x + r, y, w - 2 * r, colored); // Top DrawHLine(x + r, y + h - 1, w - 2 * r, colored); // Bottom DrawVLine(x, y + r, h - 2 * r, colored); // Left DrawVLine(x + w - 1, y + r, h - 2 * r, colored); // Right // draw four corners drawCircleHelper(x + r, y + r, r, 1, colored); drawCircleHelper(x + w - r - 1, y + r, r, 2, colored); drawCircleHelper(x + w - r - 1, y + h - r - 1, r, 4, colored); drawCircleHelper(x + r, y + h - r - 1, r, 8, colored); } public void DrawRoundFilledRect(int x, int y, int w, int h, int r, bool colored = true) { // smarter version //fillRect(x+r, y, w-2*r, h, color); for (int i = x + r; i < x + r + (w - 2 * r); i++) { DrawVLine(i, y, h, colored); } // draw four corners fillCircleHelper(x + w - r - 1, y + r, r, 1, h - 2 * r - 1, colored); fillCircleHelper(x + r, y + r, r, 2, h - 2 * r - 1, colored); } private void drawCircleHelper(int x0, int y0, int r, int cornername, bool colored = true) { int f = 1 - r; int ddF_x = 1; int ddF_y = -2 * r; int x = 0; int y = r; while (x < y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if ((cornername & 0x4) != 0) { DrawPixel(x0 + x, y0 + y, colored); DrawPixel(x0 + y, y0 + x, colored); } if ((cornername & 0x2) != 0) { DrawPixel(x0 + x, y0 - y, colored); DrawPixel(x0 + y, y0 - x, colored); } if ((cornername & 0x8) != 0) { DrawPixel(x0 - y, y0 + x, colored); DrawPixel(x0 - x, y0 + y, colored); } if ((cornername & 0x1) != 0) { DrawPixel(x0 - y, y0 - x, colored); DrawPixel(x0 - x, y0 - y, colored); } } } private void fillCircleHelper(int x0, int y0, int r, int cornername, int delta, bool colored) { int f = 1 - r; int ddF_x = 1; int ddF_y = -2 * r; int x = 0; int y = r; while (x < y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if ((cornername & 0x1) != 0) { DrawVLine(x0 + x, y0 - y, 2 * y + 1 + delta, colored); DrawVLine(x0 + y, y0 - x, 2 * x + 1 + delta, colored); } if ((cornername & 0x2) != 0) { DrawVLine(x0 - x, y0 - y, 2 * y + 1 + delta, colored); DrawVLine(x0 - y, y0 - x, 2 * x + 1 + delta, colored); } } } //// Draw a triangle public void DrawTriangle(int x0, int y0, int x1, int y1, int x2, int y2, bool colored = true) { DrawLine(x0, y0, x1, y1, colored); DrawLine(x1, y1, x2, y2, colored); DrawLine(x2, y2, x0, y0, colored); } public void DrawChar(int x, int y, char c, int size = 1, bool colored = true) { if ((x >= _width) || // Clip right (y >= _height) || // Clip bottom ((x + 6 * size - 1) < 0) || // Clip left ((y + 8 * size - 1) < 0)) // Clip top return; for (byte i = 0; i < 6; i++) { byte line; if (i == 5) line = 0x0; else //line = pgm_read_byte(font+(c*5)+i); line = Glcfont.MEM[(c * 5) + i]; for (byte j = 0; j < 8; j++) { if ((line & 0x1) != 0) { if (size == 1) // default size DrawPixel(x + i, y + j, colored); else { // big size DrawFilledRectangle(x + (i * size), y + (j * size), size, size, colored); } } else { if (size == 1) // default size DrawPixel(x + i, y + j, !colored); else { // big size DrawFilledRectangle(x + i * size, y + j * size, size, size, !colored); } } line >>= 1; } } } public void DrawText(int x,int y,char[] text, int size = 1, bool colored = true,bool wrap=true) { int cursorX = x; int cursorY = y; foreach (char c in text) { if (c == '\n') { cursorY += size * 8; cursorX = 0; } else if (c == '\r') { // skip em } else { DrawChar(cursorX, cursorY, c, size, colored); cursorX += size * 6; if (wrap && (cursorX > (_width - size * 6))) { cursorY += size * 8; cursorX = 0; } } } } private bool isInScreen(int x, int y) { if (x < 0 || x >= _width) return false; if (y < 0 || y >= _height) return false; return true; } private void SendArray(byte[] array, ushort startIndex, ushort endIndex) { for (int i = startIndex; i < endIndex; i++) { sendData(array[i]); } } public void SetContrast(byte value = 0xFF) { //sendCommand(new byte[]{0x81,value}); sendCommand(0x81); sendCommand(value); } public void SetInverseDisplay(bool inverse) { if (inverse) sendCommand(0xA7); else sendCommand(0xA6); } public void SetEntireDisplayON(bool setOn) { if (setOn) sendCommand(0xA5); else sendCommand(0xA4); } public void SetMemoryAddressingMode() { //TODO another modes sendCommand(0x20); sendCommand(0x00); } private void setColumnAddress(byte start = 0, byte end = 127) { //sendCommand(new byte[] { 0x21, start, end }); sendCommand(0x21); sendCommand(start); sendCommand(end); } private void setPageAddress(byte start = 0, byte end = 7) { sendCommand(0x22); sendCommand(start); sendCommand(end); } /// <summary> /// Start horizontall scrolling /// </summary> /// <param name="left">true = scrolling to left, false = scrollong to right</param> /// <param name="start">Start page index</param> /// <param name="stop">Stop page index</param> public void StartScrollHorizontally(bool left, byte start, byte stop) { DeactivateScroll(); if (left) sendCommand(0x27); else sendCommand(0x26); sendCommand(0x00); sendCommand(start); //start page index sendCommand(0x00); //scroll interval in frames sendCommand(stop); //end page index sendCommand(0x00); sendCommand(0xFF); sendCommand(0x2F); //start scroll } /// <summary> /// Start vert. and hor. scrolling == diagonal /// </summary> /// <param name="left">true = scrolling to left, false = scrollong to right</param> /// <param name="start">Start page index</param> /// <param name="stop">Stop page index</param> /// <param name="verticalOffset"></param> public void StartScrollVerticallyHorizontally(bool left, byte start, byte stop,byte verticalOffset) { DeactivateScroll(); if (left) sendCommand(0x2A); else sendCommand(0x29); sendCommand(0x00); sendCommand(start); //start page index sendCommand(0x00); //scroll interval in frames sendCommand(stop); //end page index sendCommand(verticalOffset); //vertical scrolling offset sendCommand(0x2F); //start scroll } /// <summary> /// Turn off scrolling /// </summary> public void DeactivateScroll() { sendCommand(0x2E); } public void SetVerticalScrollArea(byte topRow, byte numberOfRows) { DeactivateScroll(); sendCommand(0xA3); sendCommand(topRow); sendCommand(numberOfRows); sendCommand(0x2F); } } }
using System; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Drawing; using Rectangle = Microsoft.Msagl.Core.Geometry.Rectangle; using System.Collections.Generic; using Edge = Microsoft.Msagl.Core.Layout.Edge; using ILabeledObject = Microsoft.Msagl.Core.Layout.ILabeledObject; using Label = Microsoft.Msagl.Core.Layout.Label; namespace Microsoft.Msagl.Drawing { /// <summary> /// If this delegate is not null and returns true then no node rendering is done by the viewer, the delegate is supposed to do the job. /// </summary> /// <param name="node"></param> /// <param name="graphics"></param> public delegate bool DelegateToOverrideNodeRendering(Node node, object graphics); /// <summary> /// By default a node boundary is calculated from Attr.Shape and the label size. /// If the delegate is not null and returns not a null ICurve then this curve is taken as the node boundary /// </summary> /// <returns></returns> public delegate ICurve DelegateToSetNodeBoundary(Node node); /// <summary> /// Node of the Microsoft.Msagl.Drawing. /// </summary> [Serializable] public class Node : DrawingObject, ILabeledObject { Label label; /// <summary> /// the label of the object /// </summary> public Label Label { get { return label; } set { label = value; } } /// <summary> /// A delegate to draw node /// </summary> DelegateToOverrideNodeRendering drawNodeDelegate; /// <summary> /// If this delegate is not null and returns true then no node rendering is done /// </summary> public DelegateToOverrideNodeRendering DrawNodeDelegate { get { return drawNodeDelegate; } set { drawNodeDelegate = value; } } DelegateToSetNodeBoundary nodeBoundaryDelegate; /// <summary> /// By default a node boundary is calculated from Attr.Shape and the label size. /// If the delegate is not null and returns not a null ICurve then this curve is taken as the node boundary /// </summary> /// <returns></returns> public DelegateToSetNodeBoundary NodeBoundaryDelegate { get { return nodeBoundaryDelegate; } set { nodeBoundaryDelegate = value; } } /// <summary> /// gets the node bounding box /// </summary> override public Rectangle BoundingBox { get { return GeometryNode.BoundaryCurve.BoundingBox; } } /// <summary> /// Attribute controlling the node drawing. /// </summary> NodeAttr attr; /// <summary> /// gets or sets the node attribute /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Attr")] public NodeAttr Attr { get { return attr; } set { attr = value; } } /// <summary> /// Creates a Node instance /// </summary> /// <param name="id">node name</param> public Node(string id) { Label = new Label(); Label.GeometryLabel = null; Label.Owner = this; Attr = new NodeAttr(); attr.Id = id; Label.Text = id; //one can change the label later } /// <summary> /// /// </summary> /// <param name="o"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "o")] public int CompareTo(object o) { Node n = o as Node; if (n == null) throw new InvalidOperationException(); return String.Compare(this.Attr.Id, n.Attr.Id, StringComparison.Ordinal); } /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { string label_text = Label == null ? Id : Label.Text; return Utils.Quote(label_text) + "[" + Attr.ToString() + ","+ GeomDataString() + "]"; } string HeightString() { return "height=" + GeometryNode.Height; } string WidthString() { return "width=" + GeometryNode.Width; } string CenterString() { return "pos=" + string.Format("\"{0},{1}\"", GeometryNode.Center.X, GeometryNode.Center.Y); } string GeomDataString() { return Utils.ConcatWithComma(HeightString(), CenterString(), WidthString()); } /// <summary> /// the node ID /// </summary> public string Id { get { return this.attr.Id; } set { attr.Id = value; } } Set<Edge> outEdges=new Set<Edge>(); /// <summary> /// Enumerates over outgoing edges of the node /// </summary> public IEnumerable<Edge> OutEdges{ get{return outEdges;}} Set<Edge> inEdges=new Set<Edge>(); /// <summary> /// enumerates over the node incoming edges /// </summary> public IEnumerable<Edge> InEdges{ get{return inEdges;}} Set<Edge> selfEdges=new Set<Edge>(); Core.Layout.Node geometryNode; /// <summary> /// enumerates over the node self edges /// </summary> public IEnumerable<Edge> SelfEdges{ get{return selfEdges;}} /// <summary> /// add an incoming edge to the node /// </summary> /// <param name="e"></param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "e")] public void AddInEdge(Edge e){ inEdges.Insert(e); } /// <summary> /// adds and outcoming edge to the node /// </summary> /// <param name="e"></param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "e")] public void AddOutEdge(Edge e){ outEdges.Insert(e); } /// <summary> /// adds a self edge to the node /// </summary> /// <param name="e"></param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "e")] public void AddSelfEdge(Edge e){ selfEdges.Insert(e); } /// <summary> /// Removes an in-edge from the node's edge list (this won't remove the edge from the graph). /// </summary> /// <param name="edge">The edge to be removed</param> public void RemoveInEdge(Edge edge) { inEdges.Remove(edge); } /// <summary> /// Removes an out-edge from the node's edge list (this won't remove the edge from the graph). /// </summary> /// <param name="edge">The edge to be removed</param> public void RemoveOutEdge(Edge edge) { outEdges.Remove(edge); } /// <summary> /// Removes a self-edge from the node's edge list (this won't remove the edge from the graph). /// </summary> /// <param name="edge">The edge to be removed</param> public void RemoveSelfEdge(Edge edge) { selfEdges.Remove(edge); } /// <summary> /// gets the geometry node /// </summary> public override GeometryObject GeometryObject { get { return GeometryNode; } set { GeometryNode = (Core.Layout.Node) value; } } /// <summary> /// the underlying geometry node /// </summary> public Core.Layout.Node GeometryNode { get { return geometryNode; } set { geometryNode = value; } } /// <summary> /// a shortcut to the node label text /// </summary> public string LabelText { get { return Label!=null?Label.Text:""; } set { if(Label==null) Label=new Label(); Label.Text = value; } } /// <summary> /// enumerates over all edges /// </summary> public IEnumerable<Edge> Edges { get { foreach (Edge e in InEdges) yield return e; foreach (Edge e in OutEdges) yield return e; foreach (Edge e in SelfEdges) yield return e; } } /// <summary> /// /// </summary> public double Height { get { return GeometryNode.Height; } } /// <summary> /// /// </summary> public double Width { get { return GeometryNode.Width; } } /// <summary> /// /// </summary> public Point Pos{get { return GeometryNode.Center; }} /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { var otherNode = obj as Node; if (otherNode == null) return false; return otherNode.Id == Id; } /// <summary> /// /// </summary> /// <returns></returns> public override int GetHashCode() { return Id.GetHashCode(); } /// <summary> /// /// </summary> public override bool IsVisible { get { return base.IsVisible; } set { base.IsVisible = value; if(!value) foreach (var e in Edges) e.IsVisible = false; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Discovery.Tcp; using Apache.Ignite.Core.Discovery.Tcp.Static; #if !NETCOREAPP2_0 using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Binary; #endif using NUnit.Framework; /// <summary> /// Test utility methods. /// </summary> public static partial class TestUtils { /** Indicates long running and/or memory/cpu intensive test. */ public const string CategoryIntensive = "LONG_TEST"; /** Indicates examples tests. */ public const string CategoryExamples = "EXAMPLES_TEST"; /** */ private const int DfltBusywaitSleepInterval = 200; /** */ private static readonly IList<string> TestJvmOpts = Environment.Is64BitProcess ? new List<string> { "-XX:+HeapDumpOnOutOfMemoryError", "-Xms1g", "-Xmx4g", "-ea", "-DIGNITE_QUIET=true", "-Duser.timezone=UTC" } : new List<string> { "-XX:+HeapDumpOnOutOfMemoryError", "-Xms64m", "-Xmx99m", "-ea", "-DIGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE=1000", "-DIGNITE_QUIET=true", "-Duser.timezone=UTC" }; /** */ private static readonly IList<string> JvmDebugOpts = new List<string> { "-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005" }; /** */ public static bool JvmDebug = true; /** */ [ThreadStatic] private static Random _random; /** */ private static int _seed = Environment.TickCount; /// <summary> /// /// </summary> public static Random Random { get { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); } } /// <summary> /// /// </summary> /// <returns></returns> public static IList<string> TestJavaOptions(bool? jvmDebug = null) { IList<string> ops = new List<string>(TestJvmOpts); if (jvmDebug ?? JvmDebug) { foreach (string opt in JvmDebugOpts) ops.Add(opt); } return ops; } /// <summary> /// /// </summary> /// <param name="action"></param> /// <param name="threadNum"></param> public static void RunMultiThreaded(Action action, int threadNum) { List<Thread> threads = new List<Thread>(threadNum); var errors = new ConcurrentBag<Exception>(); for (int i = 0; i < threadNum; i++) { threads.Add(new Thread(() => { try { action(); } catch (Exception e) { errors.Add(e); } })); } foreach (Thread thread in threads) thread.Start(); foreach (Thread thread in threads) thread.Join(); foreach (var ex in errors) Assert.Fail("Unexpected exception: " + ex); } /// <summary> /// /// </summary> /// <param name="action"></param> /// <param name="threadNum"></param> /// <param name="duration">Duration of test execution in seconds</param> public static void RunMultiThreaded(Action action, int threadNum, int duration) { List<Thread> threads = new List<Thread>(threadNum); var errors = new ConcurrentBag<Exception>(); bool stop = false; for (int i = 0; i < threadNum; i++) { threads.Add(new Thread(() => { try { while (true) { Thread.MemoryBarrier(); // ReSharper disable once AccessToModifiedClosure if (stop) break; action(); } } catch (Exception e) { errors.Add(e); } })); } foreach (Thread thread in threads) thread.Start(); Thread.Sleep(duration * 1000); stop = true; Thread.MemoryBarrier(); foreach (Thread thread in threads) thread.Join(); foreach (var ex in errors) Assert.Fail("Unexpected exception: " + ex); } /// <summary> /// Wait for particular topology size. /// </summary> /// <param name="grid">Grid.</param> /// <param name="size">Size.</param> /// <param name="timeout">Timeout.</param> /// <returns> /// <c>True</c> if topology took required size. /// </returns> public static bool WaitTopology(this IIgnite grid, int size, int timeout = 30000) { int left = timeout; while (true) { if (grid.GetCluster().GetNodes().Count != size) { if (left > 0) { Thread.Sleep(100); left -= 100; } else break; } else return true; } return false; } /// <summary> /// Waits for condition, polling in busy wait loop. /// </summary> /// <param name="cond">Condition.</param> /// <param name="timeout">Timeout, in milliseconds.</param> /// <returns>True if condition predicate returned true within interval; false otherwise.</returns> public static bool WaitForCondition(Func<bool> cond, int timeout) { if (timeout <= 0) return cond(); var maxTime = DateTime.Now.AddMilliseconds(timeout + DfltBusywaitSleepInterval); while (DateTime.Now < maxTime) { if (cond()) return true; Thread.Sleep(DfltBusywaitSleepInterval); } return false; } /// <summary> /// Gets the static discovery. /// </summary> public static TcpDiscoverySpi GetStaticDiscovery() { return new TcpDiscoverySpi { IpFinder = new TcpDiscoveryStaticIpFinder { Endpoints = new[] { "127.0.0.1:47500" } }, SocketTimeout = TimeSpan.FromSeconds(0.3) }; } /// <summary> /// Gets the primary keys. /// </summary> public static IEnumerable<int> GetPrimaryKeys(IIgnite ignite, string cacheName, IClusterNode node = null) { var aff = ignite.GetAffinity(cacheName); node = node ?? ignite.GetCluster().GetLocalNode(); return Enumerable.Range(1, int.MaxValue).Where(x => aff.IsPrimary(node, x)); } /// <summary> /// Gets the primary key. /// </summary> public static int GetPrimaryKey(IIgnite ignite, string cacheName, IClusterNode node = null) { return GetPrimaryKeys(ignite, cacheName, node).First(); } /// <summary> /// Asserts that the handle registry is empty. /// </summary> /// <param name="timeout">Timeout, in milliseconds.</param> /// <param name="grids">Grids to check.</param> public static void AssertHandleRegistryIsEmpty(int timeout, params IIgnite[] grids) { foreach (var g in grids) AssertHandleRegistryHasItems(g, 0, timeout); } /// <summary> /// Asserts that the handle registry has specified number of entries. /// </summary> /// <param name="timeout">Timeout, in milliseconds.</param> /// <param name="expectedCount">Expected item count.</param> /// <param name="grids">Grids to check.</param> public static void AssertHandleRegistryHasItems(int timeout, int expectedCount, params IIgnite[] grids) { foreach (var g in grids) AssertHandleRegistryHasItems(g, expectedCount, timeout); } /// <summary> /// Asserts that the handle registry has specified number of entries. /// </summary> /// <param name="grid">The grid to check.</param> /// <param name="expectedCount">Expected item count.</param> /// <param name="timeout">Timeout, in milliseconds.</param> public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout) { #if !NETCOREAPP2_0 var handleRegistry = ((Ignite)grid).HandleRegistry; expectedCount++; // Skip default lifecycle bean if (WaitForCondition(() => handleRegistry.Count == expectedCount, timeout)) return; var items = handleRegistry.GetItems().Where(x => !(x.Value is LifecycleHandlerHolder)).ToList(); if (items.Any()) { Assert.Fail("HandleRegistry is not empty in grid '{0}' (expected {1}, actual {2}):\n '{3}'", grid.Name, expectedCount, handleRegistry.Count, items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y)); } #endif } /// <summary> /// Serializes and deserializes back an object. /// </summary> public static T SerializeDeserialize<T>(T obj, bool raw = false) { var cfg = new BinaryConfiguration { Serializer = raw ? new BinaryReflectiveSerializer {RawMode = true} : null }; #if NETCOREAPP2_0 var marshType = typeof(IIgnite).Assembly.GetType("Apache.Ignite.Core.Impl.Binary.Marshaller"); var marsh = Activator.CreateInstance(marshType, new object[] { cfg, null }); marshType.GetProperty("CompactFooter").SetValue(marsh, false); var bytes = marshType.GetMethod("Marshal").MakeGenericMethod(typeof(object)) .Invoke(marsh, new object[] { obj }); var res = marshType.GetMethods().Single(mi => mi.Name == "Unmarshal" && mi.GetParameters().First().ParameterType == typeof(byte[])) .MakeGenericMethod(typeof(object)).Invoke(marsh, new[] { bytes, 0 }); return (T)res; #else var marsh = new Marshaller(cfg) { CompactFooter = false }; return marsh.Unmarshal<T>(marsh.Marshal(obj)); #endif } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { // This implementation uses the System.Net.Http.WinHttpHandler class on Windows. Other platforms will need to use // their own platform specific implementation. public class HttpClientHandler : HttpMessageHandler { #region Properties public virtual bool SupportsAutomaticDecompression { get { return true; } } public virtual bool SupportsProxy { get { return true; } } public virtual bool SupportsRedirectConfiguration { get { return true; } } public bool UseCookies { get { return (_winHttpHandler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer); } set { _winHttpHandler.CookieUsePolicy = value ? CookieUsePolicy.UseSpecifiedCookieContainer : CookieUsePolicy.IgnoreCookies; } } public CookieContainer CookieContainer { get { return _winHttpHandler.CookieContainer; } set { _winHttpHandler.CookieContainer = value; } } public ClientCertificateOption ClientCertificateOptions { get { return _winHttpHandler.ClientCertificateOption; } set { _winHttpHandler.ClientCertificateOption = value; } } public DecompressionMethods AutomaticDecompression { get { return _winHttpHandler.AutomaticDecompression; } set { _winHttpHandler.AutomaticDecompression = value; } } public bool UseProxy { get { return _useProxy; } set { _useProxy = value; } } public IWebProxy Proxy { get { return _winHttpHandler.Proxy; } set { _winHttpHandler.Proxy = value; } } public bool PreAuthenticate { get { return _winHttpHandler.PreAuthenticate; } set { _winHttpHandler.PreAuthenticate = value; } } public bool UseDefaultCredentials { // WinHttpHandler doesn't have a separate UseDefaultCredentials property. There // is just a ServerCredentials property. So, we need to map the behavior. get { return (_winHttpHandler.ServerCredentials == CredentialCache.DefaultCredentials); } set { if (value) { _winHttpHandler.DefaultProxyCredentials = CredentialCache.DefaultCredentials; _winHttpHandler.ServerCredentials = CredentialCache.DefaultCredentials; } else { _winHttpHandler.DefaultProxyCredentials = null; if (_winHttpHandler.ServerCredentials == CredentialCache.DefaultCredentials) { // Only clear out the ServerCredentials property if it was a DefaultCredentials. _winHttpHandler.ServerCredentials = null; } } } } public ICredentials Credentials { get { return _winHttpHandler.ServerCredentials; } set { _winHttpHandler.ServerCredentials = value; } } public bool AllowAutoRedirect { get { return _winHttpHandler.AutomaticRedirection; } set { _winHttpHandler.AutomaticRedirection = value; } } public int MaxAutomaticRedirections { get { return _winHttpHandler.MaxAutomaticRedirections; } set { _winHttpHandler.MaxAutomaticRedirections = value; } } public long MaxRequestContentBufferSize { // This property has been deprecated. In the .NET Desktop it was only used when the handler needed to // automatically buffer the request content. That only happened if neither 'Content-Length' nor // 'Transfer-Encoding: chunked' request headers were specified. So, the handler thus needed to buffer // in the request content to determine its length and then would choose 'Content-Length' semantics when // POST'ing. In CoreCLR and .NETNative, the handler will resolve the ambiguity by always choosing // 'Transfer-Encoding: chunked'. The handler will never automatically buffer in the request content. get { return 0; } // TODO: Add message/link to exception explaining the deprecation. // Update corresponding exception in HttpClientHandler.Unix.cs if/when this is updated. set { throw new PlatformNotSupportedException(); } } #endregion Properties #region De/Constructors public HttpClientHandler() { _winHttpHandler = new WinHttpHandler(); // Adjust defaults to match current .NET Desktop HttpClientHandler (based on HWR stack). AllowAutoRedirect = true; UseProxy = true; UseCookies = true; CookieContainer = new CookieContainer(); // The existing .NET Desktop HttpClientHandler based on the HWR stack uses only WinINet registry // settings for the proxy. This also includes supporting the "Automatic Detect a proxy" using // WPAD protocol and PAC file. So, for app-compat, we will do the same for the default proxy setting. _winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; _winHttpHandler.Proxy = null; // Since the granular WinHttpHandler timeout properties are not exposed via the HttpClientHandler API, // we need to set them to infinite and allow the HttpClient.Timeout property to have precedence. _winHttpHandler.ConnectTimeout = Timeout.InfiniteTimeSpan; _winHttpHandler.ReceiveHeadersTimeout = Timeout.InfiniteTimeSpan; _winHttpHandler.ReceiveDataTimeout = Timeout.InfiniteTimeSpan; _winHttpHandler.SendTimeout = Timeout.InfiniteTimeSpan; } protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; // Release WinHttp session handle. _winHttpHandler.Dispose(); } base.Dispose(disposing); } #endregion De/Constructors #region Request Execution protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // Get current value of WindowsProxyUsePolicy. Only call its WinHttpHandler // property setter if the value needs to change. var oldProxyUsePolicy = _winHttpHandler.WindowsProxyUsePolicy; if (_useProxy) { if (_winHttpHandler.Proxy == null) { if (oldProxyUsePolicy != WindowsProxyUsePolicy.UseWinInetProxy) { _winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; } } else { if (oldProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy) { _winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy; } } } else { if (oldProxyUsePolicy != WindowsProxyUsePolicy.DoNotUseProxy) { _winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy; } } return _winHttpHandler.SendAsync(request, cancellationToken); } #endregion Request Execution #region Private private WinHttpHandler _winHttpHandler; private bool _useProxy; private volatile bool _disposed; #endregion Private } }
using System; using Knowledge.Prospector.Data.Entities; using Knowledge.Prospector.Data.Relationships; namespace Knowledge.Prospector.Data.Collections { public class EntityGraphBuilder : IEntityGraphBuilder { public int _index; private EntityGraph Graph; private IEntityList<IEntity> _source; private bool AssertIndex(int index) { if (!(0 <= index && index < Source.Count)) return false; else return true; } public EntityGraphBuilder(EntityGraph graph, IEntityList<IEntity> source) { Graph = graph; Source = source; } public int Index { get { return _index; } private set { _index = value; } } #region IEntityGraphBuilder Members public IEntityList<IEntity> Source { get { return _source; } private set { _source = value; } } public void Add(ITrueEntity trueEntity) { Graph.Add(trueEntity); } public void Add(IClassEntity classEntity) { Graph.Add(classEntity); } public void Add(IPropertyEntity propertyEntity) { Graph.Add(propertyEntity); } public void Add(IIndividualEntity individualEntity) { Graph.Add(individualEntity); } public void Add(IDatatypeEntity datatypeEntity) { Graph.Add(datatypeEntity); } public void Add(IRelationship relationship) { Graph.Add(relationship); } public void Add(SubclassRelationship subclassRelationship) { Graph.Add(subclassRelationship); } public void Add(PropertyRelationship propertyRelationship) { Graph.Add(propertyRelationship); } public void Add(SubpropertyRelationship subpropertyRelationship) { Graph.Add(subpropertyRelationship); } public void Add(EquivalenceRelationship equivalenceRelationship) { Graph.Add(equivalenceRelationship); } public void Add(ConditionalRuleRelationship conditionalRuleRelationship) { Graph.Add(conditionalRuleRelationship); } public bool MoveNext() { if(++Index<Source.Count) return true; else { Index = Source.Count; return false; } } public bool Move(int to) { int newIndex = Index + to; if (AssertIndex(newIndex)) { Index = newIndex; return true; } else return false; } public void Reset() { Index = -1; } public IEntity Current { get { return Source[Index]; } } public bool AssertCurrent { get { return AssertIndex(Index); } } public event SourceChanged OnChanged; #endregion #region IEntityGraphBuilder Members public void Insert(int position, PositionType positionType, IEntity entity, InsertionType insertionType) { int actualPosition = positionType == PositionType.Absolute ? position : Index + position; if (insertionType == InsertionType.Before) actualPosition--; if (AssertIndex(actualPosition)) Source.Insert(actualPosition, entity); else throw new ArgumentOutOfRangeException("position"); if (OnChanged != null) OnChanged(); if (Index > actualPosition) Index++; } public void Delete(int position, PositionType positionType) { int actualPosition = positionType == PositionType.Absolute ? position : Index + position; if (AssertIndex(actualPosition)) Source.RemoveAt(actualPosition); else throw new ArgumentOutOfRangeException("position"); if (OnChanged != null) OnChanged(); if (Index > actualPosition) Index--; } public void Replace(int position, PositionType positionType, IEntity newEntity) { int actualPosition = positionType == PositionType.Absolute ? position : Index + position; if (AssertIndex(actualPosition)) Source[actualPosition] = newEntity; else throw new ArgumentOutOfRangeException("position"); if (OnChanged != null) OnChanged(); } public void Replace(int position, PositionType positionType, IEntity newEntity, int count) { int actualPosition = positionType == PositionType.Absolute ? position : Index + position; for(int i=0; i< count; i++) if(!AssertIndex(actualPosition + i)) throw new ArgumentOutOfRangeException("position"); Source[actualPosition] = newEntity; for(int i=1; i<count; i++) Source.RemoveAt(actualPosition + 1); if (OnChanged != null) OnChanged(); } #endregion } }
using System; using System.IO; /* * This stream handles sending and receiving SSL/TLS records (unencrypted). * * In output mode: * -- data is buffered until a full record is obtained * -- an explicit Flush() call terminates and sends the current record * (only if there is data to send) * -- record type is set explicitly * * In input mode: * -- records MUST have the set expected type, or be alerts * -- warning-level alerts are ignored * -- fatal-level alerts trigger SSLAlertException * -- record type mismatch triggers exceptions * -- first received record sets version (from record header); all * subsequent records MUST have the same version */ class SSLRecord : Stream { const int MAX_RECORD_LEN = 16384; Stream sub; byte[] outBuf = new byte[MAX_RECORD_LEN + 5]; int outPtr; int outVersion; int outType; byte[] inBuf = new byte[MAX_RECORD_LEN]; int inPtr; int inEnd; int inVersion; int inType; int inExpectedType; /* * Create an instance over the provided stream (normally a * network socket). */ internal SSLRecord(Stream sub) { this.sub = sub; outPtr = 5; inPtr = 0; inEnd = 0; } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } /* * Set record type. If it differs from the a previously set * record type, then an automatic flush is performed. */ internal void SetOutType(int type) { if (outType != 0 && outType != type) { Flush(); } outType = type; } /* * Set the version for the next outgoing record. */ internal void SetOutVersion(int version) { outVersion = version; } /* * Flush accumulated data. Nothing is done if there is no * accumulated data. */ public override void Flush() { if (outPtr > 5) { outBuf[0] = (byte)outType; M.Enc16be(outVersion, outBuf, 1); M.Enc16be(outPtr - 5, outBuf, 3); sub.Write(outBuf, 0, outPtr); sub.Flush(); outPtr = 5; } } public override void WriteByte(byte b) { outBuf[outPtr ++] = b; if (outPtr == outBuf.Length) { Flush(); } } public void Write(byte[] buf) { Write(buf, 0, buf.Length); } public override void Write(byte[] buf, int off, int len) { while (len > 0) { int clen = Math.Min(outBuf.Length - outPtr, len); Array.Copy(buf, off, outBuf, outPtr, clen); outPtr += clen; off += clen; len -= clen; if (outPtr == outBuf.Length) { Flush(); } } } /* * Set expected type for incoming records. */ internal void SetExpectedType(int expectedType) { this.inExpectedType = expectedType; } /* * Get the version advertised in the last incoming record. */ internal int GetInVersion() { return inVersion; } /* * Obtain next record. Incoming alerts are processed; this method * exists when the next record of the expected type is received * (though it may contain an empty payload). */ void Refill() { for (;;) { M.ReadFully(sub, inBuf, 0, 5); inType = inBuf[0]; int v = M.Dec16be(inBuf, 1); inEnd = M.Dec16be(inBuf, 3); if ((v >> 8) != 0x03) { throw new IOException(string.Format( "not an SSL 3.x record (0x{0:X4})", v)); } if (inVersion != 0 && inVersion != v) { throw new IOException(string.Format( "record version change" + " (0x{0:X4} -> 0x{1:X4})", inVersion, v)); } inVersion = v; if (inEnd > inBuf.Length) { throw new IOException(string.Format( "oversized input payload (len={0})", inEnd)); } if (inType != inExpectedType && inType != M.ALERT) { throw new IOException(string.Format( "unexpected record type ({0})", inType)); } M.ReadFully(sub, inBuf, 0, inEnd); inPtr = 0; if (inType == M.ALERT) { for (int k = 0; k < inEnd; k += 2) { int at = inBuf[k]; if (at != 0x01) { throw new SSLAlertException(at); } } /* * We just ignore warnings. */ continue; } return; } } public override int ReadByte() { while (inPtr == inEnd) { Refill(); } return inBuf[inPtr ++]; } public override int Read(byte[] buf, int off, int len) { while (inPtr == inEnd) { Refill(); } int clen = Math.Min(inEnd - inPtr, len); Array.Copy(inBuf, inPtr, buf, off, clen); inPtr += clen; return clen; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Collections.ObjectModel; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; namespace Microsoft.Azure.Management.Network.Fluent { using Microsoft.Azure.Management.Network.Fluent.ConnectionMonitor.Definition; using Microsoft.Azure.Management.Network.Fluent.Models; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Implementation for Connection Monitor and its create and update interfaces. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50Lm5ldHdvcmsuaW1wbGVtZW50YXRpb24uQ29ubmVjdGlvbk1vbml0b3JJbXBs internal partial class ConnectionMonitorImpl : Creatable<IConnectionMonitor, ConnectionMonitorResultInner, ConnectionMonitorImpl, IConnectionMonitor>, IConnectionMonitor, IDefinition { private IConnectionMonitorsOperations client; private ConnectionMonitorInner createParameters; private INetworkWatcher parent; ///GENMHASH:5FF6F22B17DD7078FE6B3E25A08DAF00:C76EE92DA65DAA991DB405193AE42CE5 internal ConnectionMonitorImpl(string name, NetworkWatcherImpl parent, ConnectionMonitorResultInner innerObject, IConnectionMonitorsOperations client) : base(name, innerObject) { this.client = client; this.parent = parent; this.createParameters = new ConnectionMonitorInner() { Location = parent.RegionName }; } ///GENMHASH:B9D2BB4C39728B86BB5341EC27BEF5F2:334CE58D69655A76396F940D26F5397B private ConnectionMonitorDestination EnsureConnectionMonitorDestination() { if (createParameters.Destination == null) { createParameters.Destination = new ConnectionMonitorDestination(); } return createParameters.Destination; } ///GENMHASH:488CBB31D59278A34B699ED73A10F5DB:9C13FADD3289F7BC4E46C0F6C78A51BF private ConnectionMonitorSource EnsureConnectionMonitorSource() { if (createParameters.Source == null) { createParameters.Source = new ConnectionMonitorSource(); } return createParameters.Source; } ///GENMHASH:5AD91481A0966B059A478CD4E9DD9466:754810EA5144700BBB078C6E55E8C153 protected override async Task<Models.ConnectionMonitorResultInner> GetInnerAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await this.client.GetAsync(parent.ResourceGroupName, parent.Name, Name, cancellationToken); } ///GENMHASH:C5D89656612B3B4FD5897FBFC88C3AFB:72EB2BF07E27ECC8589DC1335BAC8634 public bool AutoStart() { return Inner.AutoStart.GetValueOrDefault(); } ///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:228A9A3D68EE8BB5ABA520AE16356B8A public override async Task<Microsoft.Azure.Management.Network.Fluent.IConnectionMonitor> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken)) { SetInner(await this.client.CreateOrUpdateAsync(parent.ResourceGroupName, parent.Name, this.Name, createParameters, cancellationToken)); return this; } ///GENMHASH:D330F5721F151F2EF9CE3A499FEC146C:6241791A4C41364EBE5B29EF053BFE99 public ConnectionMonitorDestination Destination() { return Inner.Destination; } ///GENMHASH:ACA2D5620579D8158A29586CA1FF4BC6:A3CF7B3DC953F353AAE8083D72F74056 public string Id() { return Inner.Id; } ///GENMHASH:76EDE6DBF107009D2B06F19698F6D5DB:19C4BD8FCE58F39FC1CCEB1A6C862717 public bool IsInCreateMode() { return this.Inner.Id == null; } ///GENMHASH:A85BBC58BA3B783F90EB92B75BD97D51:0D9EEC636DF1E11A81923129881E6F92 public string Location() { return Inner.Location; } ///GENMHASH:EAFDB99A61316B0968D2B5817643E652:31A5B5F46E0134D8E34EBD8783C0CD33 public int MonitoringIntervalInSeconds() { return Inner.MonitoringIntervalInSeconds.GetValueOrDefault(); } ///GENMHASH:08BED39C9817265E9F51D92232F5E007:6998790F6649D3ED6685336731B5252B public string MonitoringStatus() { return Inner.MonitoringStatus; } ///GENMHASH:99D5BF64EA8AA0E287C9B6F77AAD6FC4:3DB04077E6BABC0FB5A5ACDA19D11309 public ProvisioningState ProvisioningState() { return Inner.ProvisioningState; } ///GENMHASH:BF76A8643A23730A004C9A3DAA62583F:B0655019009F078380DC66C730FBA78F public IConnectionMonitorQueryResult Query() { return Extensions.Synchronize(() => QueryAsync()); } ///GENMHASH:A409C3D3741509AF429A05127B5E4382:58F7FC16B9BBD602D0D4676357994540 public async Task<Microsoft.Azure.Management.Network.Fluent.IConnectionMonitorQueryResult> QueryAsync(CancellationToken cancellationToken = default(CancellationToken)) { return new ConnectionMonitorQueryResultImpl(await this.client.QueryAsync(parent.ResourceGroupName, parent.Name, Name, cancellationToken)); } ///GENMHASH:32ABF27B7A32286845C5FAFE717F8E4D:E5A3D960F98D36AB45F0D6541D43C4D9 public ConnectionMonitorSource Source() { return Inner.Source; } ///GENMHASH:0F38250A3837DF9C2C345D4A038B654B:1A0917D3B99C0446F2507D37E60DF88A public void Start() { Extensions.Synchronize(() => StartAsync()); } ///GENMHASH:D5AD274A3026D80CDF6A0DD97D9F20D4:C86F332142083D93E0A8AECBA0BFB621 public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken)) { await client.StartAsync(parent.ResourceGroupName, parent.Name, Name, cancellationToken); await RefreshAsync(cancellationToken); } ///GENMHASH:8550B4F26F41D82222F735D9324AEB6D:29AAFE9F1BD0E0EEB26150A53E8B7A36 public DateTime StartTime() { return Inner.StartTime.GetValueOrDefault(); } ///GENMHASH:EB854F18026EDB6E01762FA4580BE789:42462B796F15B0EB6E603ACA753873C0 public void Stop() { Extensions.Synchronize(() => StopAsync()); } ///GENMHASH:D6FBED7FC7CBF34940541851FF5C3CC1:420B8DFD511324EA1988F38805A1D401 public async Task StopAsync(CancellationToken cancellationToken = default(CancellationToken)) { await client.StopAsync(parent.ResourceGroupName, parent.Name, Name, cancellationToken); await RefreshAsync(cancellationToken); } ///GENMHASH:4B19A5F1B35CA91D20F63FBB66E86252:15C9AB470710087E177FDDC5B9B7425E public IReadOnlyDictionary<string,string> Tags() { IDictionary<string, string> tags = Inner.Tags; if (tags == null) { tags = new Dictionary<string, string>(); } return new ReadOnlyDictionary<string, string>(tags); } ///GENMHASH:388CBA9D80803D0B06C6BEF1D75F45BE:F0B76E5F29DC1C6CB2AB2A49CE5033A9 public ConnectionMonitorImpl WithDestination(IHasNetworkInterfaces vm) { EnsureConnectionMonitorDestination().ResourceId = vm.Id; return this; } ///GENMHASH:8A174EF40FE176D85B52DCBE164A95D2:1F01EEB3C44ECBF508683E4031406628 public IWithDestinationPort WithDestinationAddress(string address) { EnsureConnectionMonitorDestination().Address = address; return this; } ///GENMHASH:5BFD78BA0B8D6AD63806A2E1A394B896:0DC49C4F23113DFE2125346DC6F3618C public ConnectionMonitorImpl WithDestinationId(string resourceId) { EnsureConnectionMonitorDestination().ResourceId = resourceId; return this; } ///GENMHASH:5C1319A874A387C53AA45A67B22181DD:65CBFD400090B912B507538B6F3F10C0 public ConnectionMonitorImpl WithDestinationPort(int port) { EnsureConnectionMonitorDestination().Port = port; return this; } ///GENMHASH:A4EC698B9E229B245DB08EABB50ED30F:5FD4951B514D8558230BD6974A41B56C public ConnectionMonitorImpl WithMonitoringInterval(int seconds) { createParameters.MonitoringIntervalInSeconds = seconds; return this; } ///GENMHASH:DA48CE39A0F1A776641DCC49EA175DB1:C2FFEC15CF486D6F001384A4795E4192 public ConnectionMonitorImpl WithoutAutoStart() { createParameters.AutoStart = false; return this; } ///GENMHASH:2345D3E100BA4B78504A2CC57A361F1E:3F3F4D4DB4FC89533CF7F0CB3337D43E public ConnectionMonitorImpl WithoutTag(string key) { if (this.createParameters.Tags != null) { this.createParameters.Tags.Remove(key); } return this; } ///GENMHASH:0022FE3C90BA353F5DFB1A0CD71BAFEC:AD3EAB000A98E8F8E7437C14A2A03788 public ConnectionMonitorImpl WithSource(IHasNetworkInterfaces vm) { EnsureConnectionMonitorSource().ResourceId = vm.Id; return this; } ///GENMHASH:3FE297B3D6780FD582BD7FDEFCE71BB3:DC53311C981BF68101FB10F19A9D9086 public ConnectionMonitorImpl WithSourceId(string resourceId) { EnsureConnectionMonitorSource().ResourceId = resourceId; return this; } ///GENMHASH:9C64003375BC094D7FF90E056718A78F:0BAE81001ED785473AC6A725480D5EFD public ConnectionMonitorImpl WithSourcePort(int port) { EnsureConnectionMonitorSource().Port = port; return this; } ///GENMHASH:FF80DD5A8C82E021759350836BD2FAD1:64CC65B272BB8B61AFE073828F00AA2F public ConnectionMonitorImpl WithTag(string key, string value) { if (Inner.Tags == null) { Inner.Tags = new Dictionary<string, string>(); } Inner.Tags.Add(key, value); return this; } ///GENMHASH:32E35A609CF1108D0FC5FAAF9277C1AA:810B4CB467DA820135856412C60BC6FD public ConnectionMonitorImpl WithTags(IDictionary<string,string> tags) { Inner.Tags = new Dictionary<string, string>(tags); return this; } } }
// 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.KeyVault.Fluent { using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Microsoft.Azure.KeyVault.Models; using Microsoft.Azure.Management.KeyVault.Fluent; using Microsoft.Azure.Management.KeyVault.Fluent.Models; using Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition; using Microsoft.Azure.Management.KeyVault.Fluent.Key.Update; using Microsoft.Azure.Management.KeyVault.Fluent.Key.UpdateWithCreate; using Microsoft.Azure.Management.KeyVault.Fluent.Key.UpdateWithImport; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; internal partial class KeyImpl { /// <summary> /// Specifies the list of allowed key operations. By default all operations are allowed. /// </summary> /// <param name="keyOperations">The list of JWK operations.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IWithKeyOperations.WithKeyOperations(IList<JsonWebKeyOperation> keyOperations) { return this.WithKeyOperations(keyOperations) as Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IUpdate; } /// <summary> /// Specifies the list of allowed key operations. By default all operations are allowed. /// </summary> /// <param name="keyOperations">The list of JWK operations.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IWithKeyOperations.WithKeyOperations(params JsonWebKeyOperation[] keyOperations) { return this.WithKeyOperations(keyOperations) as Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IUpdate; } /// <summary> /// Specifies the list of allowed key operations. By default all operations are allowed. /// </summary> /// <param name="keyOperations">The list of JWK operations.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithKeyOperations.WithKeyOperations(IList<JsonWebKeyOperation> keyOperations) { return this.WithKeyOperations(keyOperations) as Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithCreate; } /// <summary> /// Specifies the list of allowed key operations. By default all operations are allowed. /// </summary> /// <param name="keyOperations">The list of JWK operations.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithKeyOperations.WithKeyOperations(params JsonWebKeyOperation[] keyOperations) { return this.WithKeyOperations(keyOperations) as Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithCreate; } /// <summary> /// Verifies a signature from a digest. /// </summary> /// <param name="algorithm">The JWK signing algorithm.</param> /// <param name="digest">The content to be signed.</param> /// <param name="signature">The signature to verify.</param> /// <return>True if the signature is valid.</return> bool Microsoft.Azure.Management.KeyVault.Fluent.IKey.Verify(JsonWebKeySignatureAlgorithm algorithm, byte[] digest, params byte[] signature) { return this.Verify(algorithm, digest, signature); } /// <summary> /// Decrypts a single block of encrypted data. /// </summary> /// <param name="algorithm">The JWK encryption algorithm.</param> /// <param name="content">The content to be decrypted.</param> /// <return>The decrypted value.</return> byte[] Microsoft.Azure.Management.KeyVault.Fluent.IKey.Decrypt(JsonWebKeyEncryptionAlgorithm algorithm, params byte[] content) { return this.Decrypt(algorithm, content); } /// <return>A list of individual key versions with the same key name.</return> async Task<Microsoft.Azure.Management.KeyVault.Fluent.IKey> Microsoft.Azure.Management.KeyVault.Fluent.IKey.ListVersionsAsync(CancellationToken cancellationToken) { return await this.ListVersionsAsync(cancellationToken) as Microsoft.Azure.Management.KeyVault.Fluent.IKey; } /// <return>A backup of the specified key be downloaded to the client.</return> byte[] Microsoft.Azure.Management.KeyVault.Fluent.IKey.Backup() { return this.Backup(); } /// <summary> /// Gets the Json web key. /// </summary> Microsoft.Azure.KeyVault.WebKey.JsonWebKey Microsoft.Azure.Management.KeyVault.Fluent.IKey.JsonWebKey { get { return this.JsonWebKey() as Microsoft.Azure.KeyVault.WebKey.JsonWebKey; } } /// <summary> /// Gets the key management attributes. /// </summary> Microsoft.Azure.KeyVault.Models.KeyAttributes Microsoft.Azure.Management.KeyVault.Fluent.IKey.Attributes { get { return this.Attributes() as Microsoft.Azure.KeyVault.Models.KeyAttributes; } } /// <summary> /// Verifies a signature from a digest. /// </summary> /// <param name="algorithm">The JWK signing algorithm.</param> /// <param name="digest">The content to be signed.</param> /// <param name="signature">The signature to verify.</param> /// <return>True if the signature is valid.</return> async Task<bool> Microsoft.Azure.Management.KeyVault.Fluent.IKey.VerifyAsync(JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature, CancellationToken cancellationToken) { return await this.VerifyAsync(algorithm, digest, signature, cancellationToken); } /// <summary> /// Gets application specific metadata in the form of key-value pairs. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string, string> Microsoft.Azure.Management.KeyVault.Fluent.IKey.Tags { get { return this.Tags() as System.Collections.Generic.IReadOnlyDictionary<string, string>; } } /// <summary> /// Creates a signature from a digest. /// </summary> /// <param name="algorithm">The JWK signing algorithm.</param> /// <param name="digest">The content to be signed.</param> /// <return>The signature in a byte[] array.</return> async Task<byte[]> Microsoft.Azure.Management.KeyVault.Fluent.IKey.SignAsync(JsonWebKeySignatureAlgorithm algorithm, byte[] digest, CancellationToken cancellationToken) { return await this.SignAsync(algorithm, digest, cancellationToken); } /// <summary> /// Wraps a symmetric key using the specified algorithm. /// </summary> /// <param name="algorithm">The JWK encryption algorithm.</param> /// <param name="key">The symmetric key to wrap.</param> /// <return>The wrapped key.</return> async Task<byte[]> Microsoft.Azure.Management.KeyVault.Fluent.IKey.WrapKeyAsync(JsonWebKeyEncryptionAlgorithm algorithm, byte[] key, CancellationToken cancellationToken) { return await this.WrapKeyAsync(algorithm, key, cancellationToken); } /// <summary> /// Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. /// </summary> /// <param name="algorithm">The JWK encryption algorithm.</param> /// <param name="content">The content to be encrypted.</param> /// <return>The encrypted value.</return> byte[] Microsoft.Azure.Management.KeyVault.Fluent.IKey.Encrypt(JsonWebKeyEncryptionAlgorithm algorithm, params byte[] content) { return this.Encrypt(algorithm, content); } /// <summary> /// Wraps a symmetric key using the specified algorithm. /// </summary> /// <param name="algorithm">The JWK encryption algorithm.</param> /// <param name="key">The symmetric key to wrap.</param> /// <return>The wrapped key.</return> byte[] Microsoft.Azure.Management.KeyVault.Fluent.IKey.WrapKey(JsonWebKeyEncryptionAlgorithm algorithm, params byte[] key) { return this.WrapKey(algorithm, key); } /// <summary> /// Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. /// </summary> /// <param name="algorithm">The JWK encryption algorithm.</param> /// <param name="content">The content to be encrypted.</param> /// <return>The encrypted value.</return> async Task<byte[]> Microsoft.Azure.Management.KeyVault.Fluent.IKey.EncryptAsync(JsonWebKeyEncryptionAlgorithm algorithm, byte[] content, CancellationToken cancellationToken) { return await this.EncryptAsync(algorithm, content, cancellationToken); } /// <summary> /// Unwraps a symmetric key wrapped originally by this Key Vault key. /// </summary> /// <param name="algorithm">The JWK encryption algorithm.</param> /// <param name="key">The key to unwrap.</param> /// <return>The unwrapped symmetric key.</return> async Task<byte[]> Microsoft.Azure.Management.KeyVault.Fluent.IKey.UnwrapKeyAsync(JsonWebKeyEncryptionAlgorithm algorithm, byte[] key, CancellationToken cancellationToken) { return await this.UnwrapKeyAsync(algorithm, key, cancellationToken); } /// <return>A backup of the specified key be downloaded to the client.</return> async Task<byte[]> Microsoft.Azure.Management.KeyVault.Fluent.IKey.BackupAsync(CancellationToken cancellationToken) { return await this.BackupAsync(cancellationToken); } /// <summary> /// Gets true if the key's lifetime is managed by key vault. If this is a key /// backing a certificate, then managed will be true. /// </summary> bool Microsoft.Azure.Management.KeyVault.Fluent.IKey.Managed { get { return this.Managed(); } } /// <summary> /// Unwraps a symmetric key wrapped originally by this Key Vault key. /// </summary> /// <param name="algorithm">The JWK encryption algorithm.</param> /// <param name="key">The key to unwrap.</param> /// <return>The unwrapped symmetric key.</return> byte[] Microsoft.Azure.Management.KeyVault.Fluent.IKey.UnwrapKey(JsonWebKeyEncryptionAlgorithm algorithm, params byte[] key) { return this.UnwrapKey(algorithm, key); } /// <summary> /// Creates a signature from a digest. /// </summary> /// <param name="algorithm">The JWK signing algorithm.</param> /// <param name="digest">The content to be signed.</param> /// <return>The signature in a byte[] array.</return> byte[] Microsoft.Azure.Management.KeyVault.Fluent.IKey.Sign(JsonWebKeySignatureAlgorithm algorithm, params byte[] digest) { return this.Sign(algorithm, digest); } /// <summary> /// Decrypts a single block of encrypted data. /// </summary> /// <param name="algorithm">The JWK encryption algorithm.</param> /// <param name="content">The content to be decrypted.</param> /// <return>The decrypted value.</return> async Task<byte[]> Microsoft.Azure.Management.KeyVault.Fluent.IKey.DecryptAsync(JsonWebKeyEncryptionAlgorithm algorithm, byte[] content, CancellationToken cancellationToken) { return await this.DecryptAsync(algorithm, content, cancellationToken); } /// <return>A list of individual key versions with the same key name.</return> System.Collections.Generic.IEnumerable<Microsoft.Azure.Management.KeyVault.Fluent.IKey> Microsoft.Azure.Management.KeyVault.Fluent.IKey.ListVersions() { return this.ListVersions() as System.Collections.Generic.IEnumerable<Microsoft.Azure.Management.KeyVault.Fluent.IKey>; } /// <summary> /// Specifies the size of the key to create. /// </summary> /// <param name="size">The size of the key in integer.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.UpdateWithCreate.IUpdateWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IWithKeySize.WithKeySize(int size) { return this.WithKeySize(size) as Microsoft.Azure.Management.KeyVault.Fluent.Key.UpdateWithCreate.IUpdateWithCreate; } /// <summary> /// Specifies the size of the key to create. /// </summary> /// <param name="size">The size of the key in integer.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithKeySize.WithKeySize(int size) { return this.WithKeySize(size) as Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithCreate; } /// <summary> /// Specifies whether to store the key in hardware security modules. /// </summary> /// <param name="isHsm">Store in Hsm if true.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.UpdateWithImport.IUpdateWithImport Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IWithHsm.WithHsm(bool isHsm) { return this.WithHsm(isHsm) as Microsoft.Azure.Management.KeyVault.Fluent.Key.UpdateWithImport.IUpdateWithImport; } /// <summary> /// Specifies whether to store the key in hardware security modules. /// </summary> /// <param name="isHsm">Store in Hsm if true.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithImport Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithHsm.WithHsm(bool isHsm) { return this.WithHsm(isHsm) as Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithImport; } /// <summary> /// Specifies the attributes of the key. /// </summary> /// <param name="attributes">The object attributes managed by Key Vault service.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IWithAttributes.WithAttributes(Attributes attributes) { return this.WithAttributes(attributes) as Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IUpdate; } /// <summary> /// Specifies the attributes of the key. /// </summary> /// <param name="attributes">The object attributes managed by Key Vault service.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithAttributes.WithAttributes(Attributes attributes) { return this.WithAttributes(attributes) as Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithCreate; } /// <summary> /// Specifies an existing key to import as a new version. /// </summary> /// <param name="key">The existing JWK to import.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.UpdateWithImport.IUpdateWithImport Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IWithKey.WithLocalKeyToImport(Microsoft.Azure.KeyVault.WebKey.JsonWebKey key) { return this.WithLocalKeyToImport(key) as Microsoft.Azure.Management.KeyVault.Fluent.Key.UpdateWithImport.IUpdateWithImport; } /// <summary> /// Specifies a key type to create a new key version. /// </summary> /// <param name="keyType">The JWK type to create.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.UpdateWithCreate.IUpdateWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IWithKey.WithKeyTypeToCreate(JsonWebKeyType keyType) { return this.WithKeyTypeToCreate(keyType) as Microsoft.Azure.Management.KeyVault.Fluent.Key.UpdateWithCreate.IUpdateWithCreate; } /// <summary> /// Specifies an existing key to import. /// </summary> /// <param name="key">The existing JWK to import.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithImport Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithKey.WithLocalKeyToImport(Microsoft.Azure.KeyVault.WebKey.JsonWebKey key) { return this.WithLocalKeyToImport(key) as Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithImport; } /// <summary> /// Specifies a key type to create a new key. /// </summary> /// <param name="keyType">The JWK type to create.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithKey.WithKeyTypeToCreate(JsonWebKeyType keyType) { return this.WithKeyTypeToCreate(keyType) as Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithCreate; } /// <summary> /// Gets the resource ID string. /// </summary> string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasId.Id { get { return this.Id(); } } /// <summary> /// Specifies the tags on the key. /// </summary> /// <param name="tags">The key value pair of the tags.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IWithTags.WithTags(IDictionary<string, string> tags) { return this.WithTags(tags) as Microsoft.Azure.Management.KeyVault.Fluent.Key.Update.IUpdate; } /// <summary> /// Specifies the tags on the key. /// </summary> /// <param name="tags">The key value pair of the tags.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithTags.WithTags(IDictionary<string, string> tags) { return this.WithTags(tags) as Microsoft.Azure.Management.KeyVault.Fluent.Key.Definition.IWithCreate; } } }
/*************************************************************************************************************************************** * 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 * ***************************************************************************************************************************************/ //#define debug_output using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Drawing; using System.Text.RegularExpressions; using System.ComponentModel; using MLifter.DAL.Interfaces; using System.Xml; using System.Diagnostics; using MLifter.DAL.Properties; using System.Runtime.InteropServices; using System.Reflection; using MLifter.DAL.Tools; using System.Data.SqlServerCe; using MLifter.DAL.DB.MsSqlCe; using MLifter.DAL.DB; namespace MLifter.DAL { /// <summary> /// Deifferent database types /// </summary> public enum DatabaseType { /// <summary> /// The database type is an normal xml file (.odx). /// </summary> Xml, /// <summary> /// The database type is a PostgreSql-Server. /// </summary> PostgreSQL, /// <summary> /// The Connection is a (local) unc-path. /// </summary> Unc, /// <summary> /// The Database type is a Microsoft SQL Compact Edition. /// </summary> MsSqlCe, /// <summary> /// The Connection is to a WebService. /// </summary> Web } /// <summary> /// Database helpers. /// </summary> public class Helper { /// <summary> /// The different fields of a card. /// </summary> public enum CardFields { /// <summary> /// The Question field. /// </summary> Question, /// <summary> /// The Question Audio field. /// </summary> QuestionAudio, /// <summary> /// The Question Image field. /// </summary> QuestionImage, /// <summary> /// The Question Video field. /// </summary> QuestionVideo, /// <summary> /// The Question Example field. /// </summary> QuestionExample, /// <summary> /// The Question Example Audio field. /// </summary> QuestionExampleAudio, /// <summary> /// The Answer field. /// </summary> Answer, /// <summary> /// The Answer Audio field. /// </summary> AnswerAudio, /// <summary> /// The Answer Image field. /// </summary> AnswerImage, /// <summary> /// The Answer Video field. /// </summary> AnswerVideo, /// <summary> /// The Answer Example field. /// </summary> AnswerExample, /// <summary> /// The Answer Example Audio field. /// </summary> AnswerExampleAudio, } /// <summary> /// Commentary sound names /// </summary> public static readonly string[] CommentarySoundNames = new string[12] { "commentary_q_sa_correct", "commentary_q_sa_wrong", "commentary_q_sa_almost", "commentary_q_correct", "commentary_q_wrong", "commentary_q_almost", "commentary_a_sa_correct", "commentary_a_sa_wrong", "commentary_a_sa_almost", "commentary_a_correct", "commentary_a_wrong", "commentary_a_almost" }; private static Regex regEx = new Regex(@"A=(?<AV>\d{1,3}),\s*R=(?<RV>\d{1,3}),\s*G=(?<GV>\d{1,3}),\s*B=(?<BV>\d{1,3})"); private static Regex regExColorNameMatch = new Regex(@"\[(?<NAME>\w+)\]"); /// <summary> /// Parses the specified string read form the XML and returns the value /// it represents as the specified type. /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2007-08-08</remarks> public static object GetValue(Type type, string value) { if (type == typeof(string)) { return value; } else if (type == typeof(bool)) { return Convert.ToBoolean(value); } else if (type.IsEnum) { return Enum.Parse(type, value, true); } else if (type == typeof(Color)) { Match match = regEx.Match(value); if (match.Success) return Color.FromArgb(Convert.ToInt32(match.Groups["AV"].Value), Convert.ToInt32(match.Groups["RV"].Value), Convert.ToInt32(match.Groups["GV"].Value), Convert.ToInt32(match.Groups["BV"].Value)); else { match = regExColorNameMatch.Match(value); if (match.Success) return Color.FromName(match.Groups["NAME"].Value); else return Color.Empty; } } else if (type == typeof(DateTime)) { if (value.Length == 0) { return DateTime.MinValue; } else { return DateTime.Parse(value); } } else if (type == typeof(TimeSpan)) { return TimeSpan.Parse(value); } else if (type == typeof(Int16)) { return Convert.ToInt16(value); } else if (type == typeof(Int32)) { return Convert.ToInt32(value); } else if (type == typeof(Int64)) { return Convert.ToInt64(value); } else if (type == typeof(float)) { return Convert.ToSingle(value); } else if (type == typeof(double)) { return Convert.ToDouble(value); } else if (type == typeof(decimal)) { return Convert.ToDecimal(value); } else if (type == typeof(char)) { return Convert.ToChar(value); } else if (type == typeof(byte)) { return Convert.ToByte(value); } else if (type == typeof(UInt16)) { return Convert.ToUInt16(value); } else if (type == typeof(UInt32)) { return Convert.ToUInt32(value); } else if (type == typeof(UInt64)) { return Convert.ToUInt64(value); } else if (type == typeof(Guid)) { return new Guid(value); } else { return GetFromInvariantString(type, value); } } /// <summary> /// Gets the object from the invariant string. /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2007-08-13</remarks> public static object GetFromInvariantString(Type type, string value) { TypeConverter converter = TypeDescriptor.GetConverter(type); return converter.ConvertFromInvariantString(value); } /// <summary> /// Gets the string representing the given object. /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2007-08-13</remarks> public static string GetString(Type type, object value) { if (type == typeof(string)) { return (string)value; } else if (type == typeof(bool) || type.IsEnum || type == typeof(Color) || type == typeof(DateTime) || type == typeof(TimeSpan) || type == typeof(Int16) || type == typeof(Int32) || type == typeof(Int64) || type == typeof(float) || type == typeof(double) || type == typeof(decimal) || type == typeof(char) || type == typeof(byte) || type == typeof(UInt16) || type == typeof(UInt32) || type == typeof(UInt64) || type == typeof(Guid)) { return value.ToString(); } else { return GetInvariantString(type, value); } } /// <summary> /// Gets the invariant string of the object. /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns></returns> /// <remarks> /// Documented by CFI, 2007-08-13. /// </remarks> public static string GetInvariantString(Type type, object value) { TypeConverter converter = TypeDescriptor.GetConverter(type); return converter.ConvertToInvariantString(value); } /// <summary> /// Works out which types to treat as attibutes and which the treat as child objects. /// </summary> /// <param name="type">The Type to check.</param> /// <returns>true if the Type is atomic (e.g. string, date, enum or number), false if it is arrayList compound sub-object.</returns> /// <exception cref="ArgumentNullException">Thrown if <i>type</i> is null (Nothing in Visual Basic).</exception> public static bool TypeIsAtomic(Type type) { if (type == typeof(string) || TypeIsNumeric(type) || type == typeof(bool) || type == typeof(DateTime) || type == typeof(TimeSpan) || type == typeof(char) || type == typeof(byte) || type.IsSubclassOf(typeof(Enum)) || type == typeof(Guid) || type == typeof(Color) || type == typeof(Font)) { return true; } return false; } /// <summary> /// Returns true if the specified type is one of the numeric types /// (Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal) /// </summary> /// <param name="type">The Type to check.</param> /// <returns> /// true if the specified type is one of the numeric types /// (Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal) /// </returns> public static bool TypeIsNumeric(Type type) { if (type == typeof(Int16) || type == typeof(Int32) || type == typeof(Int64) || type == typeof(float) || type == typeof(double) || type == typeof(decimal) || type == typeof(UInt16) || type == typeof(UInt32) || type == typeof(UInt64)) { return true; } return false; } /// <summary> /// Checks the name of the file if the file extension is a supported one. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2007-11-28</remarks> public static bool CheckFileName(string path) { string extension = Path.GetExtension(path).ToLower(); if ((extension == Helper.OdxExtension) || (extension == Helper.OdfExtension) || (extension == Helper.DzpExtension) || (extension == Helper.ZipExtension) || (extension == Helper.EmbeddedDbExtension) || (extension == Helper.ConfigFileExtension)) return true; return false; } /// <summary> /// Determines whether the specified path is a learning module file name. /// </summary> /// <param name="path">The path.</param> /// <returns> /// <c>true</c> if the specified path is a learning module file name; otherwise, <c>false</c>. /// </returns> public static bool IsLearningModuleFileName(string path) { string extension = Path.GetExtension(path); if ((extension == Helper.OdxExtension) || (extension == Helper.OdfExtension) || (extension == Helper.DzpExtension) || (extension == Helper.ZipExtension) || (extension == Helper.EmbeddedDbExtension)) return true; return false; } /// <summary> /// Gets the type of the media. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> /// <remarks>Documented by Dev03, 2007-08-20</remarks> public static EMedia GetMediaType(string path) { EMedia type; switch (Path.GetExtension(path).ToLower()) { case ".jpg": case ".jpeg": case ".bmp": case ".ico": case ".emf": case ".wmf": case ".gif": case ".png": type = EMedia.Image; break; case ".wav": case ".wma": case ".mp3": case ".mid": type = EMedia.Audio; break; case ".wmv": case ".avi": case ".mpg": case ".mpeg": type = EMedia.Video; break; default: type = EMedia.Unknown; break; } return type; } /// <summary> /// String for a unknown mime type. /// </summary> public const string UnknownMimeType = "application/unknown"; /// <summary> /// Gets the MIME type for a filename, using the Windows Registry. /// </summary> /// <param name="fileName">Name of the file.</param> /// <returns></returns> /// <remarks>Documented by Dev02, 2008-08-06</remarks> public static string GetMimeType(string fileName) { //TODO: Provide a less environment specific way to get the MIME type (e.g. with a table). string mimeType = UnknownMimeType; string ext = System.IO.Path.GetExtension(fileName).ToLower(); Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); if (regKey != null && regKey.GetValue("Content Type") != null) mimeType = regKey.GetValue("Content Type").ToString(); return mimeType; } /// <summary> /// Reads the media properties. /// </summary> /// <param name="path">The path.</param> /// <param name="id">The id.</param> /// <param name="mediaconnector">The mediaconnector.</param> /// <remarks> /// Documented by DAC, 2008-08-06. /// </remarks> internal static void UpdateMediaProperties(string path, int id, Interfaces.DB.IDbMediaConnector mediaconnector) { Uri uri = new Uri(path); Stream mediaStream = uri.IsFile ? null : mediaconnector.GetMediaStream(id); mediaconnector.SetPropertyValue(id, MediaProperty.MimeType, GetMimeType(path)); mediaconnector.SetPropertyValue(id, MediaProperty.Extension, Path.GetExtension(path)); mediaconnector.SetPropertyValue(id, MediaProperty.MediaSize, uri.IsFile ? new FileInfo(path).Length.ToString() : mediaStream.Length.ToString()); switch (GetMediaType(path)) { case EMedia.Audio: break; case EMedia.Video: break; case EMedia.Image: using (Image image = uri.IsFile ? Image.FromFile(path) : Image.FromStream(mediaStream)) { mediaconnector.SetPropertyValue(id, MediaProperty.Width, image.Width.ToString()); mediaconnector.SetPropertyValue(id, MediaProperty.Height, image.Height.ToString()); } break; case EMedia.Unknown: default: break; } } /// <summary> /// Gets the odx connection prefix. /// </summary> /// <value>The odx connection prefix.</value> /// <remarks>Documented by Dev05, 2009-02-20</remarks> public static string OdxConnectionPrefix { get { return Resources.DICTIONARY_ODX_CONNECTION_PREFIX; } } /// <summary> /// Gets the db postgres connection prefix. /// </summary> /// <value>The db postgres connection prefix.</value> /// <remarks>Documented by Dev05, 2009-02-20</remarks> public static string DbPostgresConnectionPrefix { get { return Resources.DICTIONARY_DB_POSTGRES_CONNECTION_PREFIX; } } /// <summary> /// Gets the dip extension. /// </summary> /// <value>The dip extension.</value> /// <remarks>Documented by Dev05, 2009-02-20</remarks> public static string DipExtension { get { return Resources.DICTIONARY_DIP_EXTENSION; } } /// <summary> /// Gets the odx extension. /// </summary> /// <value>The odx extension.</value> /// <remarks>Documented by Dev05, 2009-02-20</remarks> public static string OdxExtension { get { return Resources.DICTIONARY_ODX_EXTENSION; } } /// <summary> /// Gets the odf extension. /// </summary> /// <value>The odf extension.</value> /// <remarks>Documented by Dev05, 2009-02-20</remarks> public static string OdfExtension { get { return Resources.DICTIONARY_ODF_EXTENSION; } } /// <summary> /// Gets the DZP extension. /// </summary> /// <value>The DZP extension.</value> /// <remarks>Documented by Dev05, 2009-02-20</remarks> public static string DzpExtension { get { return Resources.DICTIONARY_ARCHIVE_EXTENSION; } } /// <summary> /// Gets the embedded db extension. /// </summary> /// <value>The embedded db extension.</value> /// <remarks>Documented by Dev05, 2009-02-20</remarks> public static string EmbeddedDbExtension { get { return Resources.DICTIONARY_EDB_EXTENSION; } } /// <summary> /// Gets the synced embedded db extension. /// </summary> /// <value>The synced embedded db extension.</value> /// <remarks>Documented by Dev05, 2009-02-20</remarks> public static string SyncedEmbeddedDbExtension { get { return Resources.DICTIONARY_SYNCED_EDB_EXTENSION1; } } /// <summary> /// Gets the zip extension. /// </summary> /// <value>The zip extension.</value> /// <remarks>Documented by Dev05, 2009-02-20</remarks> public static string ZipExtension { get { return Resources.DICTIONARY_ZIP_EXTENSION; } } /// <summary> /// Gets the config file extension. /// </summary> /// <value>The config file extension.</value> /// <remarks>Documented by Dev05, 2009-02-20</remarks> public static string ConfigFileExtension { get { return Resources.CONFIGURATION_FILE_EXTENSION; } } /// <summary> /// Determines whether [is odf format] [the specified database path]. /// </summary> /// <param name="databasePath">The database path.</param> /// <returns> /// <c>true</c> if [is odf format] [the specified database path]; otherwise, <c>false</c>. /// </returns> /// <remarks>Documented by Dev03, 2007-09-04</remarks> public static bool IsOdfFormat(string databasePath) { return Path.GetExtension(databasePath).Equals(OdfExtension, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Determines whether [is odx format] [the specified database path]. /// </summary> /// <param name="databasePath">The database path.</param> /// <returns> /// <c>true</c> if [is odx format] [the specified database path]; otherwise, <c>false</c>. /// </returns> /// <remarks>Documented by Dev10, 2009-27-02</remarks> public static bool IsOdxFormat(string databasePath) { return Path.GetExtension(databasePath).Equals(OdxExtension, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Determines whether [is embedded db format] [the specified database path]. /// </summary> /// <param name="databasePath">The database path.</param> /// <returns> /// <c>true</c> if [is embedded db format] [the specified database path]; otherwise, <c>false</c>. /// </returns> /// <remarks>Documented by Dev03, 2009-03-16</remarks> public static bool IsEmbeddedDbFormat(string databasePath) { return Path.GetExtension(databasePath).Equals(EmbeddedDbExtension, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Builds the ODX connection string. /// </summary> /// <param name="databasePath">The database path.</param> /// <returns>The connection string.</returns> /// <remarks>Documented by Dev03, 2007-09-04</remarks> public static string BuildOdxConnectionString(string databasePath) { return OdxConnectionPrefix + databasePath; } /// <summary> /// Builds the DB Postgres connection string. /// </summary> /// <param name="connectionString">The connection string.</param> /// <returns></returns> /// <remarks>Documented by Dev02, 2008-07-23</remarks> public static string BuildDbPostgresConnectionString(string connectionString) { return DbPostgresConnectionPrefix + connectionString; } /// <summary> /// Generates the XML card. /// </summary> /// <param name="card">The card.</param> /// <returns></returns> public static XmlElement GenerateXmlCard(ICard card) { StringBuilder sb = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.Unicode; settings.Indent = true; XmlWriter writer = XmlWriter.Create(sb, settings); writer.WriteStartDocument(); writer.WriteStartElement("card"); writer.WriteAttributeString("id", card.Id.ToString()); writer.WriteStartElement("answer"); if (card.Answer.Words.Count > 0) writer.WriteString(card.Answer.ToQuotedString()); writer.WriteEndElement(); writer.WriteStartElement("answerexample"); if (card.AnswerExample.Words.Count > 0) writer.WriteString(card.AnswerExample.ToString()); writer.WriteEndElement(); writer.WriteStartElement("answerdistractors"); foreach (IWord distractor in card.AnswerDistractors.Words) { writer.WriteStartElement("distractor"); writer.WriteAttributeString("id", distractor.Id.ToString()); writer.WriteString(distractor.Word); writer.WriteEndElement(); } writer.WriteEndElement(); foreach (IMedia media in card.AnswerMedia) { if (!media.Active.GetValueOrDefault()) continue; if (media is IAudio) { if (media.Example.GetValueOrDefault()) { writer.WriteStartElement("answerexampleaudio"); writer.WriteString(media.Filename); writer.WriteEndElement(); } else { writer.WriteStartElement("answeraudio"); if (media.Default.GetValueOrDefault()) writer.WriteAttributeString("id", "std"); writer.WriteString(media.Filename); writer.WriteEndElement(); } } if (media is IImage) { writer.WriteStartElement("answerimage"); writer.WriteAttributeString("width", (media as IImage).Width.ToString()); writer.WriteAttributeString("height", (media as IImage).Height.ToString()); writer.WriteString(media.Filename); writer.WriteEndElement(); } if (media is IVideo) { writer.WriteStartElement("answervideo"); writer.WriteString(media.Filename); writer.WriteEndElement(); } } writer.WriteStartElement("question"); if (card.Question.Words.Count > 0) writer.WriteString(card.Question.ToQuotedString()); writer.WriteEndElement(); writer.WriteStartElement("questionexample"); if (card.QuestionExample.Words.Count > 0) writer.WriteString(card.QuestionExample.ToString()); writer.WriteEndElement(); writer.WriteStartElement("questiondistractors"); foreach (IWord distractor in card.QuestionDistractors.Words) { writer.WriteStartElement("distractor"); writer.WriteAttributeString("id", distractor.Id.ToString()); writer.WriteString(distractor.Word); writer.WriteEndElement(); } writer.WriteEndElement(); foreach (IMedia media in card.QuestionMedia) { if (!media.Active.GetValueOrDefault()) continue; if (media is IAudio) { if (media.Example.GetValueOrDefault()) { writer.WriteStartElement("questionexampleaudio"); writer.WriteString(media.Filename); writer.WriteEndElement(); } else { writer.WriteStartElement("questionaudio"); if (media.Default.GetValueOrDefault()) writer.WriteAttributeString("id", "std"); writer.WriteString(media.Filename); writer.WriteEndElement(); } } if (media is IImage) { writer.WriteStartElement("questionimage"); writer.WriteAttributeString("width", (media as IImage).Width.ToString()); writer.WriteAttributeString("height", (media as IImage).Height.ToString()); writer.WriteString(media.Filename); writer.WriteEndElement(); } if (media is IVideo) { writer.WriteStartElement("questionvideo"); writer.WriteString(media.Filename); writer.WriteEndElement(); } } writer.WriteStartElement("chapter"); writer.WriteString(card.Chapter.ToString()); writer.WriteEndElement(); writer.WriteStartElement("box"); writer.WriteString(card.Box.ToString()); writer.WriteEndElement(); writer.WriteStartElement("timestamp"); writer.WriteString(XmlConvert.ToString(card.Timestamp, XmlDateTimeSerializationMode.RoundtripKind)); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); XmlDocument doc = new XmlDocument(); string xml = sb.ToString(); try { doc.LoadXml(xml); } catch (Exception e) { Debug.WriteLine(e.Message); } return doc.DocumentElement; } /// <summary> /// Splits the word list. /// </summary> /// <param name="wordList">The word list.</param> /// <returns></returns> /// <remarks>Documented by Dev03, 2007-09-28</remarks> public static string[] SplitWordList(string wordList) { string[] words; if (wordList != null) { //wordList = wordList.Trim(new char[] { ',', ' ' }); if (wordList.Length > 0) { words = wordList.Split(new string[] { "\",\"", "\", \"" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < words.Length; i++) { words[i] = words[i].Trim(); } //remove trailing and leading '"' which is used to enclose synonym text if (words.Length > 0) { if (words[0].StartsWith("\"")) words[0] = words[0].Substring(1); if (words[words.Length - 1].EndsWith("\"")) words[words.Length - 1] = words[words.Length - 1].Substring(0, words[words.Length - 1].Length - 1); } //decode some protected chars ('"' and ',') for (int i = 0; i < words.Length; i++) { words[i] = words[i].Replace("\"\"", "\"").Replace("\\,", ","); } } else { words = new string[] { }; } } else { words = new string[] { }; } return words; } /// <summary> /// Converts the array To a quoted comma string. /// </summary> /// <param name="wordsToQuote">The words to quote.</param> /// <returns></returns> public static string ToQuotedCommaString(string[] wordsToQuote) { string[] words = (string[])wordsToQuote.Clone(); //encode some protected chars ('"' and ',') for (int i = 0; i < words.Length; i++) { words[i] = words[i].Replace("\"", "\"\"").Replace(",", "\\,"); } return "\"" + String.Join("\", \"", words) + "\""; } /// <summary> /// Finds all files in all subfolders in a recursive way. /// </summary> /// <param name="path">The path.</param> /// <param name="searchPattern">The search pattern.</param> /// <returns>The found file list.</returns> /// <remarks>Documented by Dev02, 2008-12-18</remarks> public static string[] GetFilesRecursive(string path, string searchPattern) { List<string> files = new List<string>(); try { if (!Directory.Exists(path)) return new string[0]; #if DEBUG && debug_output Debug.WriteLine("Scanning directory (for " + searchPattern + ") " + path); #endif foreach (string file in Directory.GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly)) files.Add(file); foreach (string directory in Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly)) files.AddRange(GetFilesRecursive(directory, searchPattern)); } catch (Exception exp) { System.Diagnostics.Trace.WriteLine("Could not access directory " + path + " because: " + exp.Message); } return files.ToArray(); } /// <summary> /// Gets the ms SQL ce script. /// </summary> /// <returns></returns> /// <remarks>Documented by Dev08, 2009-01-13</remarks> public static string GetMsSqlCeScript() { return Resources.MsSqlCeDbCreateScript; } /// <summary> /// Occurs when the save copy to progress changed. /// </summary> public static event StatusMessageEventHandler SaveCopyToProgressChanged; /// <summary> /// Saves the copy to. /// </summary> /// <param name="source">The source.</param> /// <param name="destination">The destination.</param> /// <param name="overwrite">if set to <c>true</c> [overwrite].</param> /// <returns></returns> /// <remarks>Documented by Dev09, 2009-03-06</remarks> public static bool SaveCopyTo(string source, string destination, bool overwrite) { //StreamReader reader = new StreamReader(source); //StreamWriter writer = new StreamWriter(destination, false); int nBytes = 2048; byte[] data = new byte[nBytes]; using (FileStream writer = new FileStream(destination, FileMode.Create, FileAccess.ReadWrite, FileShare.Read)) using (FileStream reader = new FileStream(source, FileMode.Open, FileAccess.Read)) { StatusMessageEventArgs args = new StatusMessageEventArgs(StatusMessageType.SaveAsProgress, (int)reader.Length); int counter = 0; while ((nBytes = reader.Read(data, 0, data.Length)) > 0) { writer.Write(data, 0, nBytes); args.Progress = counter++ * data.Length; ReportSaveCopyToProgress(args); } reader.Close(); writer.Close(); } return false; } private static void ReportSaveCopyToProgress(StatusMessageEventArgs args) { if (SaveCopyToProgressChanged != null) SaveCopyToProgressChanged(null, args); } /// <summary> /// Filters the invalid filename characters. /// </summary> /// <param name="filename">The filename.</param> /// <returns></returns> /// <remarks>Documented by Dev02, 2009-06-25</remarks> public static string FilterInvalidFilenameCharacters(string filename) { Match match = Regex.Match(filename, @"(?'drive'[a-z]{1}:\\)(?'filepath'.*)", RegexOptions.IgnoreCase); if (!match.Success) return filename; string drive = match.Groups["drive"].Value; string filepath = match.Groups["filepath"].Value; List<Char> filterChars = new List<char>(Path.GetInvalidPathChars()); filterChars.Add(':'); filterChars.Add('?'); filterChars.Add(';'); //to avoid connectionstring parse issues filterChars.Add('/'); //only backslash allowed filepath = Regex.Replace(filepath, "[" + Regex.Escape(new string(filterChars.ToArray())) + "]", "_"); return drive + filepath; } } /// <summary> /// Novell DLL-references. /// </summary> public class IcNovell { /// <summary> /// NWs the calls init. /// </summary> /// <param name="reserved1">The reserved1.</param> /// <param name="reserved2">The reserved2.</param> /// <returns></returns> [DllImport("calwin32.dll")] public static extern int NWCallsInit(byte reserved1, byte reserved2); /// <summary> /// Create the NWDS context handle. /// </summary> /// <param name="context">The context.</param> /// <returns></returns> [DllImport("netwin32.dll", EntryPoint = "NWDSCreateContextHandle")] public static extern int NWDSCreateContextHandle(ref int context); /// <summary> /// Who am I in NWDS. /// </summary> /// <param name="context">The context.</param> /// <param name="NovellUserId">The novell user id.</param> /// <returns></returns> [DllImport("netwin32.dll", EntryPoint = "NWDSWhoAmI")] public static extern int NWDSWhoAmI(int context, StringBuilder NovellUserId); /// <summary> /// Free the context. /// </summary> /// <param name="context">The context.</param> /// <returns></returns> [DllImport("netwin32.dll", EntryPoint = "NWDSFreeContext")] public static extern int NWDSFreeContext(int context); } /// <summary> /// EventHandler for the BackupCompleted Event. /// </summary> public delegate void BackupCompletedEventHandler(object sender, BackupCompletedEventArgs args); /// <summary> /// EventArgs for the BackupCompleted Event. /// </summary> /// <remarks>Documented by Dev02, 2008-09-08</remarks> public class BackupCompletedEventArgs : EventArgs { string backupFilename = string.Empty; /// <summary> /// Gets or sets the backup filename. /// </summary> /// <value>The backup filename.</value> /// <remarks>Documented by Dev02, 2008-09-08</remarks> public string BackupFilename { get { return backupFilename; } set { backupFilename = value; } } } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; namespace PCSComUtils.Common.DS { public class Sys_PostdateConfigurationDS { public Sys_PostdateConfigurationDS() { } private const string THIS = "PCSComUtils.Common.DS.DS.Sys_PostdateConfigurationDS"; //************************************************************************** /// <Description> /// This method uses to add data to Sys_PostdateConfiguration /// </Description> /// <Inputs> /// Sys_PostdateConfigurationVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// Code generate /// </Authors> /// <History> /// Monday, September 18, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Sys_PostdateConfigurationVO objObject = (Sys_PostdateConfigurationVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql = "INSERT INTO Sys_PostdateConfiguration(" + Sys_PostdateConfigurationTable.DAYBEFORE_FLD + "," + Sys_PostdateConfigurationTable.LASTUPDATED_FLD + "," + Sys_PostdateConfigurationTable.USERNAME_FLD + ")" + "VALUES(?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PostdateConfigurationTable.DAYBEFORE_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_PostdateConfigurationTable.DAYBEFORE_FLD].Value = objObject.DayBefore; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PostdateConfigurationTable.LASTUPDATED_FLD, OleDbType.Date)); ocmdPCS.Parameters[Sys_PostdateConfigurationTable.LASTUPDATED_FLD].Value = objObject.LastUpdated; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PostdateConfigurationTable.USERNAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_PostdateConfigurationTable.USERNAME_FLD].Value = objObject.Username; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from Sys_PostdateConfiguration /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// Code generate /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql = "DELETE " + Sys_PostdateConfigurationTable.TABLE_NAME + " WHERE " + "PostdateConfigurationID" + "=" + pintID.ToString(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from Sys_PostdateConfiguration /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// Sys_PostdateConfigurationVO /// </Outputs> /// <Returns> /// Sys_PostdateConfigurationVO /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// Monday, September 18, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + Sys_PostdateConfigurationTable.POSTDATECONFIGURATIONID_FLD + "," + Sys_PostdateConfigurationTable.DAYBEFORE_FLD + "," + Sys_PostdateConfigurationTable.LASTUPDATED_FLD + "," + Sys_PostdateConfigurationTable.USERNAME_FLD + " FROM " + Sys_PostdateConfigurationTable.TABLE_NAME + " WHERE " + Sys_PostdateConfigurationTable.POSTDATECONFIGURATIONID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); Sys_PostdateConfigurationVO objObject = new Sys_PostdateConfigurationVO(); while (odrPCS.Read()) { objObject.PostdateConfigurationID = int.Parse(odrPCS[Sys_PostdateConfigurationTable.POSTDATECONFIGURATIONID_FLD].ToString()); objObject.DayBefore = int.Parse(odrPCS[Sys_PostdateConfigurationTable.DAYBEFORE_FLD].ToString()); objObject.LastUpdated = DateTime.Parse(odrPCS[Sys_PostdateConfigurationTable.LASTUPDATED_FLD].ToString()); objObject.Username = odrPCS[Sys_PostdateConfigurationTable.USERNAME_FLD].ToString(); } return objObject; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to Sys_PostdateConfiguration /// </Description> /// <Inputs> /// Sys_PostdateConfigurationVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; Sys_PostdateConfigurationVO objObject = (Sys_PostdateConfigurationVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql = "UPDATE Sys_PostdateConfiguration SET " + Sys_PostdateConfigurationTable.DAYBEFORE_FLD + "= ?" + "," + Sys_PostdateConfigurationTable.LASTUPDATED_FLD + "= ?" + "," + Sys_PostdateConfigurationTable.USERNAME_FLD + "= ?" + " WHERE " + Sys_PostdateConfigurationTable.POSTDATECONFIGURATIONID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PostdateConfigurationTable.DAYBEFORE_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_PostdateConfigurationTable.DAYBEFORE_FLD].Value = objObject.DayBefore; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PostdateConfigurationTable.LASTUPDATED_FLD, OleDbType.Date)); ocmdPCS.Parameters[Sys_PostdateConfigurationTable.LASTUPDATED_FLD].Value = objObject.LastUpdated; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PostdateConfigurationTable.USERNAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_PostdateConfigurationTable.USERNAME_FLD].Value = objObject.Username; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PostdateConfigurationTable.POSTDATECONFIGURATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_PostdateConfigurationTable.POSTDATECONFIGURATIONID_FLD].Value = objObject.PostdateConfigurationID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from Sys_PostdateConfiguration /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// Monday, September 18, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + Sys_PostdateConfigurationTable.POSTDATECONFIGURATIONID_FLD + "," + Sys_PostdateConfigurationTable.DAYBEFORE_FLD + "," + Sys_PostdateConfigurationTable.LASTUPDATED_FLD + "," + Sys_PostdateConfigurationTable.USERNAME_FLD + " FROM " + Sys_PostdateConfigurationTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, Sys_PostdateConfigurationTable.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DataSet List(PostDateConfigPurpose enmPurpose) { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + Sys_PostdateConfigurationTable.POSTDATECONFIGURATIONID_FLD + "," + Sys_PostdateConfigurationTable.DAYBEFORE_FLD + "," + Sys_PostdateConfigurationTable.LASTUPDATED_FLD + "," + Sys_PostdateConfigurationTable.PURPOSE_FLD + "," + Sys_PostdateConfigurationTable.USERNAME_FLD + " FROM " + Sys_PostdateConfigurationTable.TABLE_NAME + " WHERE " + Sys_PostdateConfigurationTable.PURPOSE_FLD + "=?"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.Parameters.Add(new OleDbParameter(Sys_PostdateConfigurationTable.PURPOSE_FLD, OleDbType.VarWChar)).Value = enmPurpose.ToString(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, Sys_PostdateConfigurationTable.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// Monday, September 18, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS = null; OleDbCommandBuilder odcbPCS; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql = "SELECT " + Sys_PostdateConfigurationTable.POSTDATECONFIGURATIONID_FLD + "," + Sys_PostdateConfigurationTable.DAYBEFORE_FLD + "," + Sys_PostdateConfigurationTable.LASTUPDATED_FLD + "," + Sys_PostdateConfigurationTable.USERNAME_FLD; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData, Sys_PostdateConfigurationTable.TABLE_NAME); } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
// Copyright 2018, Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using FirebaseAdmin.Auth; using FirebaseAdmin.Auth.Hash; using FirebaseAdmin.Auth.Providers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace FirebaseAdmin.Snippets { internal class FirebaseAuthSnippets { internal static async Task CreateCustomTokenAsync() { // [START custom_token] var uid = "some-uid"; string customToken = await FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(uid); // Send token back to client // [END custom_token] Console.WriteLine("Created custom token: {0}", customToken); } internal static async Task CreateCustomTokenWithClaimsAsync() { // [START custom_token_with_claims] var uid = "some-uid"; var additionalClaims = new Dictionary<string, object>() { { "premiumAccount", true }, }; string customToken = await FirebaseAuth.DefaultInstance .CreateCustomTokenAsync(uid, additionalClaims); // Send token back to client // [END custom_token_with_claims] Console.WriteLine("Created custom token: {0}", customToken); } internal static async Task VeridyIdTokenAsync(string idToken) { // [START verify_id_token] FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance .VerifyIdTokenAsync(idToken); string uid = decodedToken.Uid; // [END verify_id_token] Console.WriteLine("Decoded ID token from user: {0}", uid); } internal static async Task GetUserAsync(string uid) { // [START get_user_by_id] UserRecord userRecord = await FirebaseAuth.DefaultInstance.GetUserAsync(uid); // See the UserRecord reference doc for the contents of userRecord. Console.WriteLine($"Successfully fetched user data: {userRecord.Uid}"); // [END get_user_by_id] } internal static async Task GetUserByEmailAsync(string email) { // [START get_user_by_email] UserRecord userRecord = await FirebaseAuth.DefaultInstance.GetUserByEmailAsync(email); // See the UserRecord reference doc for the contents of userRecord. Console.WriteLine($"Successfully fetched user data: {userRecord.Uid}"); // [END get_user_by_email] } internal static async Task GetUserByPhoneNumberAsync(string phoneNumber) { // [START get_user_by_phone] UserRecord userRecord = await FirebaseAuth.DefaultInstance.GetUserByPhoneNumberAsync(phoneNumber); // See the UserRecord reference doc for the contents of userRecord. Console.WriteLine($"Successfully fetched user data: {userRecord.Uid}"); // [END get_user_by_phone] } internal static async Task GetUsersAsync() { // [START bulk_get_users] GetUsersResult result = await FirebaseAuth.DefaultInstance.GetUsersAsync( new List<UserIdentifier> { new UidIdentifier("uid1"), new EmailIdentifier("user2@example.com"), new PhoneIdentifier("+15555550003"), new ProviderIdentifier("google.com", "google_uid4"), }); Console.WriteLine("Successfully fetched user data:"); foreach (UserRecord user in result.Users) { Console.WriteLine($"User: {user.Uid}"); } Console.WriteLine("Unable to find users corresponding to these identifiers:"); foreach (UserIdentifier uid in result.NotFound) { Console.WriteLine($"{uid}"); } // [END bulk_get_users] } internal static async Task CreateUserAsync() { // [START create_user] UserRecordArgs args = new UserRecordArgs() { Email = "user@example.com", EmailVerified = false, PhoneNumber = "+11234567890", Password = "secretPassword", DisplayName = "John Doe", PhotoUrl = "http://www.example.com/12345678/photo.png", Disabled = false, }; UserRecord userRecord = await FirebaseAuth.DefaultInstance.CreateUserAsync(args); // See the UserRecord reference doc for the contents of userRecord. Console.WriteLine($"Successfully created new user: {userRecord.Uid}"); // [END create_user] } internal static async Task CreateUserWithUidAsync() { // [START create_user_with_uid] UserRecordArgs args = new UserRecordArgs() { Uid = "some-uid", Email = "user@example.com", PhoneNumber = "+11234567890", }; UserRecord userRecord = await FirebaseAuth.DefaultInstance.CreateUserAsync(args); // See the UserRecord reference doc for the contents of userRecord. Console.WriteLine($"Successfully created new user: {userRecord.Uid}"); // [END create_user_with_uid] } internal static async Task ImportUsers() { // [START build_user_list] // Up to 1000 users can be imported at once. var users = new List<ImportUserRecordArgs>() { new ImportUserRecordArgs() { Uid = "uid1", Email = "user1@example.com", PasswordHash = Encoding.ASCII.GetBytes("passwordHash1"), PasswordSalt = Encoding.ASCII.GetBytes("salt1"), }, new ImportUserRecordArgs() { Uid = "uid2", Email = "user2@example.com", PasswordHash = Encoding.ASCII.GetBytes("passwordHash2"), PasswordSalt = Encoding.ASCII.GetBytes("salt2"), }, }; // [END build_user_list] // [START import_users] var options = new UserImportOptions() { Hash = new HmacSha256() { Key = Encoding.ASCII.GetBytes("secretKey"), }, }; try { UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); Console.WriteLine($"Successfully imported {result.SuccessCount} users"); Console.WriteLine($"Failed to import {result.FailureCount} users"); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user at index: {indexedError.Index}" + $" due to error: {indexedError.Reason}"); } } catch (FirebaseAuthException) { // Some unrecoverable error occurred that prevented the operation from running. } // [END import_users] } internal static async Task ImportWithHmac() { // [START import_with_hmac] try { var users = new List<ImportUserRecordArgs>() { new ImportUserRecordArgs() { Uid = "some-uid", Email = "user@example.com", PasswordHash = Encoding.ASCII.GetBytes("password-hash"), PasswordSalt = Encoding.ASCII.GetBytes("salt"), }, }; var options = new UserImportOptions() { Hash = new HmacSha256() { Key = Encoding.ASCII.GetBytes("secret"), }, }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } // [END import_with_hmac] } internal static async Task ImportWithPbkdf() { // [START import_with_pbkdf] try { var users = new List<ImportUserRecordArgs>() { new ImportUserRecordArgs() { Uid = "some-uid", Email = "user@example.com", PasswordHash = Encoding.ASCII.GetBytes("password-hash"), PasswordSalt = Encoding.ASCII.GetBytes("salt"), }, }; var options = new UserImportOptions() { Hash = new Pbkdf2Sha256() { Rounds = 100000, }, }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } // [END import_with_pbkdf] } internal static async Task ImportWithStandardScrypt() { // [START import_with_standard_scrypt] try { var users = new List<ImportUserRecordArgs>() { new ImportUserRecordArgs() { Uid = "some-uid", Email = "user@example.com", PasswordHash = Encoding.ASCII.GetBytes("password-hash"), PasswordSalt = Encoding.ASCII.GetBytes("salt"), }, }; var options = new UserImportOptions() { Hash = new StandardScrypt() { MemoryCost = 1024, Parallelization = 16, BlockSize = 8, DerivedKeyLength = 64, }, }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } // [END import_with_standard_scrypt] } internal static async Task ImportWithBcrypt() { // [START import_with_bcrypt] try { var users = new List<ImportUserRecordArgs>() { new ImportUserRecordArgs() { Uid = "some-uid", Email = "user@example.com", PasswordHash = Encoding.ASCII.GetBytes("password-hash"), PasswordSalt = Encoding.ASCII.GetBytes("salt"), }, }; var options = new UserImportOptions() { Hash = new Bcrypt(), }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } // [END import_with_bcrypt] } internal static async Task ImportWithScrypt() { // [START import_with_scrypt] try { var users = new List<ImportUserRecordArgs>() { new ImportUserRecordArgs() { Uid = "some-uid", Email = "user@example.com", PasswordHash = Encoding.ASCII.GetBytes("password-hash"), PasswordSalt = Encoding.ASCII.GetBytes("salt"), }, }; var options = new UserImportOptions() { // All the parameters below can be obtained from the Firebase Console's "Users" // section. Base64 encoded parameters must be decoded into raw bytes. Hash = new Scrypt() { Key = Encoding.ASCII.GetBytes("base64-secret"), SaltSeparator = Encoding.ASCII.GetBytes("base64-salt-separator"), Rounds = 8, MemoryCost = 14, }, }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } // [END import_with_scrypt] } internal static async Task ImportWithoutPassword() { // [START import_without_password] try { var users = new List<ImportUserRecordArgs>() { new ImportUserRecordArgs() { Uid = "some-uid", DisplayName = "John Doe", Email = "johndoe@gmail.com", PhotoUrl = "http://www.example.com/12345678/photo.png", EmailVerified = true, PhoneNumber = "+11234567890", CustomClaims = new Dictionary<string, object>() { { "admin", true }, // set this user as admin }, UserProviders = new List<UserProvider> { new UserProvider() // user with Google provider { Uid = "google-uid", Email = "johndoe@gmail.com", DisplayName = "John Doe", PhotoUrl = "http://www.example.com/12345678/photo.png", ProviderId = "google.com", }, }, }, }; UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users); foreach (ErrorInfo indexedError in result.Errors) { Console.WriteLine($"Failed to import user: {indexedError.Reason}"); } } catch (FirebaseAuthException e) { Console.WriteLine($"Error importing users: {e.Message}"); } // [END import_without_password] } internal static async Task UpdateUserAsync(string uid) { // [START update_user] UserRecordArgs args = new UserRecordArgs() { Uid = uid, Email = "modifiedUser@example.com", PhoneNumber = "+11234567890", EmailVerified = true, Password = "newPassword", DisplayName = "Jane Doe", PhotoUrl = "http://www.example.com/12345678/photo.png", Disabled = true, }; UserRecord userRecord = await FirebaseAuth.DefaultInstance.UpdateUserAsync(args); // See the UserRecord reference doc for the contents of userRecord. Console.WriteLine($"Successfully updated user: {userRecord.Uid}"); // [END update_user] } internal static async Task DeleteUserAsync(string uid) { // [START delete_user] await FirebaseAuth.DefaultInstance.DeleteUserAsync(uid); Console.WriteLine("Successfully deleted user."); // [END delete_user] } internal static async Task DeleteUsersAsync() { // [START bulk_delete_users] DeleteUsersResult result = await FirebaseAuth.DefaultInstance.DeleteUsersAsync(new List<string> { "uid1", "uid2", "uid3", }); Console.WriteLine($"Successfully deleted {result.SuccessCount} users."); Console.WriteLine($"Failed to delete {result.FailureCount} users."); foreach (ErrorInfo err in result.Errors) { Console.WriteLine($"Error #{err.Index}, reason: {err.Reason}"); } // [END bulk_delete_users] } internal static async Task ListAllUsersAsync() { // [START list_all_users] // Start listing users from the beginning, 1000 at a time. var pagedEnumerable = FirebaseAuth.DefaultInstance.ListUsersAsync(null); var responses = pagedEnumerable.AsRawResponses().GetAsyncEnumerator(); while (await responses.MoveNextAsync()) { ExportedUserRecords response = responses.Current; foreach (ExportedUserRecord user in response.Users) { Console.WriteLine($"User: {user.Uid}"); } } // Iterate through all users. This will still retrieve users in batches, // buffering no more than 1000 users in memory at a time. var enumerator = FirebaseAuth.DefaultInstance.ListUsersAsync(null).GetAsyncEnumerator(); while (await enumerator.MoveNextAsync()) { ExportedUserRecord user = enumerator.Current; Console.WriteLine($"User: {user.Uid}"); } // [END list_all_users] } internal static async Task SetCustomUserClaimsAsync(string uid) { // [START set_custom_user_claims] // Set admin privileges on the user corresponding to uid. var claims = new Dictionary<string, object>() { { "admin", true }, }; await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(uid, claims); // The new custom claims will propagate to the user's ID token the // next time a new one is issued. // [END set_custom_user_claims] var idToken = "id_token"; // [START verify_custom_claims] // Verify the ID token first. FirebaseToken decoded = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken); object isAdmin; if (decoded.Claims.TryGetValue("admin", out isAdmin)) { if ((bool)isAdmin) { // Allow access to requested admin resource. } } // [END verify_custom_claims] // [START read_custom_user_claims] // Lookup the user associated with the specified uid. UserRecord user = await FirebaseAuth.DefaultInstance.GetUserAsync(uid); Console.WriteLine(user.CustomClaims["admin"]); // [END read_custom_user_claims] } internal static async Task SetCustomUserClaimsScriptAsync() { // [START set_custom_user_claims_script] UserRecord user = await FirebaseAuth.DefaultInstance .GetUserByEmailAsync("user@admin.example.com"); // Confirm user is verified. if (user.EmailVerified) { var claims = new Dictionary<string, object>() { { "admin", true }, }; await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(user.Uid, claims); } // [END set_custom_user_claims_script] } internal static async Task SetCustomUserClaimsIncrementalAsync() { // [START set_custom_user_claims_incremental] UserRecord user = await FirebaseAuth.DefaultInstance .GetUserByEmailAsync("user@admin.example.com"); // Add incremental custom claims without overwriting the existing claims. object isAdmin; if (user.CustomClaims.TryGetValue("admin", out isAdmin) && (bool)isAdmin) { var claims = new Dictionary<string, object>(user.CustomClaims); // Add level. claims["level"] = 10; // Add custom claims for additional privileges. await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(user.Uid, claims); } // [END set_custom_user_claims_incremental] } internal static async Task RevokeIdTokens(string idToken) { string uid = "someUid"; // [START revoke_tokens] await FirebaseAuth.DefaultInstance.RevokeRefreshTokensAsync(uid); var user = await FirebaseAuth.DefaultInstance.GetUserAsync(uid); Console.WriteLine("Tokens revoked at: " + user.TokensValidAfterTimestamp); // [END revoke_tokens] } internal static async Task VerifyIdTokenCheckRevoked(string idToken) { // [START verify_id_token_check_revoked] try { // Verify the ID token while checking if the token is revoked by passing checkRevoked // as true. bool checkRevoked = true; var decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync( idToken, checkRevoked); // Token is valid and not revoked. string uid = decodedToken.Uid; } catch (FirebaseAuthException ex) { if (ex.AuthErrorCode == AuthErrorCode.RevokedIdToken) { // Token has been revoked. Inform the user to re-authenticate or signOut() the user. } else { // Token is invalid. } } // [END verify_id_token_check_revoked] } internal static ActionCodeSettings InitActionCodeSettings() { // [START init_action_code_settings] var actionCodeSettings = new ActionCodeSettings() { Url = "https://www.example.com/checkout?cartId=1234", HandleCodeInApp = true, IosBundleId = "com.example.ios", AndroidPackageName = "com.example.android", AndroidInstallApp = true, AndroidMinimumVersion = "12", DynamicLinkDomain = "coolapp.page.link", }; // [END init_action_code_settings] return actionCodeSettings; } internal static async Task GeneratePasswordResetLink() { var actionCodeSettings = InitActionCodeSettings(); var displayName = "Example User"; // [START password_reset_link] var email = "user@example.com"; var link = await FirebaseAuth.DefaultInstance.GeneratePasswordResetLinkAsync( email, actionCodeSettings); // Construct email verification template, embed the link and send // using custom SMTP server. SendCustomEmail(email, displayName, link); // [END password_reset_link] } internal static async Task GenerateEmailVerificationLink() { var actionCodeSettings = InitActionCodeSettings(); var displayName = "Example User"; // [START email_verification_link] var email = "user@example.com"; var link = await FirebaseAuth.DefaultInstance.GenerateEmailVerificationLinkAsync( email, actionCodeSettings); // Construct email verification template, embed the link and send // using custom SMTP server. SendCustomEmail(email, displayName, link); // [END email_verification_link] } internal static async Task GenerateSignInWithEmailLink() { var actionCodeSettings = InitActionCodeSettings(); var displayName = "Example User"; // [START sign_in_with_email_link] var email = "user@example.com"; var link = await FirebaseAuth.DefaultInstance.GenerateSignInWithEmailLinkAsync( email, actionCodeSettings); // Construct email verification template, embed the link and send // using custom SMTP server. SendCustomEmail(email, displayName, link); // [END sign_in_with_email_link] } internal static async Task CreateSamlProviderConfig() { // [START create_saml_provider] var args = new SamlProviderConfigArgs() { DisplayName = "SAML provider name", Enabled = true, ProviderId = "saml.myProvider", IdpEntityId = "IDP_ENTITY_ID", SsoUrl = "https://example.com/saml/sso/1234/", X509Certificates = new List<string>() { "-----BEGIN CERTIFICATE-----\nCERT1...\n-----END CERTIFICATE-----", "-----BEGIN CERTIFICATE-----\nCERT2...\n-----END CERTIFICATE-----", }, RpEntityId = "RP_ENTITY_ID", CallbackUrl = "https://project-id.firebaseapp.com/__/auth/handler", }; SamlProviderConfig saml = await FirebaseAuth.DefaultInstance .CreateProviderConfigAsync(args); Console.WriteLine($"Created new SAML provider: {saml.ProviderId}"); // [END create_saml_provider] } internal static async Task UpdateSamlProviderConfig() { // [START update_saml_provider] var args = new SamlProviderConfigArgs() { ProviderId = "saml.myProvider", X509Certificates = new List<string>() { "-----BEGIN CERTIFICATE-----\nCERT2...\n-----END CERTIFICATE-----", "-----BEGIN CERTIFICATE-----\nCERT3...\n-----END CERTIFICATE-----", }, }; SamlProviderConfig saml = await FirebaseAuth.DefaultInstance .UpdateProviderConfigAsync(args); Console.WriteLine($"Updated SAML provider: {saml.ProviderId}"); // [END update_saml_provider] } internal static async Task GetSamlProviderConfig() { // [START get_saml_provider] SamlProviderConfig saml = await FirebaseAuth.DefaultInstance .GetSamlProviderConfigAsync("saml.myProvider"); Console.WriteLine($"{saml.DisplayName}: {saml.Enabled}"); // [END get_saml_provider] } internal static async Task DeleteSamlProviderConfig() { // [START delete_saml_provider] await FirebaseAuth.DefaultInstance.DeleteProviderConfigAsync("saml.myProvider"); // [END delete_saml_provider] } internal static async Task ListSamlProviderConfigs() { // [START list_saml_providers] var listOptions = new ListProviderConfigsOptions() { PageToken = "nextPageToken", }; IAsyncEnumerator<SamlProviderConfig> enumerator = FirebaseAuth.DefaultInstance .ListSamlProviderConfigsAsync(listOptions) .GetAsyncEnumerator(); while (await enumerator.MoveNextAsync()) { SamlProviderConfig saml = enumerator.Current; Console.WriteLine(saml.ProviderId); } // [END list_saml_providers] } internal static async Task CreateOidcProviderConfig() { // [START create_oidc_provider] var args = new OidcProviderConfigArgs() { DisplayName = "OIDC provider name", Enabled = true, ProviderId = "oidc.myProvider", ClientId = "CLIENT_ID2", Issuer = "https://oidc.com/CLIENT_ID2", }; OidcProviderConfig oidc = await FirebaseAuth.DefaultInstance .CreateProviderConfigAsync(args); Console.WriteLine($"Created new OIDC provider: {oidc.ProviderId}"); // [END create_oidc_provider] } internal static async Task UpdateOidcProviderConfig() { // [START update_oidc_provider] var args = new OidcProviderConfigArgs() { DisplayName = "OIDC provider name", Enabled = true, ProviderId = "oidc.myProvider", ClientId = "CLIENT_ID", Issuer = "https://oidc.com", }; OidcProviderConfig oidc = await FirebaseAuth.DefaultInstance .UpdateProviderConfigAsync(args); Console.WriteLine($"Updated OIDC provider: {oidc.ProviderId}"); // [END update_oidc_provider] } internal static async Task GetOidcProviderConfig() { // [START get_oidc_provider] OidcProviderConfig oidc = await FirebaseAuth.DefaultInstance .GetOidcProviderConfigAsync("oidc.myProvider"); Console.WriteLine($"{oidc.DisplayName}: {oidc.Enabled}"); // [END get_oidc_provider] } internal static async Task DeleteOidcProviderConfig() { // [START delete_oidc_provider] await FirebaseAuth.DefaultInstance.DeleteProviderConfigAsync("oidc.myProvider"); // [END delete_oidc_provider] } internal static async Task ListOidcProviderConfigs() { // [START list_oidc_providers] var listOptions = new ListProviderConfigsOptions() { PageToken = "nextPageToken", }; IAsyncEnumerator<OidcProviderConfig> enumerator = FirebaseAuth.DefaultInstance .ListOidcProviderConfigsAsync(listOptions) .GetAsyncEnumerator(); while (await enumerator.MoveNextAsync()) { OidcProviderConfig oidc = enumerator.Current; Console.WriteLine(oidc.ProviderId); } // [END list_oidc_providers] } // Place holder method to make the compiler happy. This is referenced by all email action // link snippets. private static void SendCustomEmail(string email, string displayName, string link) { } public class LoginRequest { public string IdToken { get; set; } } public class SessionCookieSnippets : ControllerBase { // [START session_login] // POST: /sessionLogin [HttpPost] public async Task<ActionResult> Login([FromBody] LoginRequest request) { // Set session expiration to 5 days. var options = new SessionCookieOptions() { ExpiresIn = TimeSpan.FromDays(5), }; try { // Create the session cookie. This will also verify the ID token in the process. // The session cookie will have the same claims as the ID token. var sessionCookie = await FirebaseAuth.DefaultInstance .CreateSessionCookieAsync(request.IdToken, options); // Set cookie policy parameters as required. var cookieOptions = new CookieOptions() { Expires = DateTimeOffset.UtcNow.Add(options.ExpiresIn), HttpOnly = true, Secure = true, }; this.Response.Cookies.Append("session", sessionCookie, cookieOptions); return this.Ok(); } catch (FirebaseAuthException) { return this.Unauthorized("Failed to create a session cookie"); } } // [END session_login] // [START session_verify] // POST: /profile [HttpPost] public async Task<ActionResult> Profile() { var sessionCookie = this.Request.Cookies["session"]; if (string.IsNullOrEmpty(sessionCookie)) { // Session cookie is not available. Force user to login. return this.Redirect("/login"); } try { // Verify the session cookie. In this case an additional check is added to detect // if the user's Firebase session was revoked, user deleted/disabled, etc. var checkRevoked = true; var decodedToken = await FirebaseAuth.DefaultInstance.VerifySessionCookieAsync( sessionCookie, checkRevoked); return ViewContentForUser(decodedToken); } catch (FirebaseAuthException) { // Session cookie is invalid or revoked. Force user to login. return this.Redirect("/login"); } } // [END session_verify] // [START session_clear] // POST: /sessionLogout [HttpPost] public ActionResult ClearSessionCookie() { this.Response.Cookies.Delete("session"); return this.Redirect("/login"); } // [END session_clear] // [START session_clear_and_revoke] // POST: /sessionLogout [HttpPost] public async Task<ActionResult> ClearSessionCookieAndRevoke() { var sessionCookie = this.Request.Cookies["session"]; try { var decodedToken = await FirebaseAuth.DefaultInstance .VerifySessionCookieAsync(sessionCookie); await FirebaseAuth.DefaultInstance.RevokeRefreshTokensAsync(decodedToken.Uid); this.Response.Cookies.Delete("session"); return this.Redirect("/login"); } catch (FirebaseAuthException) { return this.Redirect("/login"); } } // [END session_clear_and_revoke] internal async Task<ActionResult> CheckAuthTime(string idToken) { // [START check_auth_time] // To ensure that cookies are set only on recently signed in users, check auth_time in // ID token before creating a cookie. var decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken); var authTime = new DateTime(1970, 1, 1).AddSeconds( (long)decodedToken.Claims["auth_time"]); // Only process if the user signed in within the last 5 minutes. if (DateTime.UtcNow - authTime < TimeSpan.FromMinutes(5)) { var options = new SessionCookieOptions() { ExpiresIn = TimeSpan.FromDays(5), }; var sessionCookie = await FirebaseAuth.DefaultInstance.CreateSessionCookieAsync( idToken, options); // Set cookie policy parameters as required. this.Response.Cookies.Append("session", sessionCookie); return this.Ok(); } // User did not sign in recently. To guard against ID token theft, require // re-authentication. return this.Unauthorized("Recent sign in required"); // [END check_auth_time] } internal async Task<ActionResult> CheckPermissions(string sessionCookie) { // [START session_verify_with_permission_check] try { var checkRevoked = true; var decodedToken = await FirebaseAuth.DefaultInstance.VerifySessionCookieAsync( sessionCookie, checkRevoked); object isAdmin; if (decodedToken.Claims.TryGetValue("admin", out isAdmin) && (bool)isAdmin) { return ViewContentForAdmin(decodedToken); } return this.Unauthorized("Insufficient permissions"); } catch (FirebaseAuthException) { // Session cookie is invalid or revoked. Force user to login. return this.Redirect("/login"); } // [END session_verify_with_permission_check] } private static ActionResult ViewContentForUser(FirebaseToken token) { return null; } private static ActionResult ViewContentForAdmin(FirebaseToken token) { return null; } } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; // ERROR: Not supported in C#: OptionDeclaration using Microsoft.VisualBasic.PowerPacks.Printing.Compatibility.VB6; namespace _4PosBackOffice.NET { internal partial class frmPrinter : System.Windows.Forms.Form { bool gSelect; List<RadioButton> optType = new List<RadioButton>(); private void loadLanguage() { modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1810; //Select a Printer|Checked if (modRecordSet.rsLang.RecordCount){this.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;this.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1811; //NOTE: Please select your printer type before clicking "next"|Checked if (modRecordSet.rsLang.RecordCount){Frame1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Frame1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1812; //A4 Printer|Checked if (modRecordSet.rsLang.RecordCount){_optType_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_optType_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1813; //Argox Printer|Checked if (modRecordSet.rsLang.RecordCount){_optType_2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_optType_2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1814; //Other barcode printer| if (modRecordSet.rsLang.RecordCount){_optType_3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_optType_3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004; //Exit|Checked if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1005; //Next|Checked if (modRecordSet.rsLang.RecordCount){cmdNext.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdNext.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmPrinter.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } public string selectPrinter() { string functionReturnValue = null; string TheSelectedPrinterStr = null; Printer Printer = new Printer(); Printer lPrn = null; ADODB.Recordset rs = default(ADODB.Recordset); Printer lPrnType = null; // ERROR: Not supported in C#: OnErrorStatement rs = modRecordSet.getRS(ref "SELECT * FROM PrinterOftenUsed"); lstPrinter.Items.Clear(); foreach (Printer lPrn_loopVariable in GlobalModule.Printers) { lPrn = lPrn_loopVariable; lstPrinter.Items.Add((lPrn.DeviceName)); } if (lstPrinter.Items.Count) { if (rs.RecordCount > 0) { lstPrinter.SelectedIndex = rs.Fields("PrinterIndex").Value; if (rs.Fields("PrinterType").Value == 0) { lPrnType = GlobalModule.Printers[lstPrinter.SelectedIndex]; if (Strings.InStr(Strings.LCase(lPrnType.DeviceName), "label")) { optType[2].Checked = true; } else if (Printer.Width <= 9000) { optType[3].Checked = true; } else { optType[1].Checked = true; } } else if (rs.Fields("PrinterType").Value > 0) { optType[rs.Fields("PrinterType").Value].Checked = true; } } else { optType[1].Checked = true; } loadLanguage(); ShowDialog(); } else { functionReturnValue = ""; optType[1].Checked = true; } if (gSelect) { functionReturnValue = Printer.DeviceName; TheSelectedPrinterStr = Printer.DeviceName; modApplication.MyNewPrLabel = functionReturnValue; } else { functionReturnValue = ""; } selectPrinterErr: // ERROR: Not supported in C#: ResumeStatement return functionReturnValue; } private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs) { this.Close(); } private void cmdNext_Click(System.Object eventSender, System.EventArgs eventArgs) { Printer Printer = new Printer(); Printer lPrinter = null; bool lPrinterName = false; //added by jonas ADODB.Recordset rs = default(ADODB.Recordset); ADODB.Recordset rst = default(ADODB.Recordset); short prnType = 0; prnType = 0; if (optType[1].Checked == true) prnType = 1; if (optType[2].Checked == true) prnType = 2; if (optType[3].Checked == true) prnType = 3; rs = new ADODB.Recordset(); rst = modRecordSet.getRS(ref "SELECT * FROM PrinterOftenUsed"); if (rst.RecordCount < 1) { rs = modRecordSet.getRS(ref "INSERT INTO PrinterOftenUsed(PrinterIndex,LabelIndex,ShelfIndex,PrinterType)VALUES(" + lstPrinter.SelectedIndex + "," + -1 + "," + -1 + "," + prnType + ")"); } else { rs = modRecordSet.getRS(ref "SELECT * FROM PrinterOftenUsed"); rs = modRecordSet.getRS(ref "UPDATE PrinterOftenUsed SET PrinterIndex=" + lstPrinter.SelectedIndex + ", PrinterType=" + prnType + " WHERE PrinterIndex=" + rs.Fields("PrinterIndex").Value + ""); } //added by jonas if (lstPrinter.SelectedIndex != -1) { if (optType[1].Checked == false & optType[2].Checked == false & optType[3].Checked == false) { Interaction.MsgBox("You are required to select Printer Type in order to proceed next. [A4 will be used as default].", MsgBoxStyle.ApplicationModal + MsgBoxStyle.Information, "Printing"); return; } else { Printer = GlobalModule.Printers[lstPrinter.SelectedIndex]; gSelect = true; } } else { Interaction.MsgBox("You are required to select Printer in order to proceed NEXT. Or No printer installed.", MsgBoxStyle.ApplicationModal + MsgBoxStyle.Information, "Printing"); return; } this.Close(); } private void frmPrinter_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); if (KeyAscii == 27) { KeyAscii = 0; cmdExit_Click(cmdExit, new System.EventArgs()); } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void lstPrinter_DoubleClick(System.Object eventSender, System.EventArgs eventArgs) { cmdNext_Click(cmdNext, new System.EventArgs()); } private void lstPrinter_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); if (KeyAscii == 13) { cmdNext_Click(cmdNext, new System.EventArgs()); } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void frmPrinter_Load(object sender, System.EventArgs e) { optType.AddRange(new RadioButton[] { _optType_0, _optType_1, _optType_2, _optType_3 }); } } }
/*************************************************************************** Copyright (c) Microsoft Corporation 2012-2015. This code is licensed using the Microsoft Public License (Ms-PL). The text of the license can be found here: http://www.microsoft.com/resources/sharedsource/licensingbasics/publiclicense.mspx Published at http://OpenXmlDeveloper.org Resource Center and Documentation: http://openxmldeveloper.org/wiki/w/wiki/powertools-for-open-xml.aspx Developer: Eric White Blog: http://www.ericwhite.com Twitter: @EricWhiteDev Email: eric@ericwhite.com ***************************************************************************/ using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using DocumentFormat.OpenXml.Packaging; namespace OpenXmlPowerTools { /// <summary> /// Manages SpreadsheetDocument content /// </summary> public class SpreadsheetDocumentManager { private static XNamespace ns; private static XNamespace relationshipsns; private static int headerRow = 1; static SpreadsheetDocumentManager() { ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; relationshipsns = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; } /// <summary> /// Creates a spreadsheet document from a value table /// </summary> /// <param name="filePath">Path to store the document</param> /// <param name="headerList">Contents of first row (header)</param> /// <param name="valueTable">Contents of data</param> /// <param name="initialRow">Row to start copying data from</param> /// <returns></returns> public static void Create(SpreadsheetDocument document, List<string> headerList, string[][] valueTable, int initialRow) { headerRow = initialRow; //Creates a worksheet with given data WorksheetPart worksheet = WorksheetAccessor.Create(document, headerList, valueTable, headerRow); } /// <summary> /// Creates a spreadsheet document with a chart from a value table /// </summary> /// <param name="filePath">Path to store the document</param> /// <param name="headerList">Contents of first row (header)</param> /// <param name="valueTable">Contents of data</param> /// <param name="chartType">Chart type</param> /// <param name="categoryColumn">Column to use as category for charting</param> /// <param name="columnsToChart">Columns to use as data series</param> /// <param name="initialRow">Row index to start copying data</param> /// <returns>SpreadsheetDocument</returns> //public static void Create(SpreadsheetDocument document, List<string> headerList, string[][] valueTable, ChartType chartType, string categoryColumn, List<string> columnsToChart, int initialRow) //{ // headerRow = initialRow; // //Creates worksheet with data // WorksheetPart worksheet = WorksheetAccessor.Create(document, headerList, valueTable, headerRow); // //Creates chartsheet with given series and category // string sheetName = GetSheetName(worksheet, document); // ChartsheetPart chartsheet = // ChartsheetAccessor.Create(document, // chartType, // GetValueReferences(sheetName, categoryColumn, headerList, columnsToChart, valueTable), // GetHeaderReferences(sheetName, categoryColumn, headerList, columnsToChart, valueTable), // GetCategoryReference(sheetName, categoryColumn, headerList, valueTable) // ); //} /// <summary> /// Gets the internal name of a worksheet from a document /// </summary> private static string GetSheetName(WorksheetPart worksheet, SpreadsheetDocument document) { //Gets the id of worksheet part string partId = document.WorkbookPart.GetIdOfPart(worksheet); XDocument workbookDocument = document.WorkbookPart.GetXDocument(); //Gets the name from sheet tag related to worksheet string sheetName = workbookDocument.Root .Element(ns + "sheets") .Elements(ns + "sheet") .Where( t => t.Attribute(relationshipsns + "id").Value == partId ).First() .Attribute("name").Value; return sheetName; } /// <summary> /// Gets the range reference for category /// </summary> /// <param name="sheetName">worksheet to take data from</param> /// <param name="headerColumn">name of column used as category</param> /// <param name="headerList">column names from data</param> /// <param name="valueTable">Data values</param> /// <returns></returns> private static string GetCategoryReference(string sheetName, string headerColumn, List<string> headerList, string[][] valueTable) { int categoryColumn = headerList.IndexOf(headerColumn.ToUpper()) + 1; int numRows = valueTable.GetLength(0); return GetRangeReference( sheetName, categoryColumn, headerRow + 1, categoryColumn, numRows + headerRow ); } /// <summary> /// Gets a list of range references for each of the series headers /// </summary> /// <param name="sheetName">worksheet to take data from</param> /// <param name="headerColumn">name of column used as category</param> /// <param name="headerList">column names from data</param> /// <param name="valueTable">Data values</param> /// <param name="colsToChart">Columns used as data series</param> /// <returns></returns> private static List<string> GetHeaderReferences(string sheetName, string headerColumn, List<string> headerList, List<string> colsToChart, string[][] valueTable) { List<string> valueReferenceList = new List<string>(); foreach (string column in colsToChart) { valueReferenceList.Add( GetRangeReference( sheetName, headerList.IndexOf(column.ToUpper()) + 1, headerRow ) ); } return valueReferenceList; } /// <summary> /// Gets a list of range references for each of the series values /// </summary> /// <param name="sheetName">worksheet to take data from</param> /// <param name="headerColumn">name of column used as category</param> /// <param name="headerList">column names from data</param> /// <param name="valueTable">Data values</param> /// <param name="colsToChart">Columns used as data series</param> /// <returns></returns> private static List<string> GetValueReferences(string sheetName, string headerColumn, List<string> headerList, List<string> colsToChart, string[][] valueTable) { List<string> valueReferenceList = new List<string>(); int numRows = valueTable.GetLength(0); foreach (string column in colsToChart) { int dataColumn = headerList.IndexOf(column.ToUpper()) + 1; valueReferenceList.Add( GetRangeReference( sheetName, dataColumn, headerRow + 1, dataColumn, numRows + headerRow ) ); } return valueReferenceList; } /// <summary> /// Gets a formatted representation of a cell range from a worksheet /// </summary> private static string GetRangeReference(string worksheet, int column, int row) { return string.Format("{0}!{1}{2}", worksheet, WorksheetAccessor.GetColumnId(column), row); } /// <summary> /// Gets a formatted representation of a cell range from a worksheet /// </summary> private static string GetRangeReference(string worksheet, int startColumn, int startRow, int endColumn, int endRow) { return string.Format("{0}!{1}{2}:{3}{4}", worksheet, WorksheetAccessor.GetColumnId(startColumn), startRow, WorksheetAccessor.GetColumnId(endColumn), endRow ); } /// <summary> /// Creates an empty (base) workbook document /// </summary> /// <returns></returns> private static XDocument CreateEmptyWorkbook() { XDocument document = new XDocument( new XElement(ns + "workbook", new XAttribute("xmlns", ns), new XAttribute(XNamespace.Xmlns + "r", relationshipsns), new XElement(ns + "sheets") ) ); return document; } } }
using System; using System.Linq; using System.Collections.Generic; using Blueprint41; using Blueprint41.Core; using Blueprint41.Query; using Blueprint41.DatastoreTemplates; using q = Domain.Data.Query; namespace Domain.Data.Manipulation { public interface IAddressOriginalData : ISchemaBaseOriginalData { string AddressLine1 { get; } string AddressLine2 { get; } string City { get; } string PostalCode { get; } string SpatialLocation { get; } string rowguid { get; } StateProvince StateProvince { get; } AddressType AddressType { get; } } public partial class Address : OGM<Address, Address.AddressData, System.String>, ISchemaBase, INeo4jBase, IAddressOriginalData { #region Initialize static Address() { Register.Types(); } protected override void RegisterGeneratedStoredQueries() { #region LoadByKeys RegisterQuery(nameof(LoadByKeys), (query, alias) => query. Where(alias.Uid.In(Parameter.New<System.String>(Param0)))); #endregion AdditionalGeneratedStoredQueries(); } partial void AdditionalGeneratedStoredQueries(); public static Dictionary<System.String, Address> LoadByKeys(IEnumerable<System.String> uids) { return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item); } protected static void RegisterQuery(string name, Func<IMatchQuery, q.AddressAlias, IWhereQuery> query) { q.AddressAlias alias; IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.Address.Alias(out alias)); IWhereQuery partial = query.Invoke(matchQuery, alias); ICompiled compiled = partial.Return(alias).Compile(); RegisterQuery(name, compiled); } public override string ToString() { return $"Address => AddressLine1 : {this.AddressLine1}, AddressLine2 : {this.AddressLine2?.ToString() ?? "null"}, City : {this.City}, PostalCode : {this.PostalCode}, SpatialLocation : {this.SpatialLocation?.ToString() ?? "null"}, rowguid : {this.rowguid}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}"; } public override int GetHashCode() { return base.GetHashCode(); } protected override void LazySet() { base.LazySet(); if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged) { if ((object)InnerData == (object)OriginalData) OriginalData = new AddressData(InnerData); } } #endregion #region Validations protected override void ValidateSave() { bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged); #pragma warning disable CS0472 if (InnerData.AddressLine1 == null) throw new PersistenceException(string.Format("Cannot save Address with key '{0}' because the AddressLine1 cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.City == null) throw new PersistenceException(string.Format("Cannot save Address with key '{0}' because the City cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.PostalCode == null) throw new PersistenceException(string.Format("Cannot save Address with key '{0}' because the PostalCode cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.rowguid == null) throw new PersistenceException(string.Format("Cannot save Address with key '{0}' because the rowguid cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.ModifiedDate == null) throw new PersistenceException(string.Format("Cannot save Address with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>")); #pragma warning restore CS0472 } protected override void ValidateDelete() { } #endregion #region Inner Data public class AddressData : Data<System.String> { public AddressData() { } public AddressData(AddressData data) { AddressLine1 = data.AddressLine1; AddressLine2 = data.AddressLine2; City = data.City; PostalCode = data.PostalCode; SpatialLocation = data.SpatialLocation; rowguid = data.rowguid; StateProvince = data.StateProvince; AddressType = data.AddressType; ModifiedDate = data.ModifiedDate; Uid = data.Uid; } #region Initialize Collections protected override void InitializeCollections() { NodeType = "Address"; StateProvince = new EntityCollection<StateProvince>(Wrapper, Members.StateProvince); AddressType = new EntityCollection<AddressType>(Wrapper, Members.AddressType); } public string NodeType { get; private set; } sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); } sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); } #endregion #region Map Data sealed public override IDictionary<string, object> MapTo() { IDictionary<string, object> dictionary = new Dictionary<string, object>(); dictionary.Add("AddressLine1", AddressLine1); dictionary.Add("AddressLine2", AddressLine2); dictionary.Add("City", City); dictionary.Add("PostalCode", PostalCode); dictionary.Add("SpatialLocation", SpatialLocation); dictionary.Add("rowguid", rowguid); dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate)); dictionary.Add("Uid", Uid); return dictionary; } sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties) { object value; if (properties.TryGetValue("AddressLine1", out value)) AddressLine1 = (string)value; if (properties.TryGetValue("AddressLine2", out value)) AddressLine2 = (string)value; if (properties.TryGetValue("City", out value)) City = (string)value; if (properties.TryGetValue("PostalCode", out value)) PostalCode = (string)value; if (properties.TryGetValue("SpatialLocation", out value)) SpatialLocation = (string)value; if (properties.TryGetValue("rowguid", out value)) rowguid = (string)value; if (properties.TryGetValue("ModifiedDate", out value)) ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("Uid", out value)) Uid = (string)value; } #endregion #region Members for interface IAddress public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public string City { get; set; } public string PostalCode { get; set; } public string SpatialLocation { get; set; } public string rowguid { get; set; } public EntityCollection<StateProvince> StateProvince { get; private set; } public EntityCollection<AddressType> AddressType { get; private set; } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get; set; } #endregion #region Members for interface INeo4jBase public string Uid { get; set; } #endregion } #endregion #region Outer Data #region Members for interface IAddress public string AddressLine1 { get { LazyGet(); return InnerData.AddressLine1; } set { if (LazySet(Members.AddressLine1, InnerData.AddressLine1, value)) InnerData.AddressLine1 = value; } } public string AddressLine2 { get { LazyGet(); return InnerData.AddressLine2; } set { if (LazySet(Members.AddressLine2, InnerData.AddressLine2, value)) InnerData.AddressLine2 = value; } } public string City { get { LazyGet(); return InnerData.City; } set { if (LazySet(Members.City, InnerData.City, value)) InnerData.City = value; } } public string PostalCode { get { LazyGet(); return InnerData.PostalCode; } set { if (LazySet(Members.PostalCode, InnerData.PostalCode, value)) InnerData.PostalCode = value; } } public string SpatialLocation { get { LazyGet(); return InnerData.SpatialLocation; } set { if (LazySet(Members.SpatialLocation, InnerData.SpatialLocation, value)) InnerData.SpatialLocation = value; } } public string rowguid { get { LazyGet(); return InnerData.rowguid; } set { if (LazySet(Members.rowguid, InnerData.rowguid, value)) InnerData.rowguid = value; } } public StateProvince StateProvince { get { return ((ILookupHelper<StateProvince>)InnerData.StateProvince).GetItem(null); } set { if (LazySet(Members.StateProvince, ((ILookupHelper<StateProvince>)InnerData.StateProvince).GetItem(null), value)) ((ILookupHelper<StateProvince>)InnerData.StateProvince).SetItem(value, null); } } public AddressType AddressType { get { return ((ILookupHelper<AddressType>)InnerData.AddressType).GetItem(null); } set { if (LazySet(Members.AddressType, ((ILookupHelper<AddressType>)InnerData.AddressType).GetItem(null), value)) ((ILookupHelper<AddressType>)InnerData.AddressType).SetItem(value, null); } } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } } #endregion #region Members for interface INeo4jBase public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } } #endregion #region Virtual Node Type public string NodeType { get { return InnerData.NodeType; } } #endregion #endregion #region Reflection private static AddressMembers members = null; public static AddressMembers Members { get { if (members == null) { lock (typeof(Address)) { if (members == null) members = new AddressMembers(); } } return members; } } public class AddressMembers { internal AddressMembers() { } #region Members for interface IAddress public Property AddressLine1 { get; } = Datastore.AdventureWorks.Model.Entities["Address"].Properties["AddressLine1"]; public Property AddressLine2 { get; } = Datastore.AdventureWorks.Model.Entities["Address"].Properties["AddressLine2"]; public Property City { get; } = Datastore.AdventureWorks.Model.Entities["Address"].Properties["City"]; public Property PostalCode { get; } = Datastore.AdventureWorks.Model.Entities["Address"].Properties["PostalCode"]; public Property SpatialLocation { get; } = Datastore.AdventureWorks.Model.Entities["Address"].Properties["SpatialLocation"]; public Property rowguid { get; } = Datastore.AdventureWorks.Model.Entities["Address"].Properties["rowguid"]; public Property StateProvince { get; } = Datastore.AdventureWorks.Model.Entities["Address"].Properties["StateProvince"]; public Property AddressType { get; } = Datastore.AdventureWorks.Model.Entities["Address"].Properties["AddressType"]; #endregion #region Members for interface ISchemaBase public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]; #endregion #region Members for interface INeo4jBase public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]; #endregion } private static AddressFullTextMembers fullTextMembers = null; public static AddressFullTextMembers FullTextMembers { get { if (fullTextMembers == null) { lock (typeof(Address)) { if (fullTextMembers == null) fullTextMembers = new AddressFullTextMembers(); } } return fullTextMembers; } } public class AddressFullTextMembers { internal AddressFullTextMembers() { } } sealed public override Entity GetEntity() { if (entity == null) { lock (typeof(Address)) { if (entity == null) entity = Datastore.AdventureWorks.Model.Entities["Address"]; } } return entity; } private static AddressEvents events = null; public static AddressEvents Events { get { if (events == null) { lock (typeof(Address)) { if (events == null) events = new AddressEvents(); } } return events; } } public class AddressEvents { #region OnNew private bool onNewIsRegistered = false; private EventHandler<Address, EntityEventArgs> onNew; public event EventHandler<Address, EntityEventArgs> OnNew { add { lock (this) { if (!onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; Entity.Events.OnNew += onNewProxy; onNewIsRegistered = true; } onNew += value; } } remove { lock (this) { onNew -= value; if (onNew == null && onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; onNewIsRegistered = false; } } } } private void onNewProxy(object sender, EntityEventArgs args) { EventHandler<Address, EntityEventArgs> handler = onNew; if ((object)handler != null) handler.Invoke((Address)sender, args); } #endregion #region OnDelete private bool onDeleteIsRegistered = false; private EventHandler<Address, EntityEventArgs> onDelete; public event EventHandler<Address, EntityEventArgs> OnDelete { add { lock (this) { if (!onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; Entity.Events.OnDelete += onDeleteProxy; onDeleteIsRegistered = true; } onDelete += value; } } remove { lock (this) { onDelete -= value; if (onDelete == null && onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; onDeleteIsRegistered = false; } } } } private void onDeleteProxy(object sender, EntityEventArgs args) { EventHandler<Address, EntityEventArgs> handler = onDelete; if ((object)handler != null) handler.Invoke((Address)sender, args); } #endregion #region OnSave private bool onSaveIsRegistered = false; private EventHandler<Address, EntityEventArgs> onSave; public event EventHandler<Address, EntityEventArgs> OnSave { add { lock (this) { if (!onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; Entity.Events.OnSave += onSaveProxy; onSaveIsRegistered = true; } onSave += value; } } remove { lock (this) { onSave -= value; if (onSave == null && onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; onSaveIsRegistered = false; } } } } private void onSaveProxy(object sender, EntityEventArgs args) { EventHandler<Address, EntityEventArgs> handler = onSave; if ((object)handler != null) handler.Invoke((Address)sender, args); } #endregion #region OnPropertyChange public static class OnPropertyChange { #region OnAddressLine1 private static bool onAddressLine1IsRegistered = false; private static EventHandler<Address, PropertyEventArgs> onAddressLine1; public static event EventHandler<Address, PropertyEventArgs> OnAddressLine1 { add { lock (typeof(OnPropertyChange)) { if (!onAddressLine1IsRegistered) { Members.AddressLine1.Events.OnChange -= onAddressLine1Proxy; Members.AddressLine1.Events.OnChange += onAddressLine1Proxy; onAddressLine1IsRegistered = true; } onAddressLine1 += value; } } remove { lock (typeof(OnPropertyChange)) { onAddressLine1 -= value; if (onAddressLine1 == null && onAddressLine1IsRegistered) { Members.AddressLine1.Events.OnChange -= onAddressLine1Proxy; onAddressLine1IsRegistered = false; } } } } private static void onAddressLine1Proxy(object sender, PropertyEventArgs args) { EventHandler<Address, PropertyEventArgs> handler = onAddressLine1; if ((object)handler != null) handler.Invoke((Address)sender, args); } #endregion #region OnAddressLine2 private static bool onAddressLine2IsRegistered = false; private static EventHandler<Address, PropertyEventArgs> onAddressLine2; public static event EventHandler<Address, PropertyEventArgs> OnAddressLine2 { add { lock (typeof(OnPropertyChange)) { if (!onAddressLine2IsRegistered) { Members.AddressLine2.Events.OnChange -= onAddressLine2Proxy; Members.AddressLine2.Events.OnChange += onAddressLine2Proxy; onAddressLine2IsRegistered = true; } onAddressLine2 += value; } } remove { lock (typeof(OnPropertyChange)) { onAddressLine2 -= value; if (onAddressLine2 == null && onAddressLine2IsRegistered) { Members.AddressLine2.Events.OnChange -= onAddressLine2Proxy; onAddressLine2IsRegistered = false; } } } } private static void onAddressLine2Proxy(object sender, PropertyEventArgs args) { EventHandler<Address, PropertyEventArgs> handler = onAddressLine2; if ((object)handler != null) handler.Invoke((Address)sender, args); } #endregion #region OnCity private static bool onCityIsRegistered = false; private static EventHandler<Address, PropertyEventArgs> onCity; public static event EventHandler<Address, PropertyEventArgs> OnCity { add { lock (typeof(OnPropertyChange)) { if (!onCityIsRegistered) { Members.City.Events.OnChange -= onCityProxy; Members.City.Events.OnChange += onCityProxy; onCityIsRegistered = true; } onCity += value; } } remove { lock (typeof(OnPropertyChange)) { onCity -= value; if (onCity == null && onCityIsRegistered) { Members.City.Events.OnChange -= onCityProxy; onCityIsRegistered = false; } } } } private static void onCityProxy(object sender, PropertyEventArgs args) { EventHandler<Address, PropertyEventArgs> handler = onCity; if ((object)handler != null) handler.Invoke((Address)sender, args); } #endregion #region OnPostalCode private static bool onPostalCodeIsRegistered = false; private static EventHandler<Address, PropertyEventArgs> onPostalCode; public static event EventHandler<Address, PropertyEventArgs> OnPostalCode { add { lock (typeof(OnPropertyChange)) { if (!onPostalCodeIsRegistered) { Members.PostalCode.Events.OnChange -= onPostalCodeProxy; Members.PostalCode.Events.OnChange += onPostalCodeProxy; onPostalCodeIsRegistered = true; } onPostalCode += value; } } remove { lock (typeof(OnPropertyChange)) { onPostalCode -= value; if (onPostalCode == null && onPostalCodeIsRegistered) { Members.PostalCode.Events.OnChange -= onPostalCodeProxy; onPostalCodeIsRegistered = false; } } } } private static void onPostalCodeProxy(object sender, PropertyEventArgs args) { EventHandler<Address, PropertyEventArgs> handler = onPostalCode; if ((object)handler != null) handler.Invoke((Address)sender, args); } #endregion #region OnSpatialLocation private static bool onSpatialLocationIsRegistered = false; private static EventHandler<Address, PropertyEventArgs> onSpatialLocation; public static event EventHandler<Address, PropertyEventArgs> OnSpatialLocation { add { lock (typeof(OnPropertyChange)) { if (!onSpatialLocationIsRegistered) { Members.SpatialLocation.Events.OnChange -= onSpatialLocationProxy; Members.SpatialLocation.Events.OnChange += onSpatialLocationProxy; onSpatialLocationIsRegistered = true; } onSpatialLocation += value; } } remove { lock (typeof(OnPropertyChange)) { onSpatialLocation -= value; if (onSpatialLocation == null && onSpatialLocationIsRegistered) { Members.SpatialLocation.Events.OnChange -= onSpatialLocationProxy; onSpatialLocationIsRegistered = false; } } } } private static void onSpatialLocationProxy(object sender, PropertyEventArgs args) { EventHandler<Address, PropertyEventArgs> handler = onSpatialLocation; if ((object)handler != null) handler.Invoke((Address)sender, args); } #endregion #region Onrowguid private static bool onrowguidIsRegistered = false; private static EventHandler<Address, PropertyEventArgs> onrowguid; public static event EventHandler<Address, PropertyEventArgs> Onrowguid { add { lock (typeof(OnPropertyChange)) { if (!onrowguidIsRegistered) { Members.rowguid.Events.OnChange -= onrowguidProxy; Members.rowguid.Events.OnChange += onrowguidProxy; onrowguidIsRegistered = true; } onrowguid += value; } } remove { lock (typeof(OnPropertyChange)) { onrowguid -= value; if (onrowguid == null && onrowguidIsRegistered) { Members.rowguid.Events.OnChange -= onrowguidProxy; onrowguidIsRegistered = false; } } } } private static void onrowguidProxy(object sender, PropertyEventArgs args) { EventHandler<Address, PropertyEventArgs> handler = onrowguid; if ((object)handler != null) handler.Invoke((Address)sender, args); } #endregion #region OnStateProvince private static bool onStateProvinceIsRegistered = false; private static EventHandler<Address, PropertyEventArgs> onStateProvince; public static event EventHandler<Address, PropertyEventArgs> OnStateProvince { add { lock (typeof(OnPropertyChange)) { if (!onStateProvinceIsRegistered) { Members.StateProvince.Events.OnChange -= onStateProvinceProxy; Members.StateProvince.Events.OnChange += onStateProvinceProxy; onStateProvinceIsRegistered = true; } onStateProvince += value; } } remove { lock (typeof(OnPropertyChange)) { onStateProvince -= value; if (onStateProvince == null && onStateProvinceIsRegistered) { Members.StateProvince.Events.OnChange -= onStateProvinceProxy; onStateProvinceIsRegistered = false; } } } } private static void onStateProvinceProxy(object sender, PropertyEventArgs args) { EventHandler<Address, PropertyEventArgs> handler = onStateProvince; if ((object)handler != null) handler.Invoke((Address)sender, args); } #endregion #region OnAddressType private static bool onAddressTypeIsRegistered = false; private static EventHandler<Address, PropertyEventArgs> onAddressType; public static event EventHandler<Address, PropertyEventArgs> OnAddressType { add { lock (typeof(OnPropertyChange)) { if (!onAddressTypeIsRegistered) { Members.AddressType.Events.OnChange -= onAddressTypeProxy; Members.AddressType.Events.OnChange += onAddressTypeProxy; onAddressTypeIsRegistered = true; } onAddressType += value; } } remove { lock (typeof(OnPropertyChange)) { onAddressType -= value; if (onAddressType == null && onAddressTypeIsRegistered) { Members.AddressType.Events.OnChange -= onAddressTypeProxy; onAddressTypeIsRegistered = false; } } } } private static void onAddressTypeProxy(object sender, PropertyEventArgs args) { EventHandler<Address, PropertyEventArgs> handler = onAddressType; if ((object)handler != null) handler.Invoke((Address)sender, args); } #endregion #region OnModifiedDate private static bool onModifiedDateIsRegistered = false; private static EventHandler<Address, PropertyEventArgs> onModifiedDate; public static event EventHandler<Address, PropertyEventArgs> OnModifiedDate { add { lock (typeof(OnPropertyChange)) { if (!onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; Members.ModifiedDate.Events.OnChange += onModifiedDateProxy; onModifiedDateIsRegistered = true; } onModifiedDate += value; } } remove { lock (typeof(OnPropertyChange)) { onModifiedDate -= value; if (onModifiedDate == null && onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; onModifiedDateIsRegistered = false; } } } } private static void onModifiedDateProxy(object sender, PropertyEventArgs args) { EventHandler<Address, PropertyEventArgs> handler = onModifiedDate; if ((object)handler != null) handler.Invoke((Address)sender, args); } #endregion #region OnUid private static bool onUidIsRegistered = false; private static EventHandler<Address, PropertyEventArgs> onUid; public static event EventHandler<Address, PropertyEventArgs> OnUid { add { lock (typeof(OnPropertyChange)) { if (!onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; Members.Uid.Events.OnChange += onUidProxy; onUidIsRegistered = true; } onUid += value; } } remove { lock (typeof(OnPropertyChange)) { onUid -= value; if (onUid == null && onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; onUidIsRegistered = false; } } } } private static void onUidProxy(object sender, PropertyEventArgs args) { EventHandler<Address, PropertyEventArgs> handler = onUid; if ((object)handler != null) handler.Invoke((Address)sender, args); } #endregion } #endregion } #endregion #region IAddressOriginalData public IAddressOriginalData OriginalVersion { get { return this; } } #region Members for interface IAddress string IAddressOriginalData.AddressLine1 { get { return OriginalData.AddressLine1; } } string IAddressOriginalData.AddressLine2 { get { return OriginalData.AddressLine2; } } string IAddressOriginalData.City { get { return OriginalData.City; } } string IAddressOriginalData.PostalCode { get { return OriginalData.PostalCode; } } string IAddressOriginalData.SpatialLocation { get { return OriginalData.SpatialLocation; } } string IAddressOriginalData.rowguid { get { return OriginalData.rowguid; } } StateProvince IAddressOriginalData.StateProvince { get { return ((ILookupHelper<StateProvince>)OriginalData.StateProvince).GetOriginalItem(null); } } AddressType IAddressOriginalData.AddressType { get { return ((ILookupHelper<AddressType>)OriginalData.AddressType).GetOriginalItem(null); } } #endregion #region Members for interface ISchemaBase ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } } System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } } #endregion #region Members for interface INeo4jBase INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } } string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } } #endregion #endregion } }
//----------------------------------------------------------------------- // <copyright file="GvrTooltip.cs" company="Google Inc."> // Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- using UnityEngine; using UnityEngine.UI; using System.Collections; /// <summary> /// A tooltip for displaying control schemes overlaying the controller visual using a Unity Canvas. /// </summary> /// <remarks> /// Automatically changes what side of the controller the tooltip is shown on depending /// on the handedness setting for the player. /// Automatically fades out when the controller visual is too close or too far /// away from the player's head. /// Look at the prefab GvrControllerPointer to see an example of how to use this script. /// </remarks> [RequireComponent(typeof(CanvasGroup))] [RequireComponent(typeof(RectTransform))] [ExecuteInEditMode] [HelpURL("https://developers.google.com/vr/unity/reference/class/GvrTooltip")] public class GvrTooltip : MonoBehaviour, IGvrArmModelReceiver { /// Rotation for a tooltip when it is displayed on the right side of the controller visual. protected static readonly Quaternion RIGHT_SIDE_ROTATION = Quaternion.Euler(0.0f, 0.0f, 0.0f); /// Rotation for a tooltip when it is displayed on the left side of the controller visual. protected static readonly Quaternion LEFT_SIDE_ROTATION = Quaternion.Euler(0.0f, 0.0f, 180.0f); /// Anchor point for a tooltip, used for controlling what side the tooltip is on. protected static readonly Vector2 SQUARE_CENTER = new Vector2(0.5f, 0.5f); /// Pivot point for a tooltip, used for controlling what side the tooltip is on. protected static readonly Vector2 PIVOT = new Vector2(-0.5f, 0.5f); /// Y Position for touch pad tooltips based on the standard controller visual. protected const float TOUCH_PAD_Y_POSITION_METERS = 0.0385f; /// Y position for app button tooltips based on the standard controller visual. protected const float APP_BUTTON_Y_POSITION_METERS = 0.0105f; /// Z position for all tooltips based on the standard controller visual. protected const float TOOLTIP_Z_POSITION_METERS = 0.0098f; /// Options for where the controller should be displayed. /// If set to custom, then the manually set localPosition of the tooltip is used. /// This is useful when displaying a tooltip for a non-standard controller visual. enum Location { TouchPadOutside, TouchPadInside, AppButtonOutside, AppButtonInside, Custom } [Tooltip("The location to display the tooltip at relative to the controller visual.")] [SerializeField] private Location location; [Tooltip("The text field for this tooltip.")] [SerializeField] private Text text; [Tooltip("Determines if the tooltip is always visible regardless of the controller's location.")] [SerializeField] private bool alwaysVisible; private bool isOnLeft = false; private RectTransform rectTransform; private CanvasGroup canvasGroup; /// The text field for this tooltip. public Text TooltipText { get { return text; } } /// <summary>Arm model reference.</summary> public GvrBaseArmModel ArmModel { get; set; } void Awake() { rectTransform = GetComponent<RectTransform>(); canvasGroup = GetComponent<CanvasGroup>(); isOnLeft = IsTooltipOnLeft(); RefreshTooltip(); } void OnEnable() { // Update using OnPostControllerInputUpdated. // This way, the position and rotation will be correct for the entire frame // so that it doesn't matter what order Updates get called in. if (Application.isPlaying) { GvrControllerInput.OnPostControllerInputUpdated += OnPostControllerInputUpdated; } } void OnDisable() { GvrControllerInput.OnPostControllerInputUpdated -= OnPostControllerInputUpdated; } private void OnPostControllerInputUpdated() { CheckTooltipSide(); if (canvasGroup != null && ArmModel != null) { canvasGroup.alpha = alwaysVisible ? 1.0f : ArmModel.TooltipAlphaValue; } } void OnValidate() { rectTransform = GetComponent<RectTransform>(); RefreshTooltip(); } #if UNITY_EDITOR void OnRenderObject() { if (!Application.isPlaying) { CheckTooltipSide(); } } #endif // UNITY_EDITOR /// <summary>Returns true if this tooltip is set to display on the inside of the controller.</summary> public bool IsTooltipInside() { switch (location) { case Location.TouchPadInside: case Location.AppButtonInside: case Location.Custom: return true; case Location.TouchPadOutside: case Location.AppButtonOutside: default: return false; } } /// Returns true if the tooltip should display on the left side of the controller. /// This will change based on the handedness of the controller, as well as if the /// tooltip is set to display inside or outside. public bool IsTooltipOnLeft() { bool isInside = IsTooltipInside(); GvrSettings.UserPrefsHandedness handedness = GvrSettings.Handedness; if (handedness == GvrSettings.UserPrefsHandedness.Left) { return !isInside; } else { return isInside; } } /// Refreshes how the tooltip is being displayed based on what side it is being shown on. /// Override to add custom display functionality. protected virtual void OnSideChanged(bool IsLocationOnLeft) { transform.localRotation = (isOnLeft ? LEFT_SIDE_ROTATION : RIGHT_SIDE_ROTATION); if (text != null) { text.transform.localRotation = (IsLocationOnLeft ? LEFT_SIDE_ROTATION : RIGHT_SIDE_ROTATION); text.alignment = (IsLocationOnLeft ? TextAnchor.MiddleRight : TextAnchor.MiddleLeft); } } /// <summary>Helper method to return meters to canvas scale.</summary> protected float GetMetersToCanvasScale() { return GvrUIHelpers.GetMetersToCanvasScale(transform); } private Vector3 GetLocalPosition() { float metersToCanvasScale = GetMetersToCanvasScale(); // Return early if we didn't find a valid metersToCanvasScale. if (metersToCanvasScale == 0.0f) { return rectTransform.anchoredPosition3D; } float tooltipZPosition = TOOLTIP_Z_POSITION_METERS / metersToCanvasScale; switch (location) { case Location.TouchPadOutside: case Location.TouchPadInside: float touchPadYPosition = TOUCH_PAD_Y_POSITION_METERS / metersToCanvasScale; return new Vector3(0.0f, touchPadYPosition, tooltipZPosition); case Location.AppButtonOutside: case Location.AppButtonInside: float appButtonYPosition = APP_BUTTON_Y_POSITION_METERS / metersToCanvasScale; return new Vector3(0.0f, appButtonYPosition, tooltipZPosition); case Location.Custom: default: return rectTransform.anchoredPosition3D; } } private void CheckTooltipSide() { // If handedness changes, the tooltip will switch sides. bool newIsOnLeft = IsTooltipOnLeft(); if (newIsOnLeft != isOnLeft) { isOnLeft = newIsOnLeft; RefreshTooltip(); } } private void RefreshTooltip() { rectTransform.anchorMax = SQUARE_CENTER; rectTransform.anchorMax = SQUARE_CENTER; rectTransform.pivot = PIVOT; rectTransform.anchoredPosition3D = GetLocalPosition(); OnSideChanged(isOnLeft); } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using ASC.Api.Attributes; using ASC.Api.Documents; using ASC.Api.Employee; using ASC.Api.Exceptions; using ASC.Api.Projects.Wrappers; using ASC.Api.Utils; using ASC.MessagingSystem; using ASC.Projects.Core.Domain; using ASC.Projects.Engine; using ASC.Specific; using ASC.Web.Studio.Utility.HtmlUtility; namespace ASC.Api.Projects { public partial class ProjectApi { ///<summary> ///Returns the list with the detailed information about all the message matching the filter parameters specified in the request ///</summary> ///<short> /// Get message by filter ///</short> ///<category>Discussions</category> ///<param name="projectid" optional="true"> Project ID</param> ///<param name="tag" optional="true">Project Tag</param> ///<param name="departament" optional="true">Departament GUID</param> ///<param name="participant" optional="true">Participant GUID</param> ///<param name="createdStart" optional="true">Minimum value of message creation date</param> ///<param name="createdStop" optional="true">Maximum value of message creation date</param> ///<param name="lastId">Last message ID</param> ///<param name="myProjects">Messages in my projects</param> ///<param name="follow">Followed messages</param> ///<param name="status"></param> ///<returns>List of messages</returns> ///<exception cref="ItemNotFoundException"></exception> [Read(@"message/filter")] public IEnumerable<MessageWrapper> GetMessageByFilter(int projectid, int tag, Guid departament, Guid participant, ApiDateTime createdStart, ApiDateTime createdStop, int lastId, bool myProjects, bool follow, MessageStatus? status) { var messageEngine = EngineFactory.MessageEngine; var filter = CreateFilter(EntityType.Message); filter.DepartmentId = departament; filter.UserId = participant; filter.FromDate = createdStart; filter.ToDate = createdStop; filter.TagId = tag; filter.MyProjects = myProjects; filter.LastId = lastId; filter.Follow = follow; filter.MessageStatus = status; if (projectid != 0) filter.ProjectIds.Add(projectid); SetTotalCount(messageEngine.GetByFilterCount(filter)); return messageEngine.GetByFilter(filter).NotFoundIfNull().Select(MessageWrapperSelector).ToList(); } ///<summary> ///Returns the list of all the messages in the discussions within the project with the ID specified in the request ///</summary> ///<short> ///Messages ///</short> ///<category>Discussions</category> ///<param name="projectid">Project ID</param> ///<returns>List of messages</returns> ///<exception cref="ItemNotFoundException"></exception> [Read(@"{projectid:[0-9]+}/message")] public IEnumerable<MessageWrapper> GetProjectMessages(int projectid) { var project = EngineFactory.ProjectEngine.GetByID(projectid).NotFoundIfNull(); if (!ProjectSecurity.CanRead<Message>(project)) throw ProjectSecurity.CreateSecurityException(); return EngineFactory.MessageEngine.GetByProject(projectid).Select(MessageWrapperSelector).ToList(); } ///<summary> ///Adds a message to the selected discussion within the project with the ID specified in the request ///</summary> ///<short> ///Add message ///</short> ///<category>Discussions</category> ///<param name="projectid">Project ID</param> ///<param name="title">Discussion title</param> ///<param name="content">Message text</param> ///<param name="participants">IDs (GUIDs) of users separated with ','</param> ///<param name="notify">Notify participants</param> ///<returns></returns> ///<exception cref="ArgumentException"></exception> ///<exception cref="ItemNotFoundException"></exception> [Create(@"{projectid:[0-9]+}/message")] public MessageWrapper AddProjectMessage(int projectid, string title, string content, string participants, bool? notify) { if (string.IsNullOrEmpty(title)) throw new ArgumentException(@"title can't be empty", "title"); if (string.IsNullOrEmpty(content)) throw new ArgumentException(@"description can't be empty", "content"); var project = EngineFactory.ProjectEngine.GetByID(projectid).NotFoundIfNull(); ProjectSecurity.DemandCreate<Message>(project); var messageEngine = EngineFactory.MessageEngine; var discussion = new Message { Description = content, Title = title, Project = project, }; messageEngine.SaveOrUpdate(discussion, notify.HasValue ? notify.Value : true, ToGuidList(participants)); MessageService.Send(Request, MessageAction.DiscussionCreated, MessageTarget.Create(discussion.ID), discussion.Project.Title, discussion.Title); return MessageWrapperSelector(discussion); } ///<summary> ///Updates the selected message in the discussion within the project with the ID specified in the request ///</summary> ///<short> ///Update message ///</short> ///<category>Discussions</category> ///<param name="messageid">Message ID</param> ///<param name="projectid">Project ID</param> ///<param name="title">Discussion title</param> ///<param name="content">Message text</param> ///<param name="participants">IDs (GUIDs) of users separated with ','</param> ///<param name="notify">Notify participants</param> ///<returns></returns> ///<exception cref="ArgumentException"></exception> ///<exception cref="ItemNotFoundException"></exception> [Update(@"message/{messageid:[0-9]+}")] public MessageWrapperFull UpdateProjectMessage(int messageid, int projectid, string title, string content, string participants, bool? notify) { var messageEngine = EngineFactory.MessageEngine; var discussion = messageEngine.GetByID(messageid).NotFoundIfNull(); var project = EngineFactory.ProjectEngine.GetByID(projectid).NotFoundIfNull(); ProjectSecurity.DemandEdit(discussion); discussion.Project = Update.IfNotEmptyAndNotEquals(discussion.Project, project); discussion.Description = Update.IfNotEmptyAndNotEquals(discussion.Description, content); discussion.Title = Update.IfNotEmptyAndNotEquals(discussion.Title, title); messageEngine.SaveOrUpdate(discussion, notify.HasValue ? notify.Value : true, ToGuidList(participants)); MessageService.Send(Request, MessageAction.DiscussionUpdated, MessageTarget.Create(discussion.ID), discussion.Project.Title, discussion.Title); return new MessageWrapperFull(this, discussion, new ProjectWrapperFull(this, discussion.Project, EngineFactory.FileEngine.GetRoot(discussion.Project.ID)), GetProjectMessageSubscribers(messageid)); } ///<summary> ///Updates the selected message status ///</summary> ///<short> ///Update message status ///</short> ///<category>Discussions</category> ///<param name="messageid">Message ID</param> ///<param name="status">Project ID</param> ///<returns></returns> ///<exception cref="ArgumentException"></exception> ///<exception cref="ItemNotFoundException"></exception> [Update(@"message/{messageid:[0-9]+}/status")] public MessageWrapper UpdateProjectMessage(int messageid, MessageStatus status) { var messageEngine = EngineFactory.MessageEngine; var discussion = messageEngine.GetByID(messageid).NotFoundIfNull(); ProjectSecurity.DemandEdit(discussion); discussion.Status = status; messageEngine.ChangeStatus(discussion); MessageService.Send(Request, MessageAction.DiscussionUpdated, MessageTarget.Create(discussion.ID), discussion.Project.Title, discussion.Title); return MessageWrapperSelector(discussion); } ///<summary> ///Deletes the message with the ID specified in the request from a project discussion ///</summary> ///<short> ///Delete message ///</short> ///<category>Discussions</category> ///<param name="messageid">Message ID</param> ///<returns></returns> ///<exception cref="ItemNotFoundException"></exception> [Delete(@"message/{messageid:[0-9]+}")] public MessageWrapper DeleteProjectMessage(int messageid) { var discussionEngine = EngineFactory.MessageEngine; var discussion = discussionEngine.GetByID(messageid).NotFoundIfNull(); ProjectSecurity.DemandEdit(discussion); discussionEngine.Delete(discussion); MessageService.Send(Request, MessageAction.DiscussionDeleted, MessageTarget.Create(discussion.ID), discussion.Project.Title, discussion.Title); return MessageWrapperSelector(discussion); } private static IEnumerable<Guid> ToGuidList(string participants) { return participants != null ? participants.Equals(string.Empty) ? new List<Guid>() : participants.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => new Guid(x)) : null; } ///<summary> ///Returns the detailed information about the message with the ID specified in the request ///</summary> ///<short> ///Message ///</short> ///<category>Discussions</category> ///<param name="messageid">Message ID</param> ///<returns>Message</returns> ///<exception cref="ItemNotFoundException"></exception> [Read(@"message/{messageid:[0-9]+}")] public MessageWrapperFull GetProjectMessage(int messageid) { var discussion = EngineFactory.MessageEngine.GetByID(messageid).NotFoundIfNull(); var project = ProjectWrapperFullSelector(discussion.Project, EngineFactory.FileEngine.GetRoot(discussion.Project.ID)); var subscribers = GetProjectMessageSubscribers(messageid); var files = EngineFactory.MessageEngine.GetFiles(discussion).Select(FileWrapperSelector); var comments = EngineFactory.CommentEngine.GetComments(discussion); return new MessageWrapperFull(this, discussion, project, subscribers, files, comments.Where(r => r.Parent.Equals(Guid.Empty)).Select(x => GetCommentInfo(comments, x, discussion)).ToList()); } ///<summary> ///Returns the detailed information about files attached to the message with the ID specified in the request ///</summary> ///<short> ///Message files ///</short> ///<category>Files</category> ///<param name="messageid">Message ID</param> ///<returns> List of message files</returns> ///<exception cref="ItemNotFoundException"></exception> [Read(@"message/{messageid:[0-9]+}/files")] public IEnumerable<FileWrapper> GetMessageFiles(int messageid) { var messageEngine = EngineFactory.MessageEngine; var message = messageEngine.GetByID(messageid).NotFoundIfNull(); ProjectSecurity.DemandReadFiles(message.Project); return messageEngine.GetFiles(message).Select(FileWrapperSelector); } ///<summary> ///Uploads the file specified in the request to the selected message ///</summary> ///<short> ///Upload file to message ///</short> ///<category>Files</category> ///<param name="messageid">Message ID</param> ///<param name="files">File ID</param> ///<returns>Message</returns> ///<exception cref="ItemNotFoundException"></exception> [Create(@"message/{messageid:[0-9]+}/files")] public MessageWrapper UploadFilesToMessage(int messageid, IEnumerable<int> files) { var messageEngine = EngineFactory.MessageEngine; var fileEngine = EngineFactory.FileEngine; var discussion = messageEngine.GetByID(messageid).NotFoundIfNull(); ProjectSecurity.DemandReadFiles(discussion.Project); var filesList = files.ToList(); var attachments = new List<Files.Core.File>(); foreach (var fileid in filesList) { var file = fileEngine.GetFile(fileid).NotFoundIfNull(); attachments.Add(file); messageEngine.AttachFile(discussion, file.ID, true); } MessageService.Send(Request, MessageAction.DiscussionAttachedFiles, MessageTarget.Create(discussion.ID), discussion.Project.Title, discussion.Title, attachments.Select(x => x.Title)); return MessageWrapperSelector(discussion); } ///<summary> ///Detaches the selected file from the message with the ID specified in the request ///</summary> ///<short> ///Detach file from message ///</short> ///<category>Files</category> ///<param name="messageid">Message ID</param> ///<param name="fileid">File ID</param> ///<returns>Message</returns> ///<exception cref="ItemNotFoundException"></exception> [Delete(@"message/{messageid:[0-9]+}/files")] public MessageWrapper DetachFileFromMessage(int messageid, int fileid) { var messageEngine = EngineFactory.MessageEngine; var discussion = messageEngine.GetByID(messageid).NotFoundIfNull(); ProjectSecurity.DemandReadFiles(discussion.Project); var file = EngineFactory.FileEngine.GetFile(fileid).NotFoundIfNull(); messageEngine.DetachFile(discussion, fileid); MessageService.Send(Request, MessageAction.DiscussionDetachedFile, MessageTarget.Create(discussion.ID), discussion.Project.Title, discussion.Title, file.Title); return MessageWrapperSelector(discussion); } ///<summary> ///Detaches the selected file from the message with the ID specified in the request ///</summary> ///<short> ///Detach file from message ///</short> ///<category>Files</category> ///<param name="messageid">Message ID</param> ///<param name="files">File ID</param> ///<returns>Message</returns> ///<exception cref="ItemNotFoundException"></exception> ///<visible>false</visible> [Delete(@"message/{messageid:[0-9]+}/filesmany")] public MessageWrapper DetachFileFromMessage(int messageid, IEnumerable<int> files) { var messageEngine = EngineFactory.MessageEngine; var fileEngine = EngineFactory.FileEngine; var discussion = messageEngine.GetByID(messageid).NotFoundIfNull(); ProjectSecurity.DemandReadFiles(discussion.Project); var filesList = files.ToList(); var attachments = new List<Files.Core.File>(); foreach (var fileid in filesList) { var file = fileEngine.GetFile(fileid).NotFoundIfNull(); attachments.Add(file); messageEngine.DetachFile(discussion, fileid); } MessageService.Send(Request, MessageAction.DiscussionDetachedFile, MessageTarget.Create(discussion.ID), discussion.Project.Title, discussion.Title, attachments.Select(x => x.Title)); return MessageWrapperSelector(discussion); } ///<summary> ///Returns the list of latest messages in the discussions within the project with the ID specified in the request ///</summary> ///<short> ///Latest messages ///</short> ///<category>Discussions</category> ///<returns>List of messages</returns> ///<exception cref="ItemNotFoundException"></exception> [Read(@"message")] public IEnumerable<MessageWrapper> GetProjectRecentMessages() { return EngineFactory.MessageEngine.GetMessages((int)StartIndex, (int)Count).Select(MessageWrapperSelector); } ///<summary> ///Returns the list of comments to the messages in the discussions within the project with the ID specified in the request ///</summary> ///<short> ///Message comments ///</short> ///<category>Comments</category> ///<param name="messageid">Message ID</param> ///<returns>Comments for message</returns> ///<exception cref="ItemNotFoundException"></exception> [Read(@"message/{messageid:[0-9]+}/comment")] public IEnumerable<CommentWrapper> GetProjectMessagesComments(int messageid) { var messageEngine = EngineFactory.MessageEngine; var message = messageEngine.GetByID(messageid).NotFoundIfNull(); return EngineFactory.CommentEngine.GetComments(message).Select(x => new CommentWrapper(this, x, message)); } ///<summary> ///Adds a comment to the selected message in a discussion within the project with the content specified in the request. The parent comment ID can also be selected. ///</summary> ///<short> ///Add message comment ///</short> ///<category>Comments</category> ///<param name="messageid">Message ID</param> ///<param name="content">Comment content</param> ///<param name="parentId">Parrent comment ID</param> ///<returns></returns> ///<exception cref="ItemNotFoundException"></exception> [Create(@"message/{messageid:[0-9]+}/comment")] public CommentWrapper AddProjectMessagesComment(int messageid, string content, Guid parentId) { if (string.IsNullOrEmpty(content)) throw new ArgumentException(@"Comment text is empty", content); if (parentId != Guid.Empty && EngineFactory.CommentEngine.GetByID(parentId) == null) throw new ItemNotFoundException("parent comment not found"); var comment = new Comment { Content = content, TargetUniqID = ProjectEntity.BuildUniqId<Message>(messageid), CreateBy = CurrentUserId, CreateOn = Core.Tenants.TenantUtil.DateTimeNow() }; if (parentId != Guid.Empty) { comment.Parent = parentId; } var message = EngineFactory.CommentEngine.GetEntityByTargetUniqId(comment).NotFoundIfNull(); EngineFactory.CommentEngine.SaveOrUpdateComment(message, comment); MessageService.Send(Request, MessageAction.DiscussionCommentCreated, MessageTarget.Create(comment.ID), message.Project.Title, message.Title); return new CommentWrapper(this, comment, message); } ///<summary> ///Subscribe to notifications about the actions performed with the task with the ID specified in the request ///</summary> ///<short> ///Subscribe to message action ///</short> ///<category>Discussions</category> ///<returns>Discussion</returns> ///<param name="messageid">Message ID</param> ///<exception cref="ItemNotFoundException"></exception> [Update(@"message/{messageid:[0-9]+}/subscribe")] public MessageWrapper SubscribeToMessage(int messageid) { var discussionEngine = EngineFactory.MessageEngine; var discussion = discussionEngine.GetByID(messageid).NotFoundIfNull(); ProjectSecurity.DemandAuthentication(); discussionEngine.Follow(discussion); MessageService.Send(Request, MessageAction.DiscussionUpdatedFollowing, MessageTarget.Create(discussion.ID), discussion.Project.Title, discussion.Title); return new MessageWrapperFull(this, discussion, ProjectWrapperFullSelector(discussion.Project, EngineFactory.FileEngine.GetRoot(discussion.Project.ID)), GetProjectMessageSubscribers(messageid)); } ///<summary> ///Checks subscription to notifications about the actions performed with the discussion with the ID specified in the request ///</summary> ///<short> ///Check subscription to discussion action ///</short> ///<category>Discussions</category> ///<param name="messageid">Message ID</param> ///<exception cref="ItemNotFoundException"></exception> [Read(@"message/{messageid:[0-9]+}/subscribe")] public bool IsSubscribedToMessage(int messageid) { var messageEngine = EngineFactory.MessageEngine; var message = messageEngine.GetByID(messageid).NotFoundIfNull(); ProjectSecurity.DemandAuthentication(); return messageEngine.IsSubscribed(message); } ///<summary> ///Get subscribers ///</summary> ///<short> ///Get subscribers ///</short> ///<category>Discussions</category> ///<param name="messageid">Message ID</param> ///<exception cref="ItemNotFoundException"></exception> [Read(@"message/{messageid:[0-9]+}/subscribes")] public IEnumerable<EmployeeWraperFull> GetProjectMessageSubscribers(int messageid) { var messageEngine = EngineFactory.MessageEngine; var message = messageEngine.GetByID(messageid).NotFoundIfNull(); ProjectSecurity.DemandAuthentication(); return messageEngine.GetSubscribers(message).Select(r => GetEmployeeWraperFull(new Guid(r.ID))) .OrderBy(r => r.DisplayName).ToList(); } ///<summary> ///Get preview ///</summary> ///<short> ///Get preview ///</short> ///<category>Discussions</category> ///<param name="htmltext">html to create preview</param> [Create(@"message/discussion/preview")] public string GetPreview(string htmltext) { return HtmlUtility.GetFull(htmltext); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Threading; using NLog.Common; using NLog.Internal; using NLog.Layouts; using NLog.Time; /// <summary> /// Represents the logging event. /// </summary> public class LogEventInfo { /// <summary> /// Gets the date of the first log event created. /// </summary> public static readonly DateTime ZeroDate = DateTime.UtcNow; private static int globalSequenceId; private readonly object layoutCacheLock = new object(); private string formattedMessage; private IDictionary<Layout, string> layoutCache; private IDictionary<object, object> properties; private IDictionary eventContextAdapter; /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> public LogEventInfo() { } /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Logger name.</param> /// <param name="message">Log message including parameter placeholders.</param> public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message) : this(level, loggerName, null, message, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Logger name.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">Log message including parameter placeholders.</param> /// <param name="parameters">Parameter array.</param> public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters) : this(level, loggerName, formatProvider, message, parameters, null) { } /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Logger name.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">Log message including parameter placeholders.</param> /// <param name="parameters">Parameter array.</param> /// <param name="exception">Exception information.</param> public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters, Exception exception) { this.TimeStamp = TimeSource.Current.Time; this.Level = level; this.LoggerName = loggerName; this.Message = message; this.Parameters = parameters; this.FormatProvider = formatProvider; this.Exception = exception; this.SequenceID = Interlocked.Increment(ref globalSequenceId); if (NeedToPreformatMessage(parameters)) { this.CalcFormattedMessage(); } } /// <summary> /// Gets the unique identifier of log event which is automatically generated /// and monotonously increasing. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID", Justification = "Backwards compatibility")] public int SequenceID { get; private set; } /// <summary> /// Gets or sets the timestamp of the logging event. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TimeStamp", Justification = "Backwards compatibility.")] public DateTime TimeStamp { get; set; } /// <summary> /// Gets or sets the level of the logging event. /// </summary> public LogLevel Level { get; set; } /// <summary> /// Gets a value indicating whether stack trace has been set for this event. /// </summary> public bool HasStackTrace { get { return this.StackTrace != null; } } /// <summary> /// Gets the stack frame of the method that did the logging. /// </summary> public StackFrame UserStackFrame { get { return (this.StackTrace != null) ? this.StackTrace.GetFrame(this.UserStackFrameNumber) : null; } } /// <summary> /// Gets the number index of the stack frame that represents the user /// code (not the NLog code). /// </summary> public int UserStackFrameNumber { get; private set; } /// <summary> /// Gets the entire stack trace. /// </summary> public StackTrace StackTrace { get; private set; } /// <summary> /// Gets or sets the exception information. /// </summary> public Exception Exception { get; set; } /// <summary> /// Gets or sets the logger name. /// </summary> public string LoggerName { get; set; } /// <summary> /// Gets the logger short name. /// </summary> [Obsolete("This property should not be used.")] public string LoggerShortName { get { int lastDot = this.LoggerName.LastIndexOf('.'); if (lastDot >= 0) { return this.LoggerName.Substring(lastDot + 1); } return this.LoggerName; } } /// <summary> /// Gets or sets the log message including any parameter placeholders. /// </summary> public string Message { get; set; } /// <summary> /// Gets or sets the parameter values or null if no parameters have been specified. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "For backwards compatibility.")] public object[] Parameters { get; set; } /// <summary> /// Gets or sets the format provider that was provided while logging or <see langword="null" /> /// when no formatProvider was specified. /// </summary> public IFormatProvider FormatProvider { get; set; } /// <summary> /// Gets the formatted message. /// </summary> public string FormattedMessage { get { if (this.formattedMessage == null) { this.CalcFormattedMessage(); } return this.formattedMessage; } } /// <summary> /// Gets the dictionary of per-event context properties. /// </summary> public IDictionary<object, object> Properties { get { if (this.properties == null) { this.InitEventContext(); } return this.properties; } } /// <summary> /// Gets the dictionary of per-event context properties. /// </summary> [Obsolete("Use LogEventInfo.Properties instead.", true)] public IDictionary Context { get { if (this.eventContextAdapter == null) { this.InitEventContext(); } return this.eventContextAdapter; } } /// <summary> /// Creates the null event. /// </summary> /// <returns>Null log event.</returns> public static LogEventInfo CreateNullEvent() { return new LogEventInfo(LogLevel.Off, string.Empty, string.Empty); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Name of the logger.</param> /// <param name="message">The message.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message) { return new LogEventInfo(logLevel, loggerName, null, message, null); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Name of the logger.</param> /// <param name="formatProvider">The format provider.</param> /// <param name="message">The message.</param> /// <param name="parameters">The parameters.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters) { return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Name of the logger.</param> /// <param name="formatProvider">The format provider.</param> /// <param name="message">The message.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, object message) { return new LogEventInfo(logLevel, loggerName, formatProvider, "{0}", new[] { message }); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Name of the logger.</param> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message, Exception exception) { return new LogEventInfo(logLevel, loggerName, null, message, null, exception); } /// <summary> /// Creates <see cref="AsyncLogEventInfo"/> from this <see cref="LogEventInfo"/> by attaching the specified asynchronous continuation. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <returns>Instance of <see cref="AsyncLogEventInfo"/> with attached continuation.</returns> public AsyncLogEventInfo WithContinuation(AsyncContinuation asyncContinuation) { return new AsyncLogEventInfo(this, asyncContinuation); } /// <summary> /// Returns a string representation of this log event. /// </summary> /// <returns>String representation of the log event.</returns> public override string ToString() { return "Log Event: Logger='" + this.LoggerName + "' Level=" + this.Level + " Message='" + this.FormattedMessage + "' SequenceID=" + this.SequenceID; } /// <summary> /// Sets the stack trace for the event info. /// </summary> /// <param name="stackTrace">The stack trace.</param> /// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param> public void SetStackTrace(StackTrace stackTrace, int userStackFrame) { this.StackTrace = stackTrace; this.UserStackFrameNumber = userStackFrame; } internal string AddCachedLayoutValue(Layout layout, string value) { lock (this.layoutCacheLock) { if (this.layoutCache == null) { this.layoutCache = new Dictionary<Layout, string>(); } this.layoutCache[layout] = value; } return value; } internal bool TryGetCachedLayoutValue(Layout layout, out string value) { lock (this.layoutCacheLock) { if (this.layoutCache == null) { value = null; return false; } return this.layoutCache.TryGetValue(layout, out value); } } private static bool NeedToPreformatMessage(object[] parameters) { // we need to preformat message if it contains any parameters which could possibly // do logging in their ToString() if (parameters == null || parameters.Length == 0) { return false; } if (parameters.Length > 3) { // too many parameters, too costly to check return true; } if (!IsSafeToDeferFormatting(parameters[0])) { return true; } if (parameters.Length >= 2) { if (!IsSafeToDeferFormatting(parameters[1])) { return true; } } if (parameters.Length >= 3) { if (!IsSafeToDeferFormatting(parameters[2])) { return true; } } return false; } private static bool IsSafeToDeferFormatting(object value) { if (value == null) { return true; } return value.GetType().IsPrimitive || (value is string); } private void CalcFormattedMessage() { if (this.Parameters == null || this.Parameters.Length == 0) { this.formattedMessage = this.Message; } else { try { this.formattedMessage = string.Format(this.FormatProvider ?? LogManager.DefaultCultureInfo(), this.Message, this.Parameters); } catch (Exception exception) { this.formattedMessage = this.Message; if (exception.MustBeRethrown()) { throw; } InternalLogger.Warn("Error when formatting a message: {0}", exception); } } } private void InitEventContext() { this.properties = new Dictionary<object, object>(); this.eventContextAdapter = new DictionaryAdapter<object, object>(this.properties); } } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.Linq.Expressions; using Xunit; namespace Moq.Tests { public class MockRepositoryFixture { [Fact] public void ShouldCreateFactoryWithMockBehaviorAndVerificationBehavior() { var repository = new MockRepository(MockBehavior.Loose); Assert.NotNull(repository); } [Fact] public void ShouldCreateMocksWithFactoryBehavior() { var repository = new MockRepository(MockBehavior.Loose); var mock = repository.Create<IFormatProvider>(); Assert.Equal(MockBehavior.Loose, mock.Behavior); } [Fact] public void ShouldCreateMockWithConstructorArgs() { var repository = new MockRepository(MockBehavior.Loose); var mock = repository.Create<BaseClass>("foo"); Assert.Equal("foo", mock.Object.Value); } [Fact] public void ShouldCreateMockWithCtorLambda() { var repository = new MockRepository(MockBehavior.Loose); var mock = repository.Create(() => new ClassWithoutParameterlessConstructor("foo")); Assert.Equal("foo", mock.Object.Value); } [Fact] public void ShouldVerifyAll() { try { var repository = new MockRepository(MockBehavior.Default); var mock = repository.Create<IFoo>(); mock.Setup(foo => foo.Do()); repository.VerifyAll(); } catch (MockException mex) { Assert.Equal(MockExceptionReasons.UnmatchedSetup, mex.Reasons); } } [Fact] public void ShouldVerifyNoOtherCalls() { var repository = new MockRepository(MockBehavior.Default); repository.Create<IFoo>(); repository.VerifyNoOtherCalls(); } [Fact] public void ShouldVerifyNoOtherCalls_WhenUnmatched() { var repository = new MockRepository(MockBehavior.Default); var mock = repository.Create<IFoo>(); mock.Object.Do(); var mex = Assert.Throws<MockException>(() => repository.VerifyNoOtherCalls()); Assert.Equal(MockExceptionReasons.UnverifiedInvocations, mex.Reasons); } [Fact] public void ShouldVerifyNoOtherCalls_WhenVerified() { var repository = new MockRepository(MockBehavior.Default); var mock = repository.Create<IFoo>(); mock.Object.Do(); mock.Verify(foo => foo.Do(), Times.Once); repository.VerifyNoOtherCalls(); } [Fact] public void VerifyNoOtherCalls_should_correctly_aggregate_unmatched_calls_from_more_than_one_mock() { var repository = new MockRepository(MockBehavior.Default); var fooMock = repository.Create<IFoo>(); var barMock = repository.Create<IBar>(); fooMock.Object.Do(); barMock.Object.Redo(); var ex = Record.Exception(() => repository.VerifyNoOtherCalls()); Assert.NotNull(ex); Assert.True(ex.Message.ContainsConsecutiveLines( $" {fooMock}:", $" This mock failed verification due to the following unverified invocations:", $" ", $" MockRepositoryFixture.IFoo.Do()")); Assert.True(ex.Message.ContainsConsecutiveLines( $" {barMock}:", $" This mock failed verification due to the following unverified invocations:", $" ", $" MockRepositoryFixture.IBar.Redo()")); } [Fact] public void ShouldVerifyVerifiables() { try { var repository = new MockRepository(MockBehavior.Default); var mock = repository.Create<IFoo>(); mock.Setup(foo => foo.Do()); mock.Setup(foo => foo.Undo()).Verifiable(); repository.Verify(); } catch (MockException mex) { Assert.Equal(MockExceptionReasons.UnmatchedSetup, mex.Reasons); Expression<Action<IFoo>> doExpr = foo => foo.Do(); Assert.DoesNotContain(doExpr.ToString(), mex.Message); } } [Fact] public void ShouldAggregateFailures() { var repository = new MockRepository(MockBehavior.Loose); var foo = repository.Create<IFoo>(); var bar = repository.Create<IBar>(); foo.Setup(f => f.Do()); bar.Setup(b => b.Redo()); var ex = Record.Exception(() => repository.VerifyAll()); Assert.NotNull(ex); Assert.True(ex.Message.ContainsConsecutiveLines( $" {foo}:", $" This mock failed verification due to the following:", $" ", $" MockRepositoryFixture.IFoo f => f.Do():")); Assert.True(ex.Message.ContainsConsecutiveLines( $" {bar}:", $" This mock failed verification due to the following:", $" ", $" MockRepositoryFixture.IBar b => b.Redo()")); } [Fact] public void ShouldOverrideDefaultBehavior() { var repository = new MockRepository(MockBehavior.Loose); var mock = repository.Create<IFoo>(MockBehavior.Strict); Assert.Equal(MockBehavior.Strict, mock.Behavior); } [Fact] public void ShouldOverrideDefaultBehaviorWithCtorArgs() { var repository = new MockRepository(MockBehavior.Loose); var mock = repository.Create<BaseClass>(MockBehavior.Strict, "Foo"); Assert.Equal(MockBehavior.Strict, mock.Behavior); Assert.Equal("Foo", mock.Object.Value); } [Fact] public void ShouldCreateMocksWithFactoryDefaultValue() { var repository = new MockRepository(MockBehavior.Loose) { DefaultValue = DefaultValue.Mock }; var mock = repository.Create<IFoo>(); Assert.NotNull(mock.Object.Bar()); } [Fact] public void ShouldCreateMocksWithFactoryCallBase() { var repository = new MockRepository(MockBehavior.Loose); var mock = repository.Create<BaseClass>(); mock.Object.BaseMethod(); Assert.False(mock.Object.BaseCalled); repository.CallBase = true; mock = repository.Create<BaseClass>(); mock.Object.BaseMethod(); Assert.True(mock.Object.BaseCalled); } [Fact] public void DefaultValue_can_be_set_to_Empty() { var mockRepository = new MockRepository(MockBehavior.Default); mockRepository.DefaultValue = DefaultValue.Empty; Assert.Equal(DefaultValue.Empty, mockRepository.DefaultValue); } [Fact] public void DefaultValue_can_be_set_to_Mock() { var mockRepository = new MockRepository(MockBehavior.Default); mockRepository.DefaultValue = DefaultValue.Mock; Assert.Equal(DefaultValue.Mock, mockRepository.DefaultValue); } [Theory] [InlineData(DefaultValue.Custom)] [InlineData((DefaultValue)(-1))] public void DefaultValue_cannot_be_set_to_anything_other_than_Empty_or_Mock(DefaultValue defaultValue) { var mockRepository = new MockRepository(MockBehavior.Default); Assert.Throws<ArgumentOutOfRangeException>(() => { mockRepository.DefaultValue = defaultValue; }); } [Fact] public void DefaultValueProvider_cannot_be_set_to_null() { var mockRepository = new MockRepository(MockBehavior.Default); Assert.Throws<ArgumentNullException>(() => { mockRepository.DefaultValueProvider = null; }); } [Fact] public void Repository_initially_uses_default_switches() { var repository = new MockRepository(MockBehavior.Default); Assert.Equal(Switches.Default, actual: repository.Switches); } [Fact] public void Mock_inherits_switches_from_repository() { const Switches expectedSwitches = Switches.CollectDiagnosticFileInfoForSetups; var repository = new MockRepository(MockBehavior.Default) { Switches = expectedSwitches }; var mock = repository.Create<IFoo>(); Assert.Equal(expectedSwitches, actual: mock.Switches); } public interface IFoo { void Do(); void Undo(); IBar Bar(); } public interface IBar { void Redo(); } public abstract class BaseClass { public bool BaseCalled; public BaseClass() { } public BaseClass(string value) { this.Value = value; } public string Value { get; set; } public virtual void BaseMethod() { BaseCalled = true; } } public class ClassWithoutParameterlessConstructor : BaseClass { public ClassWithoutParameterlessConstructor(string value) : base(value) { } } } }
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 MvcVsWebApi.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; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP { #region usings using System; using AUTH; using Message; using MIME; using Stack; #endregion /// <summary> /// SIP helper methods. /// </summary> public class SIP_Utils { #region Methods /// <summary> /// Parses address from SIP To: header field. /// </summary> /// <param name="to">SIP header To: value.</param> /// <returns></returns> public static string ParseAddress(string to) { try { string retVal = to; if (to.IndexOf('<') > -1 && to.IndexOf('<') < to.IndexOf('>')) { retVal = to.Substring(to.IndexOf('<') + 1, to.IndexOf('>') - to.IndexOf('<') - 1); } // Remove sip: if (retVal.IndexOf(':') > -1) { retVal = retVal.Substring(retVal.IndexOf(':') + 1).Split(':')[0]; } return retVal; } catch { throw new ArgumentException("Invalid SIP header To: '" + to + "' value !"); } } /// <summary> /// Converts URI to Request-URI by removing all not allowed Request-URI parameters from URI. /// </summary> /// <param name="uri">URI value.</param> /// <returns>Returns valid Request-URI value.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>uri</b> is null reference.</exception> public static AbsoluteUri UriToRequestUri(AbsoluteUri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } if (uri is SIP_Uri) { // RFC 3261 19.1.2.(Table) // We need to strip off "method-param" and "header" URI parameters". // Currently we do it for sip or sips uri, do we need todo it for others too ? SIP_Uri sUri = (SIP_Uri) uri; sUri.Parameters.Remove("method"); sUri.Header = null; return sUri; } else { return uri; } } /// <summary> /// Gets if specified value is SIP or SIPS URI. /// </summary> /// <param name="value">Value to check.</param> /// <returns>Returns true if specified value is SIP or SIPS URI, otherwise false.</returns> public static bool IsSipOrSipsUri(string value) { try { SIP_Uri.Parse(value); return true; } catch {} return false; } /// <summary> /// Gets if specified URI is tel: or sip tel URI. There is special case when SIP URI can be tel:, /// sip:+xxxx and sip:xxx;user=phone. /// </summary> /// <param name="uri">URI to check.</param> /// <returns>Returns true if specified URI is tel: URI.</returns> public static bool IsTelUri(string uri) { uri = uri.ToLower(); try { if (uri.StartsWith("tel:")) { return true; } else if (IsSipOrSipsUri(uri)) { SIP_Uri sipUri = SIP_Uri.Parse(uri); // RFC 3398 12. If user part starts with +, it's tel: URI. if (sipUri.User.StartsWith("+")) { return true; } // RFC 3398 12. else if (sipUri.Param_User != null && sipUri.Param_User.ToLower() == "phone") { return true; } } } catch {} return false; } /// <summary> /// Gets specified realm SIP proxy credentials. Returns null if none exists for specified realm. /// </summary> /// <param name="request">SIP reques.</param> /// <param name="realm">Realm(domain).</param> /// <returns>Returns specified realm credentials or null if none.</returns> public static SIP_t_Credentials GetCredentials(SIP_Request request, string realm) { foreach ( SIP_SingleValueHF<SIP_t_Credentials> authorization in request.ProxyAuthorization.HeaderFields) { if (authorization.ValueX.Method.ToLower() == "digest") { Auth_HttpDigest authDigest = new Auth_HttpDigest(authorization.ValueX.AuthData, request.RequestLine.Method); if (authDigest.Realm.ToLower() == realm.ToLower()) { return authorization.ValueX; } } } return null; } /// <summary> /// Gets is specified option tags constains specified option tag. /// </summary> /// <param name="tags">Option tags.</param> /// <param name="tag">Option tag to check.</param> /// <returns>Returns true if specified option tag exists.</returns> public static bool ContainsOptionTag(SIP_t_OptionTag[] tags, string tag) { foreach (SIP_t_OptionTag t in tags) { if (t.OptionTag.ToLower() == tag) { return true; } } return false; } /// <summary> /// Gets if specified method can establish dialog. /// </summary> /// <param name="method">SIP method.</param> /// <returns>Returns true if specified SIP method can establish dialog, otherwise false.</returns> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public static bool MethodCanEstablishDialog(string method) { if (string.IsNullOrEmpty(method)) { throw new ArgumentException("Argument 'method' value can't be null or empty !"); } method = method.ToUpper(); if (method == SIP_Methods.INVITE) { return true; } else if (method == SIP_Methods.SUBSCRIBE) { return true; } else if (method == SIP_Methods.REFER) { return true; } return false; } /// <summary> /// Creates tag for tag header filed. For example From:/To: tag value. /// </summary> /// <returns>Returns tag string.</returns> public static string CreateTag() { return Guid.NewGuid().ToString().Replace("-", "").Substring(8); } /// <summary> /// Gets if the specified transport is reliable transport. /// </summary> /// <param name="transport">SIP transport.</param> /// <returns>Returns if specified transport is reliable.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>transport</b> is null reference.</exception> public static bool IsReliableTransport(string transport) { if (transport == null) { throw new ArgumentNullException("transport"); } if (transport.ToUpper() == SIP_Transport.TCP) { return true; } else if (transport.ToUpper() == SIP_Transport.TLS) { return true; } else { return false; } } /// <summary> /// Gets if the specified value is "token". /// </summary> /// <param name="value">Value to check.</param> /// <returns>Returns true if specified valu is token, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> public static bool IsToken(string value) { if (value == null) { throw new ArgumentNullException("value"); } return MIME_Reader.IsToken(value); } #endregion } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Cassandra.IntegrationTests.Policies.Util; using Cassandra.IntegrationTests.TestBase; using Cassandra.IntegrationTests.TestClusterManagement; using Cassandra.Serialization; using NUnit.Framework; namespace Cassandra.IntegrationTests.Policies.Tests { [TestFixture, Category("long"), Ignore("tests that are not marked with 'short' need to be refactored/deleted")] public class LoadBalancingPolicyTests : TestGlobals { /// <summary> /// Using a default round robin load balancing policy, connected to a cluster with one DC, /// validate that the session behaves as expected when a node is added and then another is decommissioned. /// /// @test_category consistency /// @test_category connection:outage /// @test_category load_balancing:round_robin /// </summary> [Test] public void RoundRobin_OneDc_OneNodeAdded_OneNodeDecommissioned() { // Setup PolicyTestTools policyTestTools = new PolicyTestTools(); ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(1); testCluster.Builder = Cluster.Builder().WithLoadBalancingPolicy(new RoundRobinPolicy()); testCluster.InitClient(); policyTestTools.CreateSchema(testCluster.Session); policyTestTools.InitPreparedStatement(testCluster, 12); policyTestTools.Query(testCluster, 12); // Validate that all host were queried equally policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 12); // Add new node to the end of second cluster, remove node from beginning of first cluster policyTestTools.ResetCoordinators(); // Bootstrap step int bootStrapPos = 2; testCluster.BootstrapNode(bootStrapPos); string newlyBootstrappedIp = testCluster.ClusterIpPrefix + bootStrapPos; TestUtils.WaitForUp(newlyBootstrappedIp, DefaultCassandraPort, 30); // Validate expected nodes where queried policyTestTools.WaitForPolicyToolsQueryToHitBootstrappedIp(testCluster, newlyBootstrappedIp); policyTestTools.Query(testCluster, 12); policyTestTools.AssertQueriedAtLeast(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 6); policyTestTools.AssertQueriedAtLeast(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 6); // decommission old node policyTestTools.ResetCoordinators(); testCluster.DecommissionNode(1); TestUtils.waitForDecommission(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, testCluster.Cluster, 60); policyTestTools.Query(testCluster, 12); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 12); } /// <summary> /// Using a default round robin load balancing policy, connected to a cluster with multiple DCs, /// validate that the session behaves as expected when a node is added and then another is decommissioned from each DC. /// /// @test_category consistency /// @test_category connection:outage /// @test_category load_balancing:round_robin /// </summary> [Test] public void RoundRobin_TwoDCs_EachDcHasOneNodeAddedAndDecommissioned() { // Setup PolicyTestTools policyTestTools = new PolicyTestTools(); ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(1, 1, DefaultMaxClusterCreateRetries, true); testCluster.Builder = Cluster.Builder().WithLoadBalancingPolicy(new RoundRobinPolicy()); testCluster.InitClient(); policyTestTools.CreateSchema(testCluster.Session); policyTestTools.InitPreparedStatement(testCluster, 12); policyTestTools.Query(testCluster, 12); // Validate that all host were queried equally policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 6); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 6); // Add new node to the end of first cluster, remove node from beginning of first cluster policyTestTools.ResetCoordinators(); // Bootstrap step testCluster.BootstrapNode(3, "dc1"); string newlyBootstrappedIp = testCluster.ClusterIpPrefix + "3"; TestUtils.WaitForUp(newlyBootstrappedIp, DefaultCassandraPort, 30); // Validate expected nodes where queried policyTestTools.WaitForPolicyToolsQueryToHitBootstrappedIp(testCluster, newlyBootstrappedIp); policyTestTools.Query(testCluster, 12); policyTestTools.AssertQueriedAtLeast(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 4); policyTestTools.AssertQueriedAtLeast(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 4); policyTestTools.AssertQueriedAtLeast(testCluster.ClusterIpPrefix + "3:" + DefaultCassandraPort, 4); // Remove node from beginning of first cluster policyTestTools.ResetCoordinators(); testCluster.DecommissionNode(1); TestUtils.waitForDecommission(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, testCluster.Cluster, 20); // Validate expected nodes where queried policyTestTools.Query(testCluster, 12); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 0); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 6); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "3:" + DefaultCassandraPort, 6); // Add new node to the end of second cluster, remove node from beginning of first cluster policyTestTools.ResetCoordinators(); testCluster.BootstrapNode(4, "dc2"); newlyBootstrappedIp = testCluster.ClusterIpPrefix + "4"; TestUtils.WaitForUp(newlyBootstrappedIp, DefaultCassandraPort, 30); policyTestTools.ResetCoordinators(); policyTestTools.Query(testCluster, 12); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 0); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 4); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "3:" + DefaultCassandraPort, 4); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "4:" + DefaultCassandraPort, 4); // Remove node from beginning of second cluster policyTestTools.ResetCoordinators(); testCluster.DecommissionNode(2); TestUtils.waitForDecommission(testCluster.ClusterIpPrefix + "2", testCluster.Cluster, 20); policyTestTools.Query(testCluster, 12); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 0); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 0); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "3:" + DefaultCassandraPort, 6); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "4:" + DefaultCassandraPort, 6); } /// <summary> /// Validated that the driver fails as expected with a non-existing datacenter is specified via DCAwareRoundRobinPolicy /// /// @test_category load_balancing:dc_aware /// </summary> [Test] public void RoundRobin_DcAware_BuildClusterWithNonExistentDc() { ITestCluster testCluster = TestClusterManager.GetTestCluster(1); testCluster.Builder = Cluster.Builder().WithLoadBalancingPolicy(new DCAwareRoundRobinPolicy("dc2")); try { testCluster.InitClient(); Assert.Fail("Expected exception was not thrown!"); } catch (ArgumentException e) { string expectedErrMsg = "Datacenter dc2 does not match any of the nodes, available datacenters: datacenter1."; Assert.IsTrue(e.Message.Contains(expectedErrMsg)); } } /// <summary> /// Validated that the driver only uses the DC specified by DCAwareRoundRobinPolicy /// /// @test_category load_balancing:dc_aware /// </summary> [Test] public void RoundRobin_TwoDCs_DcAware() { // Setup PolicyTestTools policyTestTools = new PolicyTestTools(); ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(1, 1, DefaultMaxClusterCreateRetries, true); testCluster.Builder = Cluster.Builder().WithLoadBalancingPolicy(new DCAwareRoundRobinPolicy("dc2")); testCluster.InitClient(); policyTestTools.CreateMultiDcSchema(testCluster.Session); policyTestTools.InitPreparedStatement(testCluster, 12); policyTestTools.Query(testCluster, 12); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 0); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 12); } /// <summary> /// Validate that the driver behaves as expected as every node of a single DC cluster is force-stopped /// /// @test_category connection:outage /// @test_category load_balancing:dc_aware /// </summary> [Test] public void RoundRobin_OneDc_AllNodesForceStoppedOneAtATime() { // Setup PolicyTestTools policyTestTools = new PolicyTestTools(); ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(2); testCluster.Builder = Cluster.Builder() .WithLoadBalancingPolicy(new RoundRobinPolicy()) .WithQueryTimeout(10000); testCluster.InitClient(); policyTestTools.CreateSchema(testCluster.Session); policyTestTools.InitPreparedStatement(testCluster, 12); policyTestTools.Query(testCluster, 12); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 6); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 6); policyTestTools.ResetCoordinators(); testCluster.StopForce(1); TestUtils.WaitForDown(testCluster.ClusterIpPrefix + "1", testCluster.Cluster, 20); policyTestTools.Query(testCluster, 12); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 0); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 12); testCluster.StopForce(2); TestUtils.WaitForDown(testCluster.ClusterIpPrefix + "2", testCluster.Cluster, 20); try { policyTestTools.Query(testCluster, 3); Assert.Fail("Exception should have been thrown, but wasn't!"); } catch (NoHostAvailableException) { Trace.TraceInformation("Expected NoHostAvailableException exception was thrown."); } } /// <summary> /// Validate that the expected nodes are queried when using a TokenAware RoundRobin policy, /// using two data centers, replication factor 2 /// /// @test_category load_balancing:dc_aware,round_robin /// @test_category replication_strategy /// </summary> [Test] public void RoundRobin_TokenAware_TwoDCsWithOneNodeEach_ReplicationFactorTwo() { // Setup PolicyTestTools policyTestTools = new PolicyTestTools(); ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(1, 1, DefaultMaxClusterCreateRetries, true); testCluster.Builder = Cluster.Builder().WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())); testCluster.InitClient(); policyTestTools.CreateSchema(testCluster.Session, 2); policyTestTools.InitPreparedStatement(testCluster, 12); policyTestTools.Query(testCluster, 12); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 6); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 6); } /// <summary> /// Validate that the expected nodes are queried when using a TokenAware RoundRobin policy, /// executing non-prepared statements /// /// @test_category load_balancing:dc_aware,round_robin /// </summary> [Test] public void RoundRobin_TokenAware_NotPrepared() { TokenAwareTest(false); } /// <summary> /// Validate that the expected nodes are queried when using a TokenAware RoundRobin policy, /// executing prepared statements /// /// @test_category load_balancing:dc_aware,round_robin /// </summary> [Test] public void RoundRobin_TokenAware_Prepared() { TokenAwareTest(true); } public void TokenAwareTest(bool usePrepared) { // Setup PolicyTestTools policyTestTools = new PolicyTestTools(); ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(1, 1, DefaultMaxClusterCreateRetries, true); testCluster.Builder = Cluster.Builder().WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())); testCluster.InitClient(); policyTestTools.CreateSchema(testCluster.Session); //clusterInfo.Cluster.RefreshSchema(); policyTestTools.InitPreparedStatement(testCluster, 12); policyTestTools.Query(testCluster, 12); // Not the best test ever, we should use OPP and check we do it the // right nodes. But since M3P is hard-coded for now, let just check // we just hit only one node. int nodePosToDecommission = 2; int nodePositionToNotDecommission = 1; if (policyTestTools.Coordinators.ContainsKey(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort)) { nodePosToDecommission = 1; nodePositionToNotDecommission = 2; } policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + nodePosToDecommission + ":" + DefaultCassandraPort, 12); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + nodePositionToNotDecommission + ":" + DefaultCassandraPort, 0); // now try again having stopped the node that was just queried policyTestTools.ResetCoordinators(); testCluster.DecommissionNode(nodePosToDecommission); TestUtils.waitForDecommission(testCluster.ClusterIpPrefix + nodePosToDecommission + ":" + DefaultCassandraPort, testCluster.Cluster, 40); policyTestTools.Query(testCluster, 12, usePrepared); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + nodePosToDecommission + ":" + DefaultCassandraPort, 0); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + nodePositionToNotDecommission + ":" + DefaultCassandraPort, 12); } /// Tests that the TokenMap can be rebulit using an existing keyspace's RF, even with a decommisioned DC /// /// TokenMap_Rebuild_With_Decommissioned_DC_Existing_RF tests that a keyspace with a non-existent DC in the replication /// options can be connected. It first creates a 2 datacenter cluster with 1 node in each. It then connects to this cluster /// using dc1 and creates a multi-dc schema which has a replication factor of 1 in each dc. It performs a simple insertion /// and verifies that the reads are performed from dc1 as expected. It then decommissions dc1 by removing its only node, causing /// the keyspace replication factor to point to a non-existing "dc1". It then verifies that the driver is able to reconnect to the /// cluster via dc2. Finally it performs some simple reads to verify that the data is read from dc2. /// /// @since 3.0.1 /// @jira_ticket CSHARP-385 /// @expected_result TokenMap is successfully rebuilt with decomissioned DC, with existing RFs. /// /// @test_category control_connection [Test] public void TokenMap_Rebuild_With_Decommissioned_DC_Existing_RF() { // Create a 2dc:1node each cluster var clusterOptions = new TestClusterOptions(); clusterOptions.Dc2NodeLength = 1; var testCluster = TestClusterManager.CreateNew(1, clusterOptions); testCluster.Builder = Cluster.Builder().AddContactPoint("127.0.0.1").WithLoadBalancingPolicy(new DCAwareRoundRobinPolicy("dc1")); testCluster.Cluster = testCluster.Builder.Build(); testCluster.Session = testCluster.Cluster.Connect(); PolicyTestTools policyTestTools = new PolicyTestTools(); // Create a ks with RF = dc1:1, dc2:1 policyTestTools.CreateMultiDcSchema(testCluster.Session, 1, 1); policyTestTools.InitPreparedStatement(testCluster, 12, false, ConsistencyLevel.All); // Replicas now in each node in each dc policyTestTools.Query(testCluster, 12, false); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 12); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 0); testCluster.Cluster.Shutdown(); testCluster.DecommissionNode(1); // dc1 no longer has any hosts testCluster.Builder = Cluster.Builder().AddContactPoint("127.0.0.2").WithLoadBalancingPolicy(new DCAwareRoundRobinPolicy("dc2")); testCluster.Cluster = testCluster.Builder.Build(); // Should be able to connect and rebuild token map testCluster.Session = testCluster.Cluster.Connect(policyTestTools.DefaultKeyspace); policyTestTools.ResetCoordinators(); policyTestTools.Query(testCluster, 12, false); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 0); policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 12); testCluster.Cluster.Shutdown(); } } }
// Copyright (c) 2015 ZZZ Projects. All rights reserved // Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods) // Website: http://www.zzzprojects.com/ // Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927 // All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library using System; using System.IO; using System.Linq; public static partial class Extensions { /// <summary> /// Returns an enumerable collection of file-system entries in a specified @this. /// </summary> /// <param name="this">The directory to search.</param> /// <param name="predicate">The predicate.</param> /// <returns> /// An enumerable collection of file-system entries in the directory specified by <paramref name="this" />. /// </returns> /// ### /// <exception cref="T:System.ArgumentException"> /// <paramref name="this " />is a zero-length string, contains only /// white space, or contains invalid characters as defined by /// <see /// cref="M:System.IO.Path.GetInvalidPathChars" /> /// . /// </exception> /// ### /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="this" /> is null. /// </exception> /// ### /// <exception cref="T:System.IO.DirectoryNotFoundException"> /// <paramref name="this" /> is invalid, such as /// referring to an unmapped drive. /// </exception> /// ### /// <exception cref="T:System.IO.IOException"> /// <paramref name="this" /> is a file name. /// </exception> /// ### /// <exception cref="T:System.IO.PathTooLongException"> /// The specified @this, file name, or combined exceed the /// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters /// and file names must be less than 260 characters. /// </exception> /// ### /// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception> /// ### /// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception> public static string[] GetFileSystemEntriesWhere(this DirectoryInfo @this, Func<string, bool> predicate) { return Directory.EnumerateFileSystemEntries(@this.FullName).Where(x => predicate(x)).ToArray(); } /// <summary> /// Returns an enumerable collection of file-system entries that match a search pattern in a specified @this. /// </summary> /// <param name="this">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in /// <paramref name="this" />. /// </param> /// <param name="predicate">The predicate.</param> /// <returns> /// An enumerable collection of file-system entries in the directory specified by <paramref name="this" /> and /// that match the specified search pattern. /// </returns> /// <example> /// <code> /// using System; /// using System.IO; /// using Microsoft.VisualStudio.TestTools.UnitTesting; /// /// /// namespace ExtensionMethods.Examples /// { /// [TestClass] /// public class System_IO_DirectoryInfo_GetFileSystemEntriesWhere /// { /// [TestMethod] /// public void GetFileSystemEntriesWhere() /// { /// // Type /// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, &quot;System_IO_DirectoryInfo_GetFileSystemEntriesWhere&quot;)); /// Directory.CreateDirectory(root.FullName); /// root.CreateSubdirectory(&quot;DirFizz123&quot;); /// root.CreateSubdirectory(&quot;DirBuzz123&quot;); /// var file1 = new FileInfo(Path.Combine(root.FullName, &quot;test1.txt&quot;)); /// file1.Create(); /// /// // Exemples /// string[] result = root.GetFileSystemEntriesWhere(x =&gt; x.Contains(&quot;DirFizz&quot;) || x.EndsWith(&quot;.txt&quot;)); /// /// // Unit Test /// Assert.AreEqual(2, result.Length); /// } /// } /// } /// </code> /// </example> /// <example> /// <code> /// using System; /// using System.IO; /// using Microsoft.VisualStudio.TestTools.UnitTesting; /// using Z.ExtensionMethods; /// /// namespace ExtensionMethods.Examples /// { /// [TestClass] /// public class System_IO_DirectoryInfo_GetFileSystemEntriesWhere /// { /// [TestMethod] /// public void GetFileSystemEntriesWhere() /// { /// // Type /// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, &quot;System_IO_DirectoryInfo_GetFileSystemEntriesWhere&quot;)); /// Directory.CreateDirectory(root.FullName); /// root.CreateSubdirectory(&quot;DirFizz123&quot;); /// root.CreateSubdirectory(&quot;DirBuzz123&quot;); /// var file1 = new FileInfo(Path.Combine(root.FullName, &quot;test1.txt&quot;)); /// file1.Create(); /// /// // Exemples /// string[] result = root.GetFileSystemEntriesWhere(x =&gt; x.Contains(&quot;DirFizz&quot;) || x.EndsWith(&quot;.txt&quot;)); /// /// // Unit Test /// Assert.AreEqual(2, result.Length); /// } /// } /// } /// </code> /// </example> /// ### /// <exception cref="T:System.ArgumentException"> /// <paramref name="this " />is a zero-length string, contains only /// white space, or contains invalid characters as defined by /// <see /// cref="M:System.IO.Path.GetInvalidPathChars" /> /// .- or -<paramref name="searchPattern" /> does not contain a valid pattern. /// </exception> /// ### /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="this" /> is null.-or- /// <paramref name="searchPattern" /> is null. /// </exception> /// ### /// <exception cref="T:System.IO.DirectoryNotFoundException"> /// <paramref name="this" /> is invalid, such as /// referring to an unmapped drive. /// </exception> /// ### /// <exception cref="T:System.IO.IOException"> /// <paramref name="this" /> is a file name. /// </exception> /// ### /// <exception cref="T:System.IO.PathTooLongException"> /// The specified @this, file name, or combined exceed the /// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters /// and file names must be less than 260 characters. /// </exception> /// ### /// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception> /// ### /// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception> public static string[] GetFileSystemEntriesWhere(this DirectoryInfo @this, String searchPattern, Func<string, bool> predicate) { return Directory.EnumerateFileSystemEntries(@this.FullName, searchPattern).Where(x => predicate(x)).ToArray(); } /// <summary> /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified /// @this, and optionally searches subdirectories. /// </summary> /// <param name="this">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in /// <paramref name="this" />. /// </param> /// <param name="searchOption"> /// One of the enumeration values that specifies whether the search operation should /// include only the current directory or should include all subdirectories.The default value is /// <see /// cref="F:System.IO.SearchOption.TopDirectoryOnly" /> /// . /// </param> /// <param name="predicate">The predicate.</param> /// <returns> /// An enumerable collection of file-system entries in the directory specified by <paramref name="this" /> and /// that match the specified search pattern and option. /// </returns> /// <example> /// <code> /// using System; /// using System.IO; /// using Microsoft.VisualStudio.TestTools.UnitTesting; /// /// /// namespace ExtensionMethods.Examples /// { /// [TestClass] /// public class System_IO_DirectoryInfo_GetFileSystemEntriesWhere /// { /// [TestMethod] /// public void GetFileSystemEntriesWhere() /// { /// // Type /// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, &quot;System_IO_DirectoryInfo_GetFileSystemEntriesWhere&quot;)); /// Directory.CreateDirectory(root.FullName); /// root.CreateSubdirectory(&quot;DirFizz123&quot;); /// root.CreateSubdirectory(&quot;DirBuzz123&quot;); /// var file1 = new FileInfo(Path.Combine(root.FullName, &quot;test1.txt&quot;)); /// file1.Create(); /// /// // Exemples /// string[] result = root.GetFileSystemEntriesWhere(x =&gt; x.Contains(&quot;DirFizz&quot;) || x.EndsWith(&quot;.txt&quot;)); /// /// // Unit Test /// Assert.AreEqual(2, result.Length); /// } /// } /// } /// </code> /// </example> /// <example> /// <code> /// using System; /// using System.IO; /// using Microsoft.VisualStudio.TestTools.UnitTesting; /// using Z.ExtensionMethods; /// /// namespace ExtensionMethods.Examples /// { /// [TestClass] /// public class System_IO_DirectoryInfo_GetFileSystemEntriesWhere /// { /// [TestMethod] /// public void GetFileSystemEntriesWhere() /// { /// // Type /// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, &quot;System_IO_DirectoryInfo_GetFileSystemEntriesWhere&quot;)); /// Directory.CreateDirectory(root.FullName); /// root.CreateSubdirectory(&quot;DirFizz123&quot;); /// root.CreateSubdirectory(&quot;DirBuzz123&quot;); /// var file1 = new FileInfo(Path.Combine(root.FullName, &quot;test1.txt&quot;)); /// file1.Create(); /// /// // Exemples /// string[] result = root.GetFileSystemEntriesWhere(x =&gt; x.Contains(&quot;DirFizz&quot;) || x.EndsWith(&quot;.txt&quot;)); /// /// // Unit Test /// Assert.AreEqual(2, result.Length); /// } /// } /// } /// </code> /// </example> /// ### /// <exception cref="T:System.ArgumentException"> /// <paramref name="this " />is a zero-length string, contains only /// white space, or contains invalid characters as defined by /// <see /// cref="M:System.IO.Path.GetInvalidPathChars" /> /// .- or -<paramref name="searchPattern" /> does not contain a valid pattern. /// </exception> /// ### /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="this" /> is null.-or- /// <paramref name="searchPattern" /> is null. /// </exception> /// ### /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="searchOption" /> is not a valid /// <see cref="T:System.IO.SearchOption" /> value. /// </exception> /// ### /// <exception cref="T:System.IO.DirectoryNotFoundException"> /// <paramref name="this" /> is invalid, such as /// referring to an unmapped drive. /// </exception> /// ### /// <exception cref="T:System.IO.IOException"> /// <paramref name="this" /> is a file name. /// </exception> /// ### /// <exception cref="T:System.IO.PathTooLongException"> /// The specified @this, file name, or combined exceed the /// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters /// and file names must be less than 260 characters. /// </exception> /// ### /// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception> /// ### /// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception> public static string[] GetFileSystemEntriesWhere(this DirectoryInfo @this, String searchPattern, SearchOption searchOption, Func<string, bool> predicate) { return Directory.EnumerateFileSystemEntries(@this.FullName, searchPattern, searchOption).Where(x => predicate(x)).ToArray(); } /// <summary> /// Returns an enumerable collection of file-system entries that match a search pattern in a specified @this. /// </summary> /// <param name="this">The directory to search.</param> /// <param name="searchPatterns">The search string to match against the names of directories in.</param> /// <param name="predicate">The predicate.</param> /// <returns> /// An enumerable collection of file-system entries in the directory specified by <paramref name="this" /> and /// that match the specified search pattern. /// </returns> /// <example> /// <code> /// using System; /// using System.IO; /// using Microsoft.VisualStudio.TestTools.UnitTesting; /// /// /// namespace ExtensionMethods.Examples /// { /// [TestClass] /// public class System_IO_DirectoryInfo_GetFileSystemEntriesWhere /// { /// [TestMethod] /// public void GetFileSystemEntriesWhere() /// { /// // Type /// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, &quot;System_IO_DirectoryInfo_GetFileSystemEntriesWhere&quot;)); /// Directory.CreateDirectory(root.FullName); /// root.CreateSubdirectory(&quot;DirFizz123&quot;); /// root.CreateSubdirectory(&quot;DirBuzz123&quot;); /// var file1 = new FileInfo(Path.Combine(root.FullName, &quot;test1.txt&quot;)); /// file1.Create(); /// /// // Exemples /// string[] result = root.GetFileSystemEntriesWhere(x =&gt; x.Contains(&quot;DirFizz&quot;) || x.EndsWith(&quot;.txt&quot;)); /// /// // Unit Test /// Assert.AreEqual(2, result.Length); /// } /// } /// } /// </code> /// </example> /// <example> /// <code> /// using System; /// using System.IO; /// using Microsoft.VisualStudio.TestTools.UnitTesting; /// using Z.ExtensionMethods; /// /// namespace ExtensionMethods.Examples /// { /// [TestClass] /// public class System_IO_DirectoryInfo_GetFileSystemEntriesWhere /// { /// [TestMethod] /// public void GetFileSystemEntriesWhere() /// { /// // Type /// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, &quot;System_IO_DirectoryInfo_GetFileSystemEntriesWhere&quot;)); /// Directory.CreateDirectory(root.FullName); /// root.CreateSubdirectory(&quot;DirFizz123&quot;); /// root.CreateSubdirectory(&quot;DirBuzz123&quot;); /// var file1 = new FileInfo(Path.Combine(root.FullName, &quot;test1.txt&quot;)); /// file1.Create(); /// /// // Exemples /// string[] result = root.GetFileSystemEntriesWhere(x =&gt; x.Contains(&quot;DirFizz&quot;) || x.EndsWith(&quot;.txt&quot;)); /// /// // Unit Test /// Assert.AreEqual(2, result.Length); /// } /// } /// } /// </code> /// </example> /// ### /// <param name="searchPattern"> /// The search string to match against the names of directories in /// <paramref name="this" />. /// </param> /// ### /// <exception cref="T:System.ArgumentException"> /// <paramref name="this " />is a zero-length string, contains only /// white space, or contains invalid characters as defined by /// <see /// cref="M:System.IO.Path.GetInvalidPathChars" /> /// .- or -<paramref name="searchPattern" /> does not contain a valid pattern. /// </exception> /// ### /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="this" /> is null.-or- /// <paramref name="searchPattern" /> is null. /// </exception> /// ### /// <exception cref="T:System.IO.DirectoryNotFoundException"> /// <paramref name="this" /> is invalid, such as /// referring to an unmapped drive. /// </exception> /// ### /// <exception cref="T:System.IO.IOException"> /// <paramref name="this" /> is a file name. /// </exception> /// ### /// <exception cref="T:System.IO.PathTooLongException"> /// The specified @this, file name, or combined exceed the /// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters /// and file names must be less than 260 characters. /// </exception> /// ### /// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception> /// ### /// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception> public static string[] GetFileSystemEntriesWhere(this DirectoryInfo @this, String[] searchPatterns, Func<string, bool> predicate) { return searchPatterns.SelectMany(x => Directory.EnumerateFileSystemEntries(@this.FullName, x)).Distinct().Where(x => predicate(x)).ToArray(); } /// <summary> /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified /// @this, and optionally searches subdirectories. /// </summary> /// <param name="this">The directory to search.</param> /// <param name="searchPatterns"> /// The search string to match against the names of directories in /// <paramref name="this" />. /// </param> /// <param name="searchOption"> /// One of the enumeration values that specifies whether the search operation should /// include only the current directory or should include all subdirectories.The default value is /// <see /// cref="F:System.IO.SearchOption.TopDirectoryOnly" /> /// . /// </param> /// <param name="predicate">The predicate.</param> /// <returns> /// An enumerable collection of file-system entries in the directory specified by <paramref name="this" /> and /// that match the specified search pattern and option. /// </returns> /// <example> /// <code> /// using System; /// using System.IO; /// using Microsoft.VisualStudio.TestTools.UnitTesting; /// /// /// namespace ExtensionMethods.Examples /// { /// [TestClass] /// public class System_IO_DirectoryInfo_GetFileSystemEntriesWhere /// { /// [TestMethod] /// public void GetFileSystemEntriesWhere() /// { /// // Type /// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, &quot;System_IO_DirectoryInfo_GetFileSystemEntriesWhere&quot;)); /// Directory.CreateDirectory(root.FullName); /// root.CreateSubdirectory(&quot;DirFizz123&quot;); /// root.CreateSubdirectory(&quot;DirBuzz123&quot;); /// var file1 = new FileInfo(Path.Combine(root.FullName, &quot;test1.txt&quot;)); /// file1.Create(); /// /// // Exemples /// string[] result = root.GetFileSystemEntriesWhere(x =&gt; x.Contains(&quot;DirFizz&quot;) || x.EndsWith(&quot;.txt&quot;)); /// /// // Unit Test /// Assert.AreEqual(2, result.Length); /// } /// } /// } /// </code> /// </example> /// <example> /// <code> /// using System; /// using System.IO; /// using Microsoft.VisualStudio.TestTools.UnitTesting; /// using Z.ExtensionMethods; /// /// namespace ExtensionMethods.Examples /// { /// [TestClass] /// public class System_IO_DirectoryInfo_GetFileSystemEntriesWhere /// { /// [TestMethod] /// public void GetFileSystemEntriesWhere() /// { /// // Type /// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, &quot;System_IO_DirectoryInfo_GetFileSystemEntriesWhere&quot;)); /// Directory.CreateDirectory(root.FullName); /// root.CreateSubdirectory(&quot;DirFizz123&quot;); /// root.CreateSubdirectory(&quot;DirBuzz123&quot;); /// var file1 = new FileInfo(Path.Combine(root.FullName, &quot;test1.txt&quot;)); /// file1.Create(); /// /// // Exemples /// string[] result = root.GetFileSystemEntriesWhere(x =&gt; x.Contains(&quot;DirFizz&quot;) || x.EndsWith(&quot;.txt&quot;)); /// /// // Unit Test /// Assert.AreEqual(2, result.Length); /// } /// } /// } /// </code> /// </example> /// ### /// <exception cref="T:System.ArgumentException"> /// <paramref name="this " />is a zero-length string, contains only /// white space, or contains invalid characters as defined by /// <see /// cref="M:System.IO.Path.GetInvalidPathChars" /> /// .- or -<paramref name="searchPattern" /> does not contain a valid pattern. /// </exception> /// ### /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="this" /> is null.-or- /// <paramref name="searchPattern" /> is null. /// </exception> /// ### /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="searchOption" /> is not a valid /// <see cref="T:System.IO.SearchOption" /> value. /// </exception> /// ### /// <exception cref="T:System.IO.DirectoryNotFoundException"> /// <paramref name="this" /> is invalid, such as /// referring to an unmapped drive. /// </exception> /// ### /// <exception cref="T:System.IO.IOException"> /// <paramref name="this" /> is a file name. /// </exception> /// ### /// <exception cref="T:System.IO.PathTooLongException"> /// The specified @this, file name, or combined exceed the /// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters /// and file names must be less than 260 characters. /// </exception> /// ### /// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception> /// ### /// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception> public static string[] GetFileSystemEntriesWhere(this DirectoryInfo @this, String[] searchPatterns, SearchOption searchOption, Func<string, bool> predicate) { return searchPatterns.SelectMany(x => Directory.EnumerateFileSystemEntries(@this.FullName, x, searchOption)).Distinct().Where(x => predicate(x)).ToArray(); } }
// <copyright file="GPGSAndroidSetupUI.cs" company="Google Inc."> // Copyright (C) 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. // </copyright> namespace GooglePlayGames.Editor { using System; using System.Collections; using System.IO; using System.Xml; using UnityEditor; using UnityEngine; /// <summary> /// Google Play Game Services Setup dialog for Android. /// </summary> public class GPGSAndroidSetupUI : EditorWindow { /// <summary> /// The configuration data from the play games console "resource data" /// </summary> private string mConfigData = string.Empty; /// <summary> /// The name of the class to generate containing the resource constants. /// </summary> private string mClassName = "GPGSIds"; /// <summary> /// The scroll position /// </summary> private Vector2 scroll; /// <summary> /// The directory for the constants class. /// </summary> private string mConstantDirectory = "Assets"; /// <summary> /// The web client identifier. /// </summary> private string mWebClientId = string.Empty; /// <summary> /// Menus the item for GPGS android setup. /// </summary> [MenuItem("Window/Google Play Games/Setup/Android setup...", false, 1)] public static void MenuItemFileGPGSAndroidSetup() { EditorWindow window = EditorWindow.GetWindow( typeof(GPGSAndroidSetupUI), true, GPGSStrings.AndroidSetup.Title); window.minSize = new Vector2(500, 400); } [MenuItem("Window/Google Play Games/Setup/Android setup...", true)] public static bool EnableAndroidMenuItem() { #if UNITY_ANDROID return true; #else return false; #endif } /// <summary> /// Performs setup using the Android resources downloaded XML file /// from the play console. /// </summary> /// <returns><c>true</c>, if setup was performed, <c>false</c> otherwise.</returns> /// <param name="clientId">The web client id.</param> /// <param name="classDirectory">the directory to write the constants file to.</param> /// <param name="className">Fully qualified class name for the resource Ids.</param> /// <param name="resourceXmlData">Resource xml data.</param> /// <param name="nearbySvcId">Nearby svc identifier.</param> /// <param name="requiresGooglePlus">Indicates this app requires G+</param> public static bool PerformSetup( string clientId, string classDirectory, string className, string resourceXmlData, string nearbySvcId) { if (string.IsNullOrEmpty(resourceXmlData) && !string.IsNullOrEmpty(nearbySvcId)) { return PerformSetup( clientId, GPGSProjectSettings.Instance.Get(GPGSUtil.APPIDKEY), nearbySvcId); } if (ParseResources(classDirectory, className, resourceXmlData)) { GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSDIRECTORYKEY, classDirectory); GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSNAMEKEY, className); GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDRESOURCEKEY, resourceXmlData); // check the bundle id and set it if needed. CheckBundleId(); Google.VersionHandler.VerboseLoggingEnabled = true; Google.VersionHandler.UpdateVersionedAssets(forceUpdate: true); Google.VersionHandler.Enabled = true; AssetDatabase.Refresh(); Google.VersionHandler.InvokeStaticMethod( Google.VersionHandler.FindClass( "Google.JarResolver", "GooglePlayServices.PlayServicesResolver"), "MenuResolve", null); return PerformSetup( clientId, GPGSProjectSettings.Instance.Get(GPGSUtil.APPIDKEY), nearbySvcId); } return false; } /// <summary> /// Provide static access to setup for facilitating automated builds. /// </summary> /// <param name="webClientId">The oauth2 client id for the game. This is only /// needed if the ID Token or access token are needed.</param> /// <param name="appId">App identifier.</param> /// <param name="nearbySvcId">Optional nearby connection serviceId</param> /// <param name="requiresGooglePlus">Indicates that GooglePlus should be enabled</param> /// <returns>true if successful</returns> public static bool PerformSetup(string webClientId, string appId, string nearbySvcId) { if (!string.IsNullOrEmpty(webClientId)) { if (!GPGSUtil.LooksLikeValidClientId(webClientId)) { GPGSUtil.Alert(GPGSStrings.Setup.ClientIdError); return false; } string serverAppId = webClientId.Split('-')[0]; if (!serverAppId.Equals(appId)) { GPGSUtil.Alert(GPGSStrings.Setup.AppIdMismatch); return false; } } // check for valid app id if (!GPGSUtil.LooksLikeValidAppId(appId) && string.IsNullOrEmpty(nearbySvcId)) { GPGSUtil.Alert(GPGSStrings.Setup.AppIdError); return false; } if (nearbySvcId != null) { #if UNITY_ANDROID if (!NearbyConnectionUI.PerformSetup(nearbySvcId, true)) { return false; } #endif } GPGSProjectSettings.Instance.Set(GPGSUtil.APPIDKEY, appId); GPGSProjectSettings.Instance.Set(GPGSUtil.WEBCLIENTIDKEY, webClientId); GPGSProjectSettings.Instance.Save(); GPGSUtil.UpdateGameInfo(); // check that Android SDK is there if (!GPGSUtil.HasAndroidSdk()) { Debug.LogError("Android SDK not found."); EditorUtility.DisplayDialog( GPGSStrings.AndroidSetup.SdkNotFound, GPGSStrings.AndroidSetup.SdkNotFoundBlurb, GPGSStrings.Ok); return false; } // Generate AndroidManifest.xml GPGSUtil.GenerateAndroidManifest(); // refresh assets, and we're done AssetDatabase.Refresh(); GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDSETUPDONEKEY, true); GPGSProjectSettings.Instance.Save(); return true; } /// <summary> /// Called when this object is enabled by Unity editor. /// </summary> public void OnEnable() { GPGSProjectSettings settings = GPGSProjectSettings.Instance; mConstantDirectory = settings.Get(GPGSUtil.CLASSDIRECTORYKEY, mConstantDirectory); mClassName = settings.Get(GPGSUtil.CLASSNAMEKEY, mClassName); mConfigData = settings.Get(GPGSUtil.ANDROIDRESOURCEKEY); mWebClientId = settings.Get(GPGSUtil.WEBCLIENTIDKEY); } /// <summary> /// Called when the GUI should be rendered. /// </summary> public void OnGUI() { GUI.skin.label.wordWrap = true; GUILayout.BeginVertical(); GUIStyle link = new GUIStyle(GUI.skin.label); link.normal.textColor = new Color(0f, 0f, 1f); GUILayout.Space(10); GUILayout.Label(GPGSStrings.AndroidSetup.Blurb); if (GUILayout.Button("Open Play Games Console", link, GUILayout.ExpandWidth(false))) { Application.OpenURL("https://play.google.com/apps/publish"); } Rect last = GUILayoutUtility.GetLastRect(); last.y += last.height - 2; last.x += 3; last.width -= 6; last.height = 2; GUI.Box(last, string.Empty); GUILayout.Space(15); GUILayout.Label("Constants class name", EditorStyles.boldLabel); GUILayout.Label("Enter the fully qualified name of the class to create containing the constants"); GUILayout.Space(10); mConstantDirectory = EditorGUILayout.TextField( "Directory to save constants", mConstantDirectory, GUILayout.Width(480)); mClassName = EditorGUILayout.TextField( "Constants class name", mClassName, GUILayout.Width(480)); GUILayout.Label("Resources Definition", EditorStyles.boldLabel); GUILayout.Label("Paste in the Android Resources from the Play Console"); GUILayout.Space(10); scroll = GUILayout.BeginScrollView(scroll); mConfigData = EditorGUILayout.TextArea( mConfigData, GUILayout.Width(475), GUILayout.Height(Screen.height)); GUILayout.EndScrollView(); GUILayout.Space(10); // Client ID field GUILayout.Label(GPGSStrings.Setup.WebClientIdTitle, EditorStyles.boldLabel); GUILayout.Label(GPGSStrings.AndroidSetup.WebClientIdBlurb); mWebClientId = EditorGUILayout.TextField( GPGSStrings.Setup.ClientId, mWebClientId, GUILayout.Width(450)); GUILayout.Space(10); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(GPGSStrings.Setup.SetupButton, GUILayout.Width(100))) { // check that the classname entered is valid try { if (GPGSUtil.LooksLikeValidPackageName(mClassName)) { DoSetup(); return; } } catch (Exception e) { GPGSUtil.Alert( GPGSStrings.Error, "Invalid classname: " + e.Message); } } if (GUILayout.Button("Cancel", GUILayout.Width(100))) { Close(); } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(20); GUILayout.EndVertical(); } /// <summary> /// Starts the setup process. /// </summary> public void DoSetup() { if (PerformSetup(mWebClientId, mConstantDirectory, mClassName, mConfigData, null)) { CheckBundleId(); EditorUtility.DisplayDialog( GPGSStrings.Success, GPGSStrings.AndroidSetup.SetupComplete, GPGSStrings.Ok); GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDSETUPDONEKEY, true); Close(); } else { GPGSUtil.Alert( GPGSStrings.Error, "Invalid or missing XML resource data. Make sure the data is" + " valid and contains the app_id element"); } } /// <summary> /// Checks the bundle identifier. /// </summary> /// <remarks> /// Check the package id. If one is set the gpgs properties, /// and the player settings are the default or empty, set it. /// if the player settings is not the default, then prompt before /// overwriting. /// </remarks> public static void CheckBundleId() { string packageName = GPGSProjectSettings.Instance.Get( GPGSUtil.ANDROIDBUNDLEIDKEY, string.Empty); string currentId; #if UNITY_5_6_OR_NEWER currentId = PlayerSettings.GetApplicationIdentifier( BuildTargetGroup.Android); #else currentId = PlayerSettings.bundleIdentifier; #endif if (!string.IsNullOrEmpty(packageName)) { if (string.IsNullOrEmpty(currentId) || currentId == "com.Company.ProductName") { #if UNITY_5_6_OR_NEWER PlayerSettings.SetApplicationIdentifier( BuildTargetGroup.Android, packageName); #else PlayerSettings.bundleIdentifier = packageName; #endif } else if (currentId != packageName) { if (EditorUtility.DisplayDialog( "Set Bundle Identifier?", "The server configuration is using " + packageName + ", but the player settings is set to " + currentId + ".\nSet the Bundle Identifier to " + packageName + "?", "OK", "Cancel")) { #if UNITY_5_6_OR_NEWER PlayerSettings.SetApplicationIdentifier( BuildTargetGroup.Android, packageName); #else PlayerSettings.bundleIdentifier = packageName; #endif } } } else { Debug.Log("NULL package!!"); } } /// <summary> /// Parses the resources xml and set the properties. Also generates the /// constants file. /// </summary> /// <returns><c>true</c>, if resources was parsed, <c>false</c> otherwise.</returns> /// <param name="classDirectory">Class directory.</param> /// <param name="className">Class name.</param> /// <param name="res">Res. the data to parse.</param> private static bool ParseResources(string classDirectory, string className, string res) { XmlTextReader reader = new XmlTextReader(new StringReader(res)); bool inResource = false; string lastProp = null; Hashtable resourceKeys = new Hashtable(); string appId = null; while (reader.Read()) { if (reader.Name == "resources") { inResource = true; } if (inResource && reader.Name == "string") { lastProp = reader.GetAttribute("name"); } else if (inResource && !string.IsNullOrEmpty(lastProp)) { if (reader.HasValue) { if (lastProp == "app_id") { appId = reader.Value; GPGSProjectSettings.Instance.Set(GPGSUtil.APPIDKEY, appId); } else if (lastProp == "package_name") { GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDBUNDLEIDKEY, reader.Value); } else { resourceKeys[lastProp] = reader.Value; } lastProp = null; } } } reader.Close(); if (resourceKeys.Count > 0) { GPGSUtil.WriteResourceIds(classDirectory, className, resourceKeys); } return appId != null; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 7/13/2009 12:39:34 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** using System; using System.Globalization; namespace DotSpatial.Projections { /// <summary> /// Meridian /// </summary> public class Meridian : ProjDescriptor, IEsriString { #region Private Variables private int _code; private double _longitude; private string _name; #endregion Private Variables #region Constructors /// <summary> /// Creates a new instance of Meridian /// </summary> public Meridian() : this(Proj4Meridian.Greenwich) // by default. { } /// <summary> /// Generates a custom meridian given a name and a longitude /// </summary> /// <param name="longitude">The longitude to use</param> /// <param name="name">The string name for this meridian</param> public Meridian(double longitude, string name) { _longitude = longitude; _name = name; } /// <summary> /// Creates a new meridian from one of the known, proj4 meridian locations. /// Presumably the longitudes here correspond to various standard meridians /// rather than some arbitrary longitudes of capital cities. /// </summary> /// <param name="standardMeridian">One of the enumerations listed</param> public Meridian(Proj4Meridian standardMeridian) { AssignMeridian(standardMeridian); } /// <summary> /// Creates a new meridian from one of the known, proj4 meridian locations. /// </summary> /// <param name="standardMeridianName">The string name of the meridian to use</param> public Meridian(string standardMeridianName) { Proj4Meridian meridian; if (Enum.TryParse(standardMeridianName, true, out meridian)) { AssignMeridian(meridian); } } /// <summary> /// Gets or sets the code. Setting this will not impact the longitude or name. /// In order to read a standard code (8901-8913) use the ReadCode method. /// </summary> public int Code { get { return _code; } set { _code = value; } } /// <summary> /// Reads the integer code (possibly only an internal GDAL code) for the Meridian. /// The value can be from 8901 (Greenwich) to 8913 (Oslo). This will also alter /// the name and longitude for this meridian. /// </summary> /// <param name="code">The integer meridian code.</param> public void ReadCode(int code) { switch (code) { case 8901: AssignMeridian(Proj4Meridian.Greenwich); break; case 8902: AssignMeridian(Proj4Meridian.Lisbon); break; case 8903: AssignMeridian(Proj4Meridian.Paris); break; case 8904: AssignMeridian(Proj4Meridian.Bogota); break; case 8905: AssignMeridian(Proj4Meridian.Madrid); break; case 8906: AssignMeridian(Proj4Meridian.Rome); break; case 8907: AssignMeridian(Proj4Meridian.Bern); break; case 8908: AssignMeridian(Proj4Meridian.Jakarta); break; case 8909: AssignMeridian(Proj4Meridian.Ferro); break; case 8910: AssignMeridian(Proj4Meridian.Brussels); break; case 8911: AssignMeridian(Proj4Meridian.Stockholm); break; case 8912: AssignMeridian(Proj4Meridian.Athens); break; case 8913: AssignMeridian(Proj4Meridian.Oslo); break; } } /// <summary> /// Changes the longitude to correspond with the specified standard meridian /// </summary> /// <param name="standardMeridian"></param> public void AssignMeridian(Proj4Meridian standardMeridian) { _name = standardMeridian.ToString(); switch (standardMeridian) { case Proj4Meridian.Greenwich: _longitude = 0; _code = 8901; break; case Proj4Meridian.Lisbon: _longitude = -9.131906111; _code = 8902; break; case Proj4Meridian.Paris: _longitude = 2.337229167; _code = 8903; break; case Proj4Meridian.Bogota: _longitude = -74.08091667; _code = 8904; break; case Proj4Meridian.Madrid: _longitude = -3.687938889; _code = 8905; break; case Proj4Meridian.Rome: _longitude = 12.45233333; _code = 8906; break; case Proj4Meridian.Bern: _longitude = 7.439583333; _code = 8907; break; case Proj4Meridian.Jakarta: _longitude = 106.8077194; _code = 8908; break; case Proj4Meridian.Ferro: _longitude = -17.66666667; _code = 8909; break; case Proj4Meridian.Brussels: _longitude = 4.367975; _code = 8910; break; case Proj4Meridian.Stockholm: _longitude = 18.05827778; _code = 8911; break; case Proj4Meridian.Athens: _longitude = 23.7163375; _code = 8912; break; case Proj4Meridian.Oslo: _longitude = 10.72291667; _code = 8913; break; } } private void FindNameByValue(double pmv) { const double precison = .0000001; if (Math.Abs(pmv) < precison) { AssignMeridian(Proj4Meridian.Greenwich); } else if (Math.Abs(pmv - -9.131906111) < precison) { AssignMeridian(Proj4Meridian.Lisbon); } else if (Math.Abs(pmv - 2.337229167) < precison) { AssignMeridian(Proj4Meridian.Paris); } else if (Math.Abs(pmv - -74.08091667) < precison) { AssignMeridian(Proj4Meridian.Bogota); } else if (Math.Abs(pmv - -3.687938889) < precison) { AssignMeridian(Proj4Meridian.Madrid); } else if (Math.Abs(pmv - 12.45233333) < precison) { AssignMeridian(Proj4Meridian.Rome); } else if (Math.Abs(pmv - 7.439583333) < precison) { AssignMeridian(Proj4Meridian.Bern); } else if (Math.Abs(pmv - 106.8077194) < precison) { AssignMeridian(Proj4Meridian.Jakarta); } else if (Math.Abs(pmv - -17.66666667) < precison) { AssignMeridian(Proj4Meridian.Ferro); } else if (Math.Abs(pmv - 4.367975) < precison) { AssignMeridian(Proj4Meridian.Brussels); } else if (Math.Abs(pmv - 18.05827778) < precison) { AssignMeridian(Proj4Meridian.Stockholm); } else if (Math.Abs(pmv - 23.7163375) < precison) { AssignMeridian(Proj4Meridian.Athens); } else if (Math.Abs(pmv - 10.72291667) < precison) { AssignMeridian(Proj4Meridian.Oslo); } else { _name = "Custom"; _code = 0; } } #endregion Constructors #region Properties /// <summary> /// Gets or sets the string name /// </summary> public string Name { get { return _name; } set { _name = value; } } /// <summary> /// Gets or sets the longitude where the prime meridian for this geographic coordinate occurs. /// </summary> public double Longitude { get { return _longitude; } set { _longitude = value; } } /// <summary> /// Gets or sets the pm. /// </summary> /// <value> /// Alternate prime meridian (typically a city name). /// </value> public string pm { get { if (_longitude != 0) return _longitude.ToString(CultureInfo.InvariantCulture); return null; } set { // maybe we have a numeric value double lon; if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out lon)) { _longitude = lon; // Try to find a standard name that has a close longitude. FindNameByValue(lon); } // otherwise try parse as city name else { Proj4Meridian meridian; if (Enum.TryParse(value, true, out meridian)) { AssignMeridian(meridian); } } } } #endregion Properties #region IEsriString Members /// <summary> /// Writes the longitude and prime meridian content to the esri string /// </summary> /// <returns>A string that is formatted for an esri prj file</returns> public string ToEsriString() { return @"PRIMEM[""" + _name + @"""," + Convert.ToString(_longitude, CultureInfo.InvariantCulture) + "]"; } /// <summary> /// Reads content from an esri string, learning information about the prime meridian /// </summary> /// <param name="esriString"></param> public void ParseEsriString(string esriString) { if (String.IsNullOrEmpty(esriString)) return; if (esriString.Contains("PRIMEM") == false) return; int iStart = esriString.IndexOf("PRIMEM", StringComparison.Ordinal) + 7; int iEnd = esriString.IndexOf("]", iStart, StringComparison.Ordinal); if (iEnd < iStart) return; string extracted = esriString.Substring(iStart, iEnd - iStart); string[] terms = extracted.Split(','); _name = terms[0]; _name = _name.Substring(1, _name.Length - 2); _longitude = double.Parse(terms[1], CultureInfo.InvariantCulture); } #endregion /// <summary> /// Returns a representaion of this object as a Proj4 string. /// </summary> /// <returns></returns> public string ToProj4String() { if (String.IsNullOrWhiteSpace(pm)) return null; return String.Format(" +pm={0}", pm); } } }
// 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 Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.Intellisense; using Moq; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class ISymbolExtensionsTests : TestBase { [Fact] public void GetGlyphGroupTests() { TestGlyph( StandardGlyphGroup.GlyphAssembly, SymbolKind.Assembly); TestGlyph( StandardGlyphGroup.GlyphAssembly, SymbolKind.NetModule); TestGlyph( StandardGlyphGroup.GlyphGroupNamespace, SymbolKind.Namespace); TestGlyph( StandardGlyphGroup.GlyphGroupType, SymbolKind.TypeParameter); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.DynamicType); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodPrivate, SymbolKind.Method, Accessibility.Private); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodPrivate, SymbolKind.Method, Accessibility.Private, isExtensionMethod: false, methodKind: MethodKind.ReducedExtension); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodProtected, declaredAccessibility: Accessibility.ProtectedAndInternal); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodProtected, declaredAccessibility: Accessibility.Protected); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodProtected, declaredAccessibility: Accessibility.ProtectedOrInternal); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodInternal, declaredAccessibility: Accessibility.Internal); TestGlyph( StandardGlyphGroup.GlyphExtensionMethod, declaredAccessibility: Accessibility.Public); TestGlyph( StandardGlyphGroup.GlyphGroupMethod, declaredAccessibility: Accessibility.Public, isExtensionMethod: false); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.PointerType, pointedAtType: (INamedTypeSymbol)CreateSymbolMock(SymbolKind.NamedType, typeKind: TypeKind.Class)); TestGlyph( StandardGlyphGroup.GlyphGroupProperty, SymbolKind.Property); TestGlyph( StandardGlyphGroup.GlyphGroupEnumMember, SymbolKind.Field, containingType: (INamedTypeSymbol)CreateSymbolMock(SymbolKind.NamedType, typeKind: TypeKind.Enum)); TestGlyph( StandardGlyphGroup.GlyphGroupConstant, SymbolKind.Field, isConst: true); TestGlyph( StandardGlyphGroup.GlyphGroupField, SymbolKind.Field); TestGlyph(StandardGlyphGroup.GlyphGroupVariable, SymbolKind.Parameter); TestGlyph(StandardGlyphGroup.GlyphGroupVariable, SymbolKind.Local); TestGlyph(StandardGlyphGroup.GlyphGroupVariable, SymbolKind.RangeVariable); TestGlyph(StandardGlyphGroup.GlyphGroupIntrinsic, SymbolKind.Label); TestGlyph(StandardGlyphGroup.GlyphGroupEvent, SymbolKind.Event); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.ArrayType, elementType: (INamedTypeSymbol)CreateSymbolMock(SymbolKind.NamedType, typeKind: TypeKind.Class)); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.Alias, target: (INamedTypeSymbol)CreateSymbolMock(SymbolKind.NamedType, typeKind: TypeKind.Class)); Assert.ThrowsAny<ArgumentException>(() => TestGlyph( StandardGlyphGroup.GlyphGroupClass, (SymbolKind)1000)); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.NamedType, typeKind: TypeKind.Class); TestGlyph( StandardGlyphGroup.GlyphGroupDelegate, SymbolKind.NamedType, typeKind: TypeKind.Delegate); TestGlyph( StandardGlyphGroup.GlyphGroupEnum, SymbolKind.NamedType, typeKind: TypeKind.Enum); TestGlyph( StandardGlyphGroup.GlyphGroupModule, SymbolKind.NamedType, typeKind: TypeKind.Module); TestGlyph( StandardGlyphGroup.GlyphGroupInterface, SymbolKind.NamedType, typeKind: TypeKind.Interface); TestGlyph( StandardGlyphGroup.GlyphGroupStruct, SymbolKind.NamedType, typeKind: TypeKind.Struct); TestGlyph( StandardGlyphGroup.GlyphGroupError, SymbolKind.NamedType, typeKind: TypeKind.Error); Assert.ThrowsAny<Exception>(() => TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.NamedType, typeKind: TypeKind.Unknown)); } [Fact, WorkItem(545015)] public void TestRegularOperatorGlyph() { TestGlyph( StandardGlyphGroup.GlyphGroupOperator, SymbolKind.Method, methodKind: MethodKind.UserDefinedOperator); } [Fact, WorkItem(545015)] public void TestConversionOperatorGlyph() { TestGlyph( StandardGlyphGroup.GlyphGroupOperator, SymbolKind.Method, methodKind: MethodKind.Conversion); } [Fact] public void TestWithEventsMemberGlyph() { TestGlyph( StandardGlyphGroup.GlyphGroupField, SymbolKind.Property, isWithEvents: true); } private void TestGlyph( StandardGlyphGroup expectedGlyphGroup, SymbolKind kind = SymbolKind.Method, Accessibility declaredAccessibility = Accessibility.NotApplicable, bool isExtensionMethod = true, MethodKind methodKind = MethodKind.Ordinary, INamedTypeSymbol containingType = null, bool isConst = false, ITypeSymbol elementType = null, INamespaceOrTypeSymbol target = null, ITypeSymbol pointedAtType = null, bool isWithEvents = false, TypeKind typeKind = TypeKind.Unknown) { var symbol = CreateSymbolMock(kind, declaredAccessibility, isExtensionMethod, methodKind, containingType, isConst, elementType, target, pointedAtType, isWithEvents, typeKind); Assert.Equal(expectedGlyphGroup, symbol.GetGlyph().GetStandardGlyphGroup()); } private static ISymbol CreateSymbolMock( SymbolKind kind, Accessibility declaredAccessibility = Accessibility.NotApplicable, bool isExtensionMethod = false, MethodKind methodKind = MethodKind.Ordinary, INamedTypeSymbol containingType = null, bool isConst = false, ITypeSymbol elementType = null, INamespaceOrTypeSymbol target = null, ITypeSymbol pointedAtType = null, bool isWithEvents = false, TypeKind typeKind = TypeKind.Unknown) { var symbolMock = new Mock<ISymbol>(); symbolMock.SetupGet(s => s.Kind).Returns(kind); symbolMock.SetupGet(s => s.DeclaredAccessibility).Returns(declaredAccessibility); symbolMock.SetupGet(s => s.ContainingType).Returns(containingType); if (kind == SymbolKind.ArrayType) { var arrayTypeMock = symbolMock.As<IArrayTypeSymbol>(); arrayTypeMock.SetupGet(s => s.ElementType).Returns(elementType); } if (kind == SymbolKind.Alias) { var aliasMock = symbolMock.As<IAliasSymbol>(); aliasMock.SetupGet(s => s.Target).Returns(target); } if (kind == SymbolKind.Method) { var methodTypeMock = symbolMock.As<IMethodSymbol>(); methodTypeMock.SetupGet(s => s.MethodKind).Returns(methodKind); methodTypeMock.SetupGet(s => s.IsExtensionMethod).Returns(isExtensionMethod); } if (kind == SymbolKind.NamedType) { var namedTypeMock = symbolMock.As<INamedTypeSymbol>(); namedTypeMock.SetupGet(s => s.TypeKind).Returns(typeKind); } if (kind == SymbolKind.Field) { var fieldMock = symbolMock.As<IFieldSymbol>(); fieldMock.SetupGet(s => s.IsConst).Returns(isConst); } if (kind == SymbolKind.PointerType) { var pointerTypeMock = symbolMock.As<IPointerTypeSymbol>(); pointerTypeMock.SetupGet(s => s.PointedAtType).Returns(pointedAtType); } if (kind == SymbolKind.Property) { var propertyMock = symbolMock.As<IPropertySymbol>(); propertyMock.SetupGet(s => s.IsWithEvents).Returns(isWithEvents); } return symbolMock.Object; } } }
using Signum.Utilities; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Signum.Engine.Connection { public static class SqlServerRetry { public static int MaxRetryCount = 6; /// must not be lesser than 1. public static double DefaultRandomFactor = 1.1; /// must be positive. public static double DefaultExponentialBase = 2; public static readonly TimeSpan MaxDelay = TimeSpan.FromSeconds(30); public static readonly TimeSpan BaseDelay = TimeSpan.FromSeconds(1); static TimeSpan? GetNextDelay(int currentRetryCount) { if (MaxRetryCount <= currentRetryCount) return null; var delta = (Math.Pow(DefaultExponentialBase, currentRetryCount) - 1.0) * (1.0 + MyRandom.Current.NextDouble() * (DefaultRandomFactor - 1.0)); var delay = Math.Min( BaseDelay.TotalMilliseconds * delta, MaxDelay.TotalMilliseconds); return TimeSpan.FromMilliseconds(delay); } static readonly AsyncLocal<bool?> _suspended = new AsyncLocal<bool?>(); public static bool Suspended = _suspended.Value ?? false; public static IDisposable Suspend() { var val = _suspended.Value; _suspended.Value = true; return new Disposable(() => _suspended.Value = true); } public static Func<bool> IsEnabled = () => Connector.Current?.RequiresRetry ?? true; //https://docs.microsoft.com/en-us/azure/sql-database/sql-database-connectivity-issues public static T Retry<T>(Func<T> action) { if (Suspended || !IsEnabled()) return action(); int retry = 0; while (true) { try { using(Suspend()) { return action(); } } catch(Exception e) { if (!ShouldRetryOn(e)) throw; var delay = GetNextDelay(retry); if(delay == null) { e.Data["retryCount"] = retry; throw; } retry++; Thread.Sleep(delay.Value); } } } public static async Task<T> RetryAsync<T>(Func<Task<T>> action) { if (Suspended || !IsEnabled()) return await action(); int retry = 0; while (true) { try { using (Suspend()) { return await action(); } } catch (Exception e) { if (!ShouldRetryOn(e)) throw; var delay = GetNextDelay(retry); if (delay == null) { e.Data["retryCount"] = retry; throw; } retry++; await Task.Delay(delay.Value); } } } public static bool ShouldRetryOn(Exception ex) { if (ex is SqlException sqlException) { foreach (SqlError? err in sqlException.Errors) { switch (err!.Number) { // SQL Error Code: 49920 // Cannot process request. Too many operations in progress for subscription "%ld". // The service is busy processing multiple requests for this subscription. // Requests are currently blocked for resource optimization. Query sys.dm_operation_status for operation status. // Wait until pending requests are complete or delete one of your pending requests and retry your request later. case 49920: // SQL Error Code: 49919 // Cannot process create or update request. Too many create or update operations in progress for subscription "%ld". // The service is busy processing multiple create or update requests for your subscription or server. // Requests are currently blocked for resource optimization. Query sys.dm_operation_status for pending operations. // Wait till pending create or update requests are complete or delete one of your pending requests and // retry your request later. case 49919: // SQL Error Code: 49918 // Cannot process request. Not enough resources to process request. // The service is currently busy.Please retry the request later. case 49918: // SQL Error Code: 41839 // Transaction exceeded the maximum number of commit dependencies. case 41839: // SQL Error Code: 41325 // The current transaction failed to commit due to a serializable validation failure. case 41325: // SQL Error Code: 41305 // The current transaction failed to commit due to a repeatable read validation failure. case 41305: // SQL Error Code: 41302 // The current transaction attempted to update a record that has been updated since the transaction started. case 41302: // SQL Error Code: 41301 // Dependency failure: a dependency was taken on another transaction that later failed to commit. case 41301: // SQL Error Code: 40613 // Database XXXX on server YYYY is not currently available. Please retry the connection later. // If the problem persists, contact customer support, and provide them the session tracing ID of ZZZZZ. case 40613: // SQL Error Code: 40501 // The service is currently busy. Retry the request after 10 seconds. Code: (reason code to be decoded). case 40501: // SQL Error Code: 40197 // The service has encountered an error processing your request. Please try again. case 40197: // SQL Error Code: 10929 // Resource ID: %d. The %s minimum guarantee is %d, maximum limit is %d and the current usage for the database is %d. // However, the server is currently too busy to support requests greater than %d for this database. // For more information, see http://go.microsoft.com/fwlink/?LinkId=267637. Otherwise, please try again. case 10929: // SQL Error Code: 10928 // Resource ID: %d. The %s limit for the database is %d and has been reached. For more information, // see http://go.microsoft.com/fwlink/?LinkId=267637. case 10928: // SQL Error Code: 10060 // A network-related or instance-specific error occurred while establishing a connection to SQL Server. // The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server // is configured to allow remote connections. (provider: TCP Provider, error: 0 - A connection attempt failed // because the connected party did not properly respond after a period of time, or established connection failed // because connected host has failed to respond.)"} case 10060: // SQL Error Code: 10054 // A transport-level error has occurred when sending the request to the server. // (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.) case 10054: // SQL Error Code: 10053 // A transport-level error has occurred when receiving results from the server. // An established connection was aborted by the software in your host machine. case 10053: // SQL Error Code: 1205 // Deadlock case 1205: // SQL Error Code: 233 // The client was unable to establish a connection because of an error during connection initialization process before login. // Possible causes include the following: the client tried to connect to an unsupported version of SQL Server; // the server was too busy to accept new connections; or there was a resource limitation (insufficient memory or maximum // allowed connections) on the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by // the remote host.) case 233: // SQL Error Code: 121 // The semaphore timeout period has expired case 121: // SQL Error Code: 64 // A connection was successfully established with the server, but then an error occurred during the login process. // (provider: TCP Provider, error: 0 - The specified network name is no longer available.) case 64: // DBNETLIB Error Code: 20 // The instance of SQL Server you attempted to connect to does not support encryption. case 20: return true; // This exception can be thrown even if the operation completed successfully, so it's safer to let the application fail. // DBNETLIB Error Code: -2 // Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated. //case -2: } } return false; } return ex is TimeoutException; } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // SortQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// The query operator for OrderBy and ThenBy. /// </summary> /// <typeparam name="TInputOutput"></typeparam> /// <typeparam name="TSortKey"></typeparam> internal sealed class SortQueryOperator<TInputOutput, TSortKey> : UnaryQueryOperator<TInputOutput, TInputOutput>, IOrderedEnumerable<TInputOutput> { private readonly Func<TInputOutput, TSortKey> _keySelector; // Key selector used when sorting. private readonly IComparer<TSortKey> _comparer; // Key comparison logic to use during sorting. //--------------------------------------------------------------------------------------- // Instantiates a new sort operator. // internal SortQueryOperator(IEnumerable<TInputOutput> source, Func<TInputOutput, TSortKey> keySelector, IComparer<TSortKey> comparer, bool descending) : base(source, true) { Debug.Assert(keySelector != null, "key selector must not be null"); _keySelector = keySelector; // If a comparer wasn't supplied, we use the default one for the key type. if (comparer == null) { _comparer = Util.GetDefaultComparer<TSortKey>(); } else { _comparer = comparer; } if (descending) { _comparer = new ReverseComparer<TSortKey>(_comparer); } SetOrdinalIndexState(OrdinalIndexState.Shuffled); } //--------------------------------------------------------------------------------------- // IOrderedEnumerable method for nesting an order by operator inside another. // IOrderedEnumerable<TInputOutput> IOrderedEnumerable<TInputOutput>.CreateOrderedEnumerable<TKey2>( Func<TInputOutput, TKey2> key2Selector, IComparer<TKey2> key2Comparer, bool descending) { key2Comparer = key2Comparer ?? Util.GetDefaultComparer<TKey2>(); if (descending) { key2Comparer = new ReverseComparer<TKey2>(key2Comparer); } IComparer<Pair<TSortKey, TKey2>> pairComparer = new PairComparer<TSortKey, TKey2>(_comparer, key2Comparer); Func<TInputOutput, Pair<TSortKey, TKey2>> pairKeySelector = (TInputOutput elem) => new Pair<TSortKey, TKey2>(_keySelector(elem), key2Selector(elem)); return new SortQueryOperator<TInputOutput, Pair<TSortKey, TKey2>>(Child, pairKeySelector, pairComparer, false); } //--------------------------------------------------------------------------------------- // Accessor the key selector. // internal Func<TInputOutput, TSortKey> KeySelector { get { return _keySelector; } } //--------------------------------------------------------------------------------------- // Accessor the key comparer. // internal IComparer<TSortKey> KeyComparer { get { return _comparer; } } //--------------------------------------------------------------------------------------- // Opens the current operator. This involves opening the child operator tree, enumerating // the results, sorting them, and then returning an enumerator that walks the result. // internal override QueryResults<TInputOutput> Open(QuerySettings settings, bool preferStriping) { QueryResults<TInputOutput> childQueryResults = Child.Open(settings, false); return new SortQueryOperatorResults<TInputOutput, TSortKey>(childQueryResults, this, settings, preferStriping); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TInputOutput, TKey> inputStream, IPartitionedStreamRecipient<TInputOutput> recipient, bool preferStriping, QuerySettings settings) { PartitionedStream<TInputOutput, TSortKey> outputStream = new PartitionedStream<TInputOutput, TSortKey>(inputStream.PartitionCount, this._comparer, OrdinalIndexState); for (int i = 0; i < outputStream.PartitionCount; i++) { outputStream[i] = new SortQueryOperatorEnumerator<TInputOutput, TKey, TSortKey>( inputStream[i], _keySelector, _comparer); } recipient.Receive<TSortKey>(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token) { IEnumerable<TInputOutput> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token); return wrappedChild.OrderBy(_keySelector, _comparer); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } } internal class SortQueryOperatorResults<TInputOutput, TSortKey> : QueryResults<TInputOutput> { protected QueryResults<TInputOutput> _childQueryResults; // Results of the child query private SortQueryOperator<TInputOutput, TSortKey> _op; // Operator that generated these results private QuerySettings _settings; // Settings collected from the query private bool _preferStriping; // If the results are indexable, should we use striping when partitioning them internal SortQueryOperatorResults( QueryResults<TInputOutput> childQueryResults, SortQueryOperator<TInputOutput, TSortKey> op, QuerySettings settings, bool preferStriping) { _childQueryResults = childQueryResults; _op = op; _settings = settings; _preferStriping = preferStriping; } internal override bool IsIndexible { get { return false; } } internal override void GivePartitionedStream(IPartitionedStreamRecipient<TInputOutput> recipient) { _childQueryResults.GivePartitionedStream(new ChildResultsRecipient(recipient, _op, _settings)); } private class ChildResultsRecipient : IPartitionedStreamRecipient<TInputOutput> { private IPartitionedStreamRecipient<TInputOutput> _outputRecipient; private SortQueryOperator<TInputOutput, TSortKey> _op; private QuerySettings _settings; internal ChildResultsRecipient(IPartitionedStreamRecipient<TInputOutput> outputRecipient, SortQueryOperator<TInputOutput, TSortKey> op, QuerySettings settings) { _outputRecipient = outputRecipient; _op = op; _settings = settings; } public void Receive<TKey>(PartitionedStream<TInputOutput, TKey> childPartitionedStream) { _op.WrapPartitionedStream(childPartitionedStream, _outputRecipient, false, _settings); } } } //--------------------------------------------------------------------------------------- // This enumerator performs sorting based on a key selection and comparison routine. // internal class SortQueryOperatorEnumerator<TInputOutput, TKey, TSortKey> : QueryOperatorEnumerator<TInputOutput, TSortKey> { private readonly QueryOperatorEnumerator<TInputOutput, TKey> _source; // Data source to sort. private readonly Func<TInputOutput, TSortKey> _keySelector; // Key selector used when sorting. private readonly IComparer<TSortKey> _keyComparer; // Key comparison logic to use during sorting. //--------------------------------------------------------------------------------------- // Instantiates a new sort operator enumerator. // internal SortQueryOperatorEnumerator(QueryOperatorEnumerator<TInputOutput, TKey> source, Func<TInputOutput, TSortKey> keySelector, IComparer<TSortKey> keyComparer) { Debug.Assert(source != null); Debug.Assert(keySelector != null, "need a key comparer"); Debug.Assert(keyComparer != null, "expected a compiled operator"); _source = source; _keySelector = keySelector; _keyComparer = keyComparer; } //--------------------------------------------------------------------------------------- // Accessor for the key comparison routine. // public IComparer<TSortKey> KeyComparer { get { return _keyComparer; } } //--------------------------------------------------------------------------------------- // Moves to the next element in the sorted output. When called for the first time, the // descendents in the sort's child tree are executed entirely, the results accumulated // in memory, and the data sorted. // internal override bool MoveNext(ref TInputOutput currentElement, ref TSortKey currentKey) { Debug.Assert(_source != null); TKey keyUnused = default(TKey); if (!_source.MoveNext(ref currentElement, ref keyUnused)) { return false; } currentKey = _keySelector(currentElement); return true; } protected override void Dispose(bool disposing) { Debug.Assert(_source != null); _source.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System.Runtime.CompilerServices; using static System.TestHelpers; namespace System.SpanTests { public static partial class SpanTests { [Fact] public static void ReverseEmpty() { var span = Span<byte>.Empty; span.Reverse(); byte[] actual = { 1, 2, 3, 4 }; byte[] expected = { 1, 2, 3, 4 }; span = actual; span.Slice(2, 0).Reverse(); Assert.Equal<byte>(expected, span.ToArray()); } [Fact] public static void ReverseEmptyWithReference() { var span = Span<string>.Empty; span.Reverse(); string[] actual = { "a", "b", "c", "d" }; string[] expected = { "a", "b", "c", "d" }; span = actual; span.Slice(2, 0).Reverse(); Assert.Equal<string>(expected, span.ToArray()); } [Fact] public static void ReverseByte() { for(int length = 0; length < byte.MaxValue; length++) { var actual = new byte[length]; for (int i = 0; i < length; i++) { actual[i] = (byte)i; } byte[] expected = new byte[length]; Array.Copy(actual, expected, length); Array.Reverse(expected); var span = new Span<byte>(actual); span.Reverse(); Assert.Equal<byte>(expected, actual); } } [Fact] public static void ReverseByteTwiceReturnsOriginal() { byte[] actual = { 1, 2, 3, 4, 5 }; byte[] expected = { 1, 2, 3, 4, 5 }; Span<byte> span = actual; span.Reverse(); span.Reverse(); Assert.Equal<byte>(expected, actual); } [Fact] public static void ReverseByteUnaligned() { const int length = 32; const int offset = 1; var actualFull = new byte[length]; for (int i = 0; i < length; i++) { actualFull[i] = (byte)i; } byte[] expectedFull = new byte[length]; Array.Copy(actualFull, expectedFull, length); Array.Reverse(expectedFull, offset, length - offset - 1); var expectedSpan = new Span<byte>(expectedFull, offset, length - offset - 1); var actualSpan = new Span<byte>(actualFull, offset, length - offset - 1); actualSpan.Reverse(); byte[] actual = actualSpan.ToArray(); byte[] expected = expectedSpan.ToArray(); Assert.Equal<byte>(expected, actual); Assert.Equal(expectedFull[0], actualFull[0]); Assert.Equal(expectedFull[length - 1], actualFull[length - 1]); } [Fact] public static void ReverseIntPtrOffset() { const int length = 32; const int offset = 2; var actualFull = new IntPtr[length]; for (int i = 0; i < length; i++) { actualFull[i] = IntPtr.Zero + i; } IntPtr[] expectedFull = new IntPtr[length]; Array.Copy(actualFull, expectedFull, length); Array.Reverse(expectedFull, offset, length - offset); var expectedSpan = new Span<IntPtr>(expectedFull, offset, length - offset); var actualSpan = new Span<IntPtr>(actualFull, offset, length - offset); actualSpan.Reverse(); IntPtr[] actual = actualSpan.ToArray(); IntPtr[] expected = expectedSpan.ToArray(); Assert.Equal<IntPtr>(expected, actual); Assert.Equal(expectedFull[0], actualFull[0]); Assert.Equal(expectedFull[1], actualFull[1]); } [Fact] public static void ReverseValueTypeWithoutReferences() { const int length = 2048; int[] actual = new int[length]; for (int i = 0; i < length; i++) { actual[i] = i; } int[] expected = new int[length]; Array.Copy(actual, expected, length); Array.Reverse(expected); var span = new Span<int>(actual); span.Reverse(); Assert.Equal<int>(expected, actual); } [Fact] public static void ReverseValueTypeWithoutReferencesPointerSize() { const int length = 15; long[] actual = new long[length]; for (int i = 0; i < length; i++) { actual[i] = i; } long[] expected = new long[length]; Array.Copy(actual, expected, length); Array.Reverse(expected); var span = new Span<long>(actual); span.Reverse(); Assert.Equal<long>(expected, actual); } [Fact] public static void ReverseReferenceType() { const int length = 2048; string[] actual = new string[length]; for (int i = 0; i < length; i++) { actual[i] = i.ToString(); } string[] expected = new string[length]; Array.Copy(actual, expected, length); Array.Reverse(expected); var span = new Span<string>(actual); span.Reverse(); Assert.Equal<string>(expected, actual); } [Fact] public static void ReverseReferenceTwiceReturnsOriginal() { string[] actual = { "a1", "b2", "c3" }; string[] expected = { "a1", "b2", "c3" }; var span = new Span<string>(actual); span.Reverse(); span.Reverse(); Assert.Equal<string>(expected, actual); } [Fact] public static void ReverseEnumType() { TestEnum[] actual = { TestEnum.e0, TestEnum.e1, TestEnum.e2 }; TestEnum[] expected = { TestEnum.e2, TestEnum.e1, TestEnum.e0 }; var span = new Span<TestEnum>(actual); span.Reverse(); Assert.Equal<TestEnum>(expected, actual); } [Fact] public static void ReverseValueTypeWithReferences() { TestValueTypeWithReference[] actual = { new TestValueTypeWithReference() { I = 1, S = "a" }, new TestValueTypeWithReference() { I = 2, S = "b" }, new TestValueTypeWithReference() { I = 3, S = "c" } }; TestValueTypeWithReference[] expected = { new TestValueTypeWithReference() { I = 3, S = "c" }, new TestValueTypeWithReference() { I = 2, S = "b" }, new TestValueTypeWithReference() { I = 1, S = "a" } }; var span = new Span<TestValueTypeWithReference>(actual); span.Reverse(); Assert.Equal<TestValueTypeWithReference>(expected, actual); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// Static class that contains static glm functions /// </summary> public static partial class glm { /// <summary> /// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy) /// </summary> public static swizzle_vec2 swizzle(vec2 v) => v.swizzle; /// <summary> /// Returns an array with all values /// </summary> public static float[] Values(vec2 v) => v.Values; /// <summary> /// Returns an enumerator that iterates through all components. /// </summary> public static IEnumerator<float> GetEnumerator(vec2 v) => v.GetEnumerator(); /// <summary> /// Returns a string representation of this vector using ', ' as a seperator. /// </summary> public static string ToString(vec2 v) => v.ToString(); /// <summary> /// Returns a string representation of this vector using a provided seperator. /// </summary> public static string ToString(vec2 v, string sep) => v.ToString(sep); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format provider for each component. /// </summary> public static string ToString(vec2 v, string sep, IFormatProvider provider) => v.ToString(sep, provider); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format for each component. /// </summary> public static string ToString(vec2 v, string sep, string format) => v.ToString(sep, format); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format and format provider for each component. /// </summary> public static string ToString(vec2 v, string sep, string format, IFormatProvider provider) => v.ToString(sep, format, provider); /// <summary> /// Returns the number of components (2). /// </summary> public static int Count(vec2 v) => v.Count; /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool Equals(vec2 v, vec2 rhs) => v.Equals(rhs); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public static bool Equals(vec2 v, object obj) => v.Equals(obj); /// <summary> /// Returns a hash code for this instance. /// </summary> public static int GetHashCode(vec2 v) => v.GetHashCode(); /// <summary> /// Returns true iff distance between lhs and rhs is less than or equal to epsilon /// </summary> public static bool ApproxEqual(vec2 lhs, vec2 rhs, float eps = 0.1f) => vec2.ApproxEqual(lhs, rhs, eps); /// <summary> /// Returns a bvec2 from component-wise application of Equal (lhs == rhs). /// </summary> public static bvec2 Equal(vec2 lhs, vec2 rhs) => vec2.Equal(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bvec2 NotEqual(vec2 lhs, vec2 rhs) => vec2.NotEqual(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of GreaterThan (lhs &gt; rhs). /// </summary> public static bvec2 GreaterThan(vec2 lhs, vec2 rhs) => vec2.GreaterThan(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of GreaterThanEqual (lhs &gt;= rhs). /// </summary> public static bvec2 GreaterThanEqual(vec2 lhs, vec2 rhs) => vec2.GreaterThanEqual(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of LesserThan (lhs &lt; rhs). /// </summary> public static bvec2 LesserThan(vec2 lhs, vec2 rhs) => vec2.LesserThan(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of LesserThanEqual (lhs &lt;= rhs). /// </summary> public static bvec2 LesserThanEqual(vec2 lhs, vec2 rhs) => vec2.LesserThanEqual(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of IsInfinity (float.IsInfinity(v)). /// </summary> public static bvec2 IsInfinity(vec2 v) => vec2.IsInfinity(v); /// <summary> /// Returns a bvec2 from component-wise application of IsFinite (!float.IsNaN(v) &amp;&amp; !float.IsInfinity(v)). /// </summary> public static bvec2 IsFinite(vec2 v) => vec2.IsFinite(v); /// <summary> /// Returns a bvec2 from component-wise application of IsNaN (float.IsNaN(v)). /// </summary> public static bvec2 IsNaN(vec2 v) => vec2.IsNaN(v); /// <summary> /// Returns a bvec2 from component-wise application of IsNegativeInfinity (float.IsNegativeInfinity(v)). /// </summary> public static bvec2 IsNegativeInfinity(vec2 v) => vec2.IsNegativeInfinity(v); /// <summary> /// Returns a bvec2 from component-wise application of IsPositiveInfinity (float.IsPositiveInfinity(v)). /// </summary> public static bvec2 IsPositiveInfinity(vec2 v) => vec2.IsPositiveInfinity(v); /// <summary> /// Returns a vec2 from component-wise application of Abs (Math.Abs(v)). /// </summary> public static vec2 Abs(vec2 v) => vec2.Abs(v); /// <summary> /// Returns a vec2 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v). /// </summary> public static vec2 HermiteInterpolationOrder3(vec2 v) => vec2.HermiteInterpolationOrder3(v); /// <summary> /// Returns a vec2 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v). /// </summary> public static vec2 HermiteInterpolationOrder5(vec2 v) => vec2.HermiteInterpolationOrder5(v); /// <summary> /// Returns a vec2 from component-wise application of Sqr (v * v). /// </summary> public static vec2 Sqr(vec2 v) => vec2.Sqr(v); /// <summary> /// Returns a vec2 from component-wise application of Pow2 (v * v). /// </summary> public static vec2 Pow2(vec2 v) => vec2.Pow2(v); /// <summary> /// Returns a vec2 from component-wise application of Pow3 (v * v * v). /// </summary> public static vec2 Pow3(vec2 v) => vec2.Pow3(v); /// <summary> /// Returns a vec2 from component-wise application of Step (v &gt;= 0f ? 1f : 0f). /// </summary> public static vec2 Step(vec2 v) => vec2.Step(v); /// <summary> /// Returns a vec2 from component-wise application of Sqrt ((float)Math.Sqrt((double)v)). /// </summary> public static vec2 Sqrt(vec2 v) => vec2.Sqrt(v); /// <summary> /// Returns a vec2 from component-wise application of InverseSqrt ((float)(1.0 / Math.Sqrt((double)v))). /// </summary> public static vec2 InverseSqrt(vec2 v) => vec2.InverseSqrt(v); /// <summary> /// Returns a ivec2 from component-wise application of Sign (Math.Sign(v)). /// </summary> public static ivec2 Sign(vec2 v) => vec2.Sign(v); /// <summary> /// Returns a vec2 from component-wise application of Max (Math.Max(lhs, rhs)). /// </summary> public static vec2 Max(vec2 lhs, vec2 rhs) => vec2.Max(lhs, rhs); /// <summary> /// Returns a vec2 from component-wise application of Min (Math.Min(lhs, rhs)). /// </summary> public static vec2 Min(vec2 lhs, vec2 rhs) => vec2.Min(lhs, rhs); /// <summary> /// Returns a vec2 from component-wise application of Pow ((float)Math.Pow((double)lhs, (double)rhs)). /// </summary> public static vec2 Pow(vec2 lhs, vec2 rhs) => vec2.Pow(lhs, rhs); /// <summary> /// Returns a vec2 from component-wise application of Log ((float)Math.Log((double)lhs, (double)rhs)). /// </summary> public static vec2 Log(vec2 lhs, vec2 rhs) => vec2.Log(lhs, rhs); /// <summary> /// Returns a vec2 from component-wise application of Clamp (Math.Min(Math.Max(v, min), max)). /// </summary> public static vec2 Clamp(vec2 v, vec2 min, vec2 max) => vec2.Clamp(v, min, max); /// <summary> /// Returns a vec2 from component-wise application of Mix (min * (1-a) + max * a). /// </summary> public static vec2 Mix(vec2 min, vec2 max, vec2 a) => vec2.Mix(min, max, a); /// <summary> /// Returns a vec2 from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static vec2 Lerp(vec2 min, vec2 max, vec2 a) => vec2.Lerp(min, max, a); /// <summary> /// Returns a vec2 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()). /// </summary> public static vec2 Smoothstep(vec2 edge0, vec2 edge1, vec2 v) => vec2.Smoothstep(edge0, edge1, v); /// <summary> /// Returns a vec2 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()). /// </summary> public static vec2 Smootherstep(vec2 edge0, vec2 edge1, vec2 v) => vec2.Smootherstep(edge0, edge1, v); /// <summary> /// Returns a vec2 from component-wise application of Fma (a * b + c). /// </summary> public static vec2 Fma(vec2 a, vec2 b, vec2 c) => vec2.Fma(a, b, c); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static mat2 OuterProduct(vec2 c, vec2 r) => vec2.OuterProduct(c, r); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static mat3x2 OuterProduct(vec2 c, vec3 r) => vec2.OuterProduct(c, r); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static mat4x2 OuterProduct(vec2 c, vec4 r) => vec2.OuterProduct(c, r); /// <summary> /// Returns a vec2 from component-wise application of Add (lhs + rhs). /// </summary> public static vec2 Add(vec2 lhs, vec2 rhs) => vec2.Add(lhs, rhs); /// <summary> /// Returns a vec2 from component-wise application of Sub (lhs - rhs). /// </summary> public static vec2 Sub(vec2 lhs, vec2 rhs) => vec2.Sub(lhs, rhs); /// <summary> /// Returns a vec2 from component-wise application of Mul (lhs * rhs). /// </summary> public static vec2 Mul(vec2 lhs, vec2 rhs) => vec2.Mul(lhs, rhs); /// <summary> /// Returns a vec2 from component-wise application of Div (lhs / rhs). /// </summary> public static vec2 Div(vec2 lhs, vec2 rhs) => vec2.Div(lhs, rhs); /// <summary> /// Returns a vec2 from component-wise application of Modulo (lhs % rhs). /// </summary> public static vec2 Modulo(vec2 lhs, vec2 rhs) => vec2.Modulo(lhs, rhs); /// <summary> /// Returns a vec2 from component-wise application of Degrees (Radians-To-Degrees Conversion). /// </summary> public static vec2 Degrees(vec2 v) => vec2.Degrees(v); /// <summary> /// Returns a vec2 from component-wise application of Radians (Degrees-To-Radians Conversion). /// </summary> public static vec2 Radians(vec2 v) => vec2.Radians(v); /// <summary> /// Returns a vec2 from component-wise application of Acos ((float)Math.Acos((double)v)). /// </summary> public static vec2 Acos(vec2 v) => vec2.Acos(v); /// <summary> /// Returns a vec2 from component-wise application of Asin ((float)Math.Asin((double)v)). /// </summary> public static vec2 Asin(vec2 v) => vec2.Asin(v); /// <summary> /// Returns a vec2 from component-wise application of Atan ((float)Math.Atan((double)v)). /// </summary> public static vec2 Atan(vec2 v) => vec2.Atan(v); /// <summary> /// Returns a vec2 from component-wise application of Cos ((float)Math.Cos((double)v)). /// </summary> public static vec2 Cos(vec2 v) => vec2.Cos(v); /// <summary> /// Returns a vec2 from component-wise application of Cosh ((float)Math.Cosh((double)v)). /// </summary> public static vec2 Cosh(vec2 v) => vec2.Cosh(v); /// <summary> /// Returns a vec2 from component-wise application of Exp ((float)Math.Exp((double)v)). /// </summary> public static vec2 Exp(vec2 v) => vec2.Exp(v); /// <summary> /// Returns a vec2 from component-wise application of Log ((float)Math.Log((double)v)). /// </summary> public static vec2 Log(vec2 v) => vec2.Log(v); /// <summary> /// Returns a vec2 from component-wise application of Log2 ((float)Math.Log((double)v, 2)). /// </summary> public static vec2 Log2(vec2 v) => vec2.Log2(v); /// <summary> /// Returns a vec2 from component-wise application of Log10 ((float)Math.Log10((double)v)). /// </summary> public static vec2 Log10(vec2 v) => vec2.Log10(v); /// <summary> /// Returns a vec2 from component-wise application of Floor ((float)Math.Floor(v)). /// </summary> public static vec2 Floor(vec2 v) => vec2.Floor(v); /// <summary> /// Returns a vec2 from component-wise application of Ceiling ((float)Math.Ceiling(v)). /// </summary> public static vec2 Ceiling(vec2 v) => vec2.Ceiling(v); /// <summary> /// Returns a vec2 from component-wise application of Round ((float)Math.Round(v)). /// </summary> public static vec2 Round(vec2 v) => vec2.Round(v); /// <summary> /// Returns a vec2 from component-wise application of Sin ((float)Math.Sin((double)v)). /// </summary> public static vec2 Sin(vec2 v) => vec2.Sin(v); /// <summary> /// Returns a vec2 from component-wise application of Sinh ((float)Math.Sinh((double)v)). /// </summary> public static vec2 Sinh(vec2 v) => vec2.Sinh(v); /// <summary> /// Returns a vec2 from component-wise application of Tan ((float)Math.Tan((double)v)). /// </summary> public static vec2 Tan(vec2 v) => vec2.Tan(v); /// <summary> /// Returns a vec2 from component-wise application of Tanh ((float)Math.Tanh((double)v)). /// </summary> public static vec2 Tanh(vec2 v) => vec2.Tanh(v); /// <summary> /// Returns a vec2 from component-wise application of Truncate ((float)Math.Truncate((double)v)). /// </summary> public static vec2 Truncate(vec2 v) => vec2.Truncate(v); /// <summary> /// Returns a vec2 from component-wise application of Fract ((float)(v - Math.Floor(v))). /// </summary> public static vec2 Fract(vec2 v) => vec2.Fract(v); /// <summary> /// Returns a vec2 from component-wise application of Trunc ((long)(v)). /// </summary> public static vec2 Trunc(vec2 v) => vec2.Trunc(v); /// <summary> /// Returns the minimal component of this vector. /// </summary> public static float MinElement(vec2 v) => v.MinElement; /// <summary> /// Returns the maximal component of this vector. /// </summary> public static float MaxElement(vec2 v) => v.MaxElement; /// <summary> /// Returns the euclidean length of this vector. /// </summary> public static float Length(vec2 v) => v.Length; /// <summary> /// Returns the squared euclidean length of this vector. /// </summary> public static float LengthSqr(vec2 v) => v.LengthSqr; /// <summary> /// Returns the sum of all components. /// </summary> public static float Sum(vec2 v) => v.Sum; /// <summary> /// Returns the euclidean norm of this vector. /// </summary> public static float Norm(vec2 v) => v.Norm; /// <summary> /// Returns the one-norm of this vector. /// </summary> public static float Norm1(vec2 v) => v.Norm1; /// <summary> /// Returns the two-norm (euclidean length) of this vector. /// </summary> public static float Norm2(vec2 v) => v.Norm2; /// <summary> /// Returns the max-norm of this vector. /// </summary> public static float NormMax(vec2 v) => v.NormMax; /// <summary> /// Returns the p-norm of this vector. /// </summary> public static double NormP(vec2 v, double p) => v.NormP(p); /// <summary> /// Returns a copy of this vector with length one (undefined if this has zero length). /// </summary> public static vec2 Normalized(vec2 v) => v.Normalized; /// <summary> /// Returns a copy of this vector with length one (returns zero if length is zero). /// </summary> public static vec2 NormalizedSafe(vec2 v) => v.NormalizedSafe; /// <summary> /// Returns the vector angle (atan2(y, x)) in radians. /// </summary> public static double Angle(vec2 v) => v.Angle; /// <summary> /// Returns a 2D vector that was rotated by a given angle in radians (CAUTION: result is casted and may be truncated). /// </summary> public static vec2 Rotated(vec2 v, double angleInRad) => v.Rotated(angleInRad); /// <summary> /// Returns the inner product (dot product, scalar product) of the two vectors. /// </summary> public static float Dot(vec2 lhs, vec2 rhs) => vec2.Dot(lhs, rhs); /// <summary> /// Returns the euclidean distance between the two vectors. /// </summary> public static float Distance(vec2 lhs, vec2 rhs) => vec2.Distance(lhs, rhs); /// <summary> /// Returns the squared euclidean distance between the two vectors. /// </summary> public static float DistanceSqr(vec2 lhs, vec2 rhs) => vec2.DistanceSqr(lhs, rhs); /// <summary> /// Calculate the reflection direction for an incident vector (N should be normalized in order to achieve the desired result). /// </summary> public static vec2 Reflect(vec2 I, vec2 N) => vec2.Reflect(I, N); /// <summary> /// Calculate the refraction direction for an incident vector (The input parameters I and N should be normalized in order to achieve the desired result). /// </summary> public static vec2 Refract(vec2 I, vec2 N, float eta) => vec2.Refract(I, N, eta); /// <summary> /// Returns a vector pointing in the same direction as another (faceforward orients a vector to point away from a surface as defined by its normal. If dot(Nref, I) is negative faceforward returns N, otherwise it returns -N). /// </summary> public static vec2 FaceForward(vec2 N, vec2 I, vec2 Nref) => vec2.FaceForward(N, I, Nref); /// <summary> /// Returns the length of the outer product (cross product, vector product) of the two vectors. /// </summary> public static float Cross(vec2 l, vec2 r) => vec2.Cross(l, r); /// <summary> /// Returns a vec2 with independent and identically distributed uniform values between 'minValue' and 'maxValue'. /// </summary> public static vec2 Random(Random random, vec2 minValue, vec2 maxValue) => vec2.Random(random, minValue, maxValue); /// <summary> /// Returns a vec2 with independent and identically distributed uniform values between 'minValue' and 'maxValue'. /// </summary> public static vec2 RandomUniform(Random random, vec2 minValue, vec2 maxValue) => vec2.RandomUniform(random, minValue, maxValue); /// <summary> /// Returns a vec2 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance. /// </summary> public static vec2 RandomNormal(Random random, vec2 mean, vec2 variance) => vec2.RandomNormal(random, mean, variance); /// <summary> /// Returns a vec2 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance. /// </summary> public static vec2 RandomGaussian(Random random, vec2 mean, vec2 variance) => vec2.RandomGaussian(random, mean, variance); } }
/* * 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; using System.Collections.Specialized; using System.Reflection; using System.IO; using System.Web; using Mono.Addins; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Caps = OpenSim.Framework.Capabilities.Caps; using OpenSim.Framework.Capabilities; namespace OpenSim.Region.CoreModules.Avatar.Assets { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class NewFileAgentInventoryVariablePriceModule : INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; private IAssetService m_assetService; private bool m_dumpAssetsToFile = false; #region IRegionModuleBase Members public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { } public void AddRegion(Scene pScene) { m_scene = pScene; } public void RemoveRegion(Scene scene) { m_scene.EventManager.OnRegisterCaps -= RegisterCaps; m_scene = null; } public void RegionLoaded(Scene scene) { m_assetService = m_scene.RequestModuleInterface<IAssetService>(); m_scene.EventManager.OnRegisterCaps += RegisterCaps; } #endregion #region IRegionModule Members public void Close() { } public string Name { get { return "NewFileAgentInventoryVariablePriceModule"; } } public void RegisterCaps(UUID agentID, Caps caps) { UUID capID = UUID.Random(); m_log.Info("[GETMESH]: /CAPS/" + capID); caps.RegisterHandler("NewFileAgentInventoryVariablePrice", new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDNewFileAngentInventoryVariablePriceReplyResponse>("POST", "/CAPS/" + capID.ToString(), delegate(LLSDAssetUploadRequest req) { return NewAgentInventoryRequest(req,agentID); })); } #endregion public LLSDNewFileAngentInventoryVariablePriceReplyResponse NewAgentInventoryRequest(LLSDAssetUploadRequest llsdRequest, UUID agentID) { //TODO: The Mesh uploader uploads many types of content. If you're going to implement a Money based limit // You need to be aware of this and //if (llsdRequest.asset_type == "texture" || // llsdRequest.asset_type == "animation" || // llsdRequest.asset_type == "sound") // { IClientAPI client = null; IMoneyModule mm = m_scene.RequestModuleInterface<IMoneyModule>(); if (mm != null) { if (m_scene.TryGetClient(agentID, out client)) { if (!mm.UploadCovered(client, mm.UploadCharge)) { if (client != null) client.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false); LLSDNewFileAngentInventoryVariablePriceReplyResponse errorResponse = new LLSDNewFileAngentInventoryVariablePriceReplyResponse(); errorResponse.rsvp = ""; errorResponse.state = "error"; return errorResponse; } } } // } string assetName = llsdRequest.name; string assetDes = llsdRequest.description; string capsBase = "/CAPS/NewFileAgentInventoryVariablePrice/"; UUID newAsset = UUID.Random(); UUID newInvItem = UUID.Random(); UUID parentFolder = llsdRequest.folder_id; string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000") + "/"; Caps.AssetUploader uploader = new Caps.AssetUploader(assetName, assetDes, newAsset, newInvItem, parentFolder, llsdRequest.inventory_type, llsdRequest.asset_type, capsBase + uploaderPath, MainServer.Instance, m_dumpAssetsToFile); MainServer.Instance.AddStreamHandler( new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps)); string protocol = "http://"; if (MainServer.Instance.UseSSL) protocol = "https://"; string uploaderURL = protocol + m_scene.RegionInfo.ExternalHostName + ":" + MainServer.Instance.Port.ToString() + capsBase + uploaderPath; LLSDNewFileAngentInventoryVariablePriceReplyResponse uploadResponse = new LLSDNewFileAngentInventoryVariablePriceReplyResponse(); uploadResponse.rsvp = uploaderURL; uploadResponse.state = "upload"; uploadResponse.resource_cost = 0; uploadResponse.upload_price = 0; uploader.OnUpLoad += //UploadCompleteHandler; delegate( string passetName, string passetDescription, UUID passetID, UUID pinventoryItem, UUID pparentFolder, byte[] pdata, string pinventoryType, string passetType) { UploadCompleteHandler(passetName, passetDescription, passetID, pinventoryItem, pparentFolder, pdata, pinventoryType, passetType,agentID); }; return uploadResponse; } public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID, UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType, string assetType,UUID AgentID) { sbyte assType = 0; sbyte inType = 0; if (inventoryType == "sound") { inType = 1; assType = 1; } else if (inventoryType == "animation") { inType = 19; assType = 20; } else if (inventoryType == "wearable") { inType = 18; switch (assetType) { case "bodypart": assType = 13; break; case "clothing": assType = 5; break; } } else if (inventoryType == "mesh") { inType = (sbyte)InventoryType.Mesh; assType = (sbyte)AssetType.Mesh; } AssetBase asset; asset = new AssetBase(assetID, assetName, assType, AgentID.ToString()); asset.Data = data; if (m_scene.AssetService != null) m_scene.AssetService.Store(asset); InventoryItemBase item = new InventoryItemBase(); item.Owner = AgentID; item.CreatorId = AgentID.ToString(); item.ID = inventoryItem; item.AssetID = asset.FullID; item.Description = assetDescription; item.Name = assetName; item.AssetType = assType; item.InvType = inType; item.Folder = parentFolder; item.CurrentPermissions = (uint)PermissionMask.All; item.BasePermissions = (uint)PermissionMask.All; item.EveryOnePermissions = 0; item.NextPermissions = (uint)(PermissionMask.Move | PermissionMask.Modify | PermissionMask.Transfer); item.CreationDate = Util.UnixTimeSinceEpoch(); m_scene.AddInventoryItem(item); } } }
// // Copyright 2011-2013, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Windows.Devices.Enumeration; using Windows.Media.Capture; using Windows.Storage; using Windows.Storage.Pickers; using Media.Plugin.Abstractions; namespace Media.Plugin { /// <summary> /// Implementation for Media /// </summary> public class MediaImplementation : IMedia { private static readonly IEnumerable<string> SupportedVideoFileTypes = new List<string> { ".mp4", ".wmv", ".avi" }; private static readonly IEnumerable<string> SupportedImageFileTypes = new List<string> { ".jpeg", ".jpg", ".png", ".gif", ".bmp" }; /// <summary> /// Implementation /// </summary> public MediaImplementation() { this.watcher = DeviceInformation.CreateWatcher(DeviceClass.VideoCapture); this.watcher.Added += OnDeviceAdded; this.watcher.Updated += OnDeviceUpdated; this.watcher.Removed += OnDeviceRemoved; this.watcher.Start(); this.init = DeviceInformation.FindAllAsync(DeviceClass.VideoCapture).AsTask() .ContinueWith(t => { if (t.IsFaulted || t.IsCanceled) return; lock (this.devices) { foreach (DeviceInformation device in t.Result) { if (device.IsEnabled) this.devices.Add(device.Id); } this.isCameraAvailable = (this.devices.Count > 0); } this.init = null; }); } /// <inheritdoc/> public bool IsCameraAvailable { get { if (this.init != null) this.init.Wait(); return this.isCameraAvailable; } } /// <inheritdoc/> public bool IsTakePhotoSupported { get { return true; } } /// <inheritdoc/> public bool IsPickPhotoSupported { get { return true; } } /// <inheritdoc/> public bool IsTakeVideoSupported { get { return true; } } /// <inheritdoc/> public bool IsPickVideoSupported { get { return true; } } /// <summary> /// Take a photo async with specified options /// </summary> /// <param name="options">Camera Media Options</param> /// <returns>Media file of photo or null if canceled</returns> public async Task<MediaFile> TakePhotoAsync(StoreCameraMediaOptions options) { if (!IsCameraAvailable) throw new NotSupportedException(); options.VerifyOptions(); var capture = new CameraCaptureUI(); capture.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg; capture.PhotoSettings.MaxResolution = CameraCaptureUIMaxPhotoResolution.HighestAvailable; var result = await capture.CaptureFileAsync(CameraCaptureUIMode.Photo); if (result == null) return null; StorageFolder folder = ApplicationData.Current.LocalFolder; string path = options.GetFilePath(folder.Path); var directoryFull = Path.GetDirectoryName(path); var newFolder = directoryFull.Replace(folder.Path, string.Empty); if (!string.IsNullOrWhiteSpace(newFolder)) await folder.CreateFolderAsync(newFolder, CreationCollisionOption.OpenIfExists); folder = await StorageFolder.GetFolderFromPathAsync(directoryFull); string filename = Path.GetFileName(path); var file = await result.CopyAsync(folder, filename, NameCollisionOption.GenerateUniqueName).AsTask(); return new MediaFile(file.Path, () => file.OpenStreamForReadAsync().Result); } /// <summary> /// Picks a photo from the default gallery /// </summary> /// <returns>Media file or null if canceled</returns> public async Task<MediaFile> PickPhotoAsync() { var picker = new FileOpenPicker(); picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; picker.ViewMode = PickerViewMode.Thumbnail; foreach (var filter in SupportedImageFileTypes) picker.FileTypeFilter.Add(filter); var result = await picker.PickSingleFileAsync(); if (result == null) return null; return new MediaFile(result.Path, () => result.OpenStreamForReadAsync().Result); } /// <summary> /// Take a video with specified options /// </summary> /// <param name="options">Video Media Options</param> /// <returns>Media file of new video or null if canceled</returns> public async Task<MediaFile> TakeVideoAsync(StoreVideoOptions options) { if (!IsCameraAvailable) throw new NotSupportedException(); options.VerifyOptions(); var capture = new CameraCaptureUI(); capture.VideoSettings.MaxResolution = GetResolutionFromQuality(options.Quality); capture.VideoSettings.MaxDurationInSeconds = (float)options.DesiredLength.TotalSeconds; capture.VideoSettings.Format = CameraCaptureUIVideoFormat.Mp4; var result = await capture.CaptureFileAsync(CameraCaptureUIMode.Video); if (result == null) return null; return new MediaFile(result.Path, () => result.OpenStreamForReadAsync().Result); } /// <summary> /// Picks a video from the default gallery /// </summary> /// <returns>Media file of video or null if canceled</returns> public async Task<MediaFile> PickVideoAsync() { var picker = new FileOpenPicker(); picker.SuggestedStartLocation = PickerLocationId.VideosLibrary; picker.ViewMode = PickerViewMode.Thumbnail; foreach (var filter in SupportedVideoFileTypes) picker.FileTypeFilter.Add(filter); var result = await picker.PickSingleFileAsync(); if (result == null) return null; return new MediaFile(result.Path, () => result.OpenStreamForReadAsync().Result); } private Task init; private readonly HashSet<string> devices = new HashSet<string>(); private readonly DeviceWatcher watcher; private bool isCameraAvailable; private CameraCaptureUIMaxVideoResolution GetResolutionFromQuality(VideoQuality quality) { switch (quality) { case VideoQuality.High: return CameraCaptureUIMaxVideoResolution.HighestAvailable; case VideoQuality.Medium: return CameraCaptureUIMaxVideoResolution.StandardDefinition; case VideoQuality.Low: return CameraCaptureUIMaxVideoResolution.LowDefinition; default: return CameraCaptureUIMaxVideoResolution.HighestAvailable; } } private void OnDeviceUpdated(DeviceWatcher sender, DeviceInformationUpdate update) { object value; if (!update.Properties.TryGetValue("System.Devices.InterfaceEnabled", out value)) return; lock (this.devices) { if ((bool)value) this.devices.Add(update.Id); else this.devices.Remove(update.Id); this.isCameraAvailable = this.devices.Count > 0; } } private void OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate update) { lock (this.devices) { this.devices.Remove(update.Id); if (this.devices.Count == 0) this.isCameraAvailable = false; } } private void OnDeviceAdded(DeviceWatcher sender, DeviceInformation device) { if (!device.IsEnabled) return; lock (this.devices) { this.devices.Add(device.Id); this.isCameraAvailable = true; } } } }
using System; using System.Collections.Generic; using Htc.Vita.Core.Log; using Htc.Vita.Core.Util; namespace Htc.Vita.Core.Config { /// <summary> /// Class ConfigV2. /// </summary> public abstract class ConfigV2 { static ConfigV2() { TypeRegistry.RegisterDefault<ConfigV2, DummyConfigV2>(); } /// <summary> /// Registers the instance type. /// </summary> /// <typeparam name="T"></typeparam> public static void Register<T>() where T : ConfigV2, new() { TypeRegistry.Register<ConfigV2, T>(); } /// <summary> /// Gets the instance. /// </summary> /// <returns>ConfigV2.</returns> public static ConfigV2 GetInstance() { return TypeRegistry.GetInstance<ConfigV2>(); } /// <summary> /// Gets the instance. /// </summary> /// <typeparam name="T"></typeparam> /// <returns>ConfigV2.</returns> public static ConfigV2 GetInstance<T>() where T : ConfigV2, new() { return TypeRegistry.GetInstance<ConfigV2, T>(); } /// <summary> /// Get all keys. /// </summary> /// <returns>ISet&lt;System.String&gt;.</returns> public ISet<string> AllKeys() { ISet<string> result = null; try { result = OnAllKeys(); } catch (Exception e) { Logger.GetInstance(typeof(ConfigV2)).Error(e.ToString()); } return result ?? new HashSet<string>(); } /// <summary> /// Determines whether ConfigV2 has the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns><c>true</c> if ConfigV2 has the specified key; otherwise, <c>false</c>.</returns> public bool HasKey(string key) { var result = false; try { result = OnHasKey(key); } catch (Exception e) { Logger.GetInstance(typeof(ConfigV2)).Error(e.ToString()); } return result; } /// <summary> /// Gets the value. /// </summary> /// <param name="key">The key.</param> /// <returns>System.String.</returns> public string Get(string key) { return Get(key, null); } /// <summary> /// Gets the value. /// </summary> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns>System.String.</returns> public string Get( string key, string defaultValue) { if (string.IsNullOrWhiteSpace(key)) { return defaultValue; } string result = null; try { result = OnGet(key); } catch (Exception e) { Logger.GetInstance(typeof(ConfigV2)).Error(e.ToString()); } return result ?? defaultValue; } /// <summary> /// Gets the bool value. /// </summary> /// <param name="key">The key.</param> /// <returns>System.Boolean.</returns> public bool GetBool(string key) { return GetBool( key, false ); } /// <summary> /// Gets the bool value. /// </summary> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns>System.Boolean.</returns> public bool GetBool( string key, bool defaultValue) { return Util.Convert.ToBool( Get(key), defaultValue ); } /// <summary> /// Gets the double value. /// </summary> /// <param name="key">The key.</param> /// <returns>System.Double.</returns> public double GetDouble(string key) { return GetDouble( key, 0.0D ); } /// <summary> /// Gets the double value. /// </summary> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns>System.Double.</returns> public double GetDouble( string key, double defaultValue) { return Util.Convert.ToDouble( Get(key), defaultValue ); } /// <summary> /// Gets the float value. /// </summary> /// <param name="key">The key.</param> /// <returns>System.Single.</returns> public float GetFloat(string key) { return GetFloat( key, 0.0F ); } /// <summary> /// Gets the float value. /// </summary> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns>System.Single.</returns> public float GetFloat( string key, float defaultValue) { return (float) Util.Convert.ToDouble( Get(key), defaultValue ); } /// <summary> /// Gets the int value. /// </summary> /// <param name="key">The key.</param> /// <returns>System.Int32.</returns> public int GetInt(string key) { return GetInt( key, 0 ); } /// <summary> /// Gets the int value. /// </summary> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns>System.Int32.</returns> public int GetInt( string key, int defaultValue) { return Util.Convert.ToInt32( Get(key), defaultValue ); } /// <summary> /// Gets the long value. /// </summary> /// <param name="key">The key.</param> /// <returns>System.Int64.</returns> public long GetLong(string key) { return GetLong( key, 0L ); } /// <summary> /// Gets the long value. /// </summary> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns>System.Int64.</returns> public long GetLong( string key, long defaultValue) { return Util.Convert.ToInt64( Get(key), defaultValue ); } /// <summary> /// Called when getting all keys. /// </summary> /// <returns>ISet&lt;System.String&gt;.</returns> protected abstract ISet<string> OnAllKeys(); /// <summary> /// Called when determining whether Config has the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns><c>true</c> if Config has the specified key, <c>false</c> otherwise.</returns> protected abstract bool OnHasKey(string key); /// <summary> /// Called when getting value. /// </summary> /// <param name="key">The key.</param> /// <returns>System.String.</returns> protected abstract string OnGet(string key); } }
// Copyright 2008-2009 Louis DeJardin - http://whereslou.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Text; using Spark.Compiler.ChunkVisitors; using Spark.Parser.Code; namespace Spark.Compiler.ChunkVisitors { public class DetectCodeExpressionVisitor : AbstractChunkVisitor { public class Entry { public string Expression { get; set; } public bool Detected { get; set; } } readonly IList<Entry> _entries = new List<Entry>(); public DetectCodeExpressionVisitor(RenderPartialChunk currentPartial) { if (currentPartial != null) EnterRenderPartial(currentPartial); } public Entry Add(string expression) { var entry = new Entry {Expression = expression}; _entries.Add(entry); return entry; } void Examine(Snippets code) { if (Snippets.IsNullOrEmpty(code)) return; var codeString = code.ToString(); foreach(var entry in _entries) { if (entry.Detected) continue; if (codeString.Contains(entry.Expression)) entry.Detected = true; } } protected override void Visit(UseImportChunk chunk) { } protected override void Visit(ContentSetChunk chunk) { Accept(chunk.Body); } protected override void Visit(RenderPartialChunk chunk) { EnterRenderPartial(chunk); Accept(chunk.FileContext.Contents); ExitRenderPartial(chunk); } protected override void Visit(RenderSectionChunk chunk) { var outer = ExitRenderPartial(); if (string.IsNullOrEmpty(chunk.Name)) { Accept(outer.Body); } else if (outer.Sections.ContainsKey(chunk.Name)) { Accept(outer.Sections[chunk.Name]); } else { EnterRenderPartial(outer); Accept(chunk.Default); ExitRenderPartial(outer); } EnterRenderPartial(outer); } protected override void Visit(UseAssemblyChunk chunk) { //no-op } protected override void Visit(MacroChunk chunk) { //no-op } protected override void Visit(CodeStatementChunk chunk) { Examine(chunk.Code); } protected override void Visit(ExtensionChunk chunk) { // Extension content can't really be examined this way. It's too variable. } protected override void Visit(ConditionalChunk chunk) { if (!Snippets.IsNullOrEmpty(chunk.Condition)) Examine(chunk.Condition); Accept(chunk.Body); } protected override void Visit(ViewDataModelChunk chunk) { //no-op } protected override void Visit(ViewDataChunk chunk) { //no-op } protected override void Visit(AssignVariableChunk chunk) { Examine(chunk.Value); } protected override void Visit(UseContentChunk chunk) { Accept(chunk.Default); } protected override void Visit(GlobalVariableChunk chunk) { //no-op } protected override void Visit(ScopeChunk chunk) { Accept(chunk.Body); } protected override void Visit(ForEachChunk chunk) { Examine(chunk.Code); Accept(chunk.Body); } protected override void Visit(SendLiteralChunk chunk) { //no-op } protected override void Visit(LocalVariableChunk chunk) { Examine(chunk.Value); } protected override void Visit(UseMasterChunk chunk) { //no-op } protected override void Visit(DefaultVariableChunk chunk) { Examine(chunk.Value); } protected override void Visit(SendExpressionChunk chunk) { Examine(chunk.Code); } protected override void Visit(ContentChunk chunk) { Accept(chunk.Body); } protected override void Visit(UseNamespaceChunk chunk) { //no-op } protected override void Visit(PageBaseTypeChunk chunk) { } protected override void Visit(CacheChunk chunk) { Examine(chunk.Key); Examine(chunk.Expires); Accept(chunk.Body); } protected override void Visit(MarkdownChunk chunk) { Accept(chunk.Body); } } }
// This file was generated by the Gtk# code generator. // Any changes made will be lost if regenerated. namespace GLib { using System; #region Autogenerated code public interface File : GLib.IWrapper { bool Copy(GLib.File destination, GLib.FileCopyFlags flags, GLib.Cancellable cancellable, GLib.FileProgressCallback progress_callback); string Basename { get; } GLib.FileOutputStream Create(GLib.FileCreateFlags flags, GLib.Cancellable cancellable); void EjectMountableWithOperation(GLib.MountUnmountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); void LoadContentsAsync(GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileIOStream OpenReadwriteFinish(GLib.AsyncResult res); GLib.File SetDisplayName(string display_name, GLib.Cancellable cancellable); GLib.FileAttributeInfoList QueryWritableNamespaces(GLib.Cancellable cancellable); void LoadPartialContentsAsync(GLib.Cancellable cancellable, GLib.FileReadMoreCallback read_more_callback, GLib.AsyncReadyCallback cb); void ReadAsync(int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); void SetAttributesAsync(GLib.FileInfo info, GLib.FileQueryInfoFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileIOStream CreateReadwriteFinish(GLib.AsyncResult res); bool EjectMountableFinish(GLib.AsyncResult result); GLib.AppInfo QueryDefaultHandler(GLib.Cancellable cancellable); string Path { get; } bool Equal(GLib.File file2); bool SetAttributesFromInfo(GLib.FileInfo info, GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); bool HasPrefix(GLib.File prefix); GLib.FileInfo QueryInfoFinish(GLib.AsyncResult res); GLib.File SetDisplayNameFinish(GLib.AsyncResult res); bool MakeDirectory(GLib.Cancellable cancellable); GLib.FileOutputStream AppendToFinish(GLib.AsyncResult res); bool LoadContents(GLib.Cancellable cancellable, string contents, out ulong length, string etag_out); GLib.File Parent { get; } void EjectMountable(GLib.MountUnmountFlags flags, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool Delete(GLib.Cancellable cancellable); GLib.FileOutputStream AppendTo(GLib.FileCreateFlags flags, GLib.Cancellable cancellable); GLib.FileType QueryFileType(GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); bool EjectMountableWithOperationFinish(GLib.AsyncResult result); string GetRelativePath(GLib.File descendant); bool Move(GLib.File destination, GLib.FileCopyFlags flags, GLib.Cancellable cancellable, GLib.FileProgressCallback progress_callback); GLib.FileEnumerator EnumerateChildren(string attributes, GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); void FindEnclosingMountAsync(int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool CopyFinish(GLib.AsyncResult res); GLib.FileInfo QueryInfo(string attributes, GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); bool PollMountableFinish(GLib.AsyncResult result); void SetDisplayNameAsync(string display_name, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool SetAttributeInt64(string attribute, long value, GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); void UnmountMountableWithOperation(GLib.MountUnmountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); void ReplaceReadwriteAsync(string etag, bool make_backup, GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.File GetChildForDisplayName(string display_name); void ReplaceContentsAsync(string contents, string etag, bool make_backup, GLib.FileCreateFlags flags, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); void StopMountable(GLib.MountUnmountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool StopMountableFinish(GLib.AsyncResult result); void CreateAsync(GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileMonitor Monitor(GLib.FileMonitorFlags flags, GLib.Cancellable cancellable); void QueryInfoAsync(string attributes, GLib.FileQueryInfoFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool IsNative { get; } bool QueryExists(GLib.Cancellable cancellable); void CreateReadwriteAsync(GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool SetAttribute(string attribute, GLib.FileAttributeType type, IntPtr value_p, GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); bool UnmountMountableWithOperationFinish(GLib.AsyncResult result); bool Trash(GLib.Cancellable cancellable); GLib.FileIOStream ReplaceReadwriteFinish(GLib.AsyncResult res); GLib.File GetChild(string name); bool LoadPartialContentsFinish(GLib.AsyncResult res, string contents, out ulong length, string etag_out); bool MakeDirectoryWithParents(GLib.Cancellable cancellable); GLib.File Dup(); GLib.FileIOStream CreateReadwrite(GLib.FileCreateFlags flags, GLib.Cancellable cancellable); GLib.Mount FindEnclosingMountFinish(GLib.AsyncResult res); GLib.FileInputStream Read(GLib.Cancellable cancellable); bool LoadContentsFinish(GLib.AsyncResult res, string contents, out ulong length, string etag_out); void QueryFilesystemInfoAsync(string attributes, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.File ResolveRelativePath(string relative_path); GLib.FileOutputStream CreateFinish(GLib.AsyncResult res); void MountMountable(GLib.MountMountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileOutputStream ReplaceFinish(GLib.AsyncResult res); GLib.File MountMountableFinish(GLib.AsyncResult result); void PollMountable(GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileEnumerator EnumerateChildrenFinish(GLib.AsyncResult res); string UriScheme { get; } bool HasUriScheme(string uri_scheme); GLib.FileInfo QueryFilesystemInfoFinish(GLib.AsyncResult res); bool StartMountableFinish(GLib.AsyncResult result); string ParsedName { get; } GLib.FileIOStream OpenReadwrite(GLib.Cancellable cancellable); void OpenReadwriteAsync(int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool SupportsThreadContexts(); bool UnmountMountableFinish(GLib.AsyncResult result); GLib.Mount FindEnclosingMount(GLib.Cancellable cancellable); void ReplaceAsync(string etag, bool make_backup, GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); void StartMountable(GLib.DriveStartFlags flags, GLib.MountOperation start_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); void CopyAsync(GLib.File destination, GLib.FileCopyFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.FileProgressCallback progress_callback, GLib.AsyncReadyCallback cb); GLib.FileAttributeInfoList QuerySettableAttributes(GLib.Cancellable cancellable); bool SetAttributesFinish(GLib.AsyncResult result, GLib.FileInfo info); void MountEnclosingVolume(GLib.MountMountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool ReplaceContentsFinish(GLib.AsyncResult res, string new_etag); bool SetAttributeUint32(string attribute, uint value, GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); void AppendToAsync(GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool SetAttributeInt32(string attribute, int value, GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); bool MountEnclosingVolumeFinish(GLib.AsyncResult result); bool SetAttributeByteString(string attribute, string value, GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); bool CopyAttributes(GLib.File destination, GLib.FileCopyFlags flags, GLib.Cancellable cancellable); bool SetAttributeString(string attribute, string value, GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); GLib.FileOutputStream Replace(string etag, bool make_backup, GLib.FileCreateFlags flags, GLib.Cancellable cancellable); void EnumerateChildrenAsync(string attributes, GLib.FileQueryInfoFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool SetAttributeUint64(string attribute, ulong value, GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); bool MakeSymbolicLink(string symlink_value, GLib.Cancellable cancellable); bool ReplaceContents(string contents, string etag, bool make_backup, GLib.FileCreateFlags flags, string new_etag, GLib.Cancellable cancellable); void UnmountMountable(GLib.MountUnmountFlags flags, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileInfo QueryFilesystemInfo(string attributes, GLib.Cancellable cancellable); GLib.FileInputStream ReadFinish(GLib.AsyncResult res); GLib.FileIOStream ReplaceReadwrite(string etag, bool make_backup, GLib.FileCreateFlags flags, GLib.Cancellable cancellable); #region Customized extensions #line 1 "File.custom" // File.custom - customizations to GLib.File // // Authors: Stephane Delcroix <stephane@delcroix.org> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // bool Exists { get; } System.Uri Uri { get; } bool Delete (); void Dispose (); #endregion } [GLib.GInterface (typeof (FileAdapter))] public interface FileImplementor : GLib.IWrapper { GLib.File Dup (); uint Hash (); bool Equal (GLib.File file2); bool IsNative { get; } bool HasUriScheme (string uri_scheme); string UriScheme { get; } string Basename { get; } string Path { get; } string Uri { get; } string ParseName { get; } GLib.File Parent { get; } bool PrefixMatches (GLib.File file); string GetRelativePath (GLib.File descendant); GLib.File ResolveRelativePath (string relative_path); GLib.File GetChildForDisplayName (string display_name); GLib.FileEnumerator EnumerateChildren (string attributes, GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); void EnumerateChildrenAsync (string attributes, GLib.FileQueryInfoFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileEnumerator EnumerateChildrenFinish (GLib.AsyncResult res); GLib.FileInfo QueryInfo (string attributes, GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); void QueryInfoAsync (string attributes, GLib.FileQueryInfoFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileInfo QueryInfoFinish (GLib.AsyncResult res); GLib.FileInfo QueryFilesystemInfo (string attributes, GLib.Cancellable cancellable); void QueryFilesystemInfoAsync (string attributes, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileInfo QueryFilesystemInfoFinish (GLib.AsyncResult res); GLib.Mount FindEnclosingMount (GLib.Cancellable cancellable); void FindEnclosingMountAsync (int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.Mount FindEnclosingMountFinish (GLib.AsyncResult res); GLib.File SetDisplayName (string display_name, GLib.Cancellable cancellable); void SetDisplayNameAsync (string display_name, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.File SetDisplayNameFinish (GLib.AsyncResult res); GLib.FileAttributeInfoList QuerySettableAttributes (GLib.Cancellable cancellable); void QuerySettableAttributesAsync (); void QuerySettableAttributesFinish (); GLib.FileAttributeInfoList QueryWritableNamespaces (GLib.Cancellable cancellable); void QueryWritableNamespacesAsync (); void QueryWritableNamespacesFinish (); bool SetAttribute (string attribute, GLib.FileAttributeType type, IntPtr value_p, GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); bool SetAttributesFromInfo (GLib.FileInfo info, GLib.FileQueryInfoFlags flags, GLib.Cancellable cancellable); void SetAttributesAsync (GLib.FileInfo info, GLib.FileQueryInfoFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool SetAttributesFinish (GLib.AsyncResult result, GLib.FileInfo info); GLib.FileInputStream ReadFn (GLib.Cancellable cancellable); void ReadAsync (int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileInputStream ReadFinish (GLib.AsyncResult res); GLib.FileOutputStream AppendTo (GLib.FileCreateFlags flags, GLib.Cancellable cancellable); void AppendToAsync (GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileOutputStream AppendToFinish (GLib.AsyncResult res); GLib.FileOutputStream Create (GLib.FileCreateFlags flags, GLib.Cancellable cancellable); void CreateAsync (GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileOutputStream CreateFinish (GLib.AsyncResult res); GLib.FileOutputStream Replace (string etag, bool make_backup, GLib.FileCreateFlags flags, GLib.Cancellable cancellable); void ReplaceAsync (string etag, bool make_backup, GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileOutputStream ReplaceFinish (GLib.AsyncResult res); bool DeleteFile (GLib.Cancellable cancellable); void DeleteFileAsync (); void DeleteFileFinish (); bool Trash (GLib.Cancellable cancellable); void TrashAsync (); void TrashFinish (); bool MakeDirectory (GLib.Cancellable cancellable); void MakeDirectoryAsync (); void MakeDirectoryFinish (); bool MakeSymbolicLink (string symlink_value, GLib.Cancellable cancellable); void MakeSymbolicLinkAsync (); void MakeSymbolicLinkFinish (); bool Copy (GLib.File destination, GLib.FileCopyFlags flags, GLib.Cancellable cancellable, GLib.FileProgressCallback progress_callback); void CopyAsync (GLib.File destination, GLib.FileCopyFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.FileProgressCallback progress_callback, GLib.AsyncReadyCallback cb); bool CopyFinish (GLib.AsyncResult res); bool Move (GLib.File destination, GLib.FileCopyFlags flags, GLib.Cancellable cancellable, GLib.FileProgressCallback progress_callback); void MoveAsync (); void MoveFinish (); void MountMountable (GLib.MountMountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.File MountMountableFinish (GLib.AsyncResult result); void UnmountMountable (GLib.MountUnmountFlags flags, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool UnmountMountableFinish (GLib.AsyncResult result); void EjectMountable (GLib.MountUnmountFlags flags, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool EjectMountableFinish (GLib.AsyncResult result); void MountEnclosingVolume (GLib.MountMountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool MountEnclosingVolumeFinish (GLib.AsyncResult result); GLib.FileMonitor MonitorDir (GLib.FileMonitorFlags flags, GLib.Cancellable cancellable); GLib.FileMonitor MonitorFile (GLib.FileMonitorFlags flags, GLib.Cancellable cancellable); GLib.FileIOStream OpenReadwrite (GLib.Cancellable cancellable); void OpenReadwriteAsync (int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileIOStream OpenReadwriteFinish (GLib.AsyncResult res); GLib.FileIOStream CreateReadwrite (GLib.FileCreateFlags flags, GLib.Cancellable cancellable); void CreateReadwriteAsync (GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileIOStream CreateReadwriteFinish (GLib.AsyncResult res); GLib.FileIOStream ReplaceReadwrite (string etag, bool make_backup, GLib.FileCreateFlags flags, GLib.Cancellable cancellable); void ReplaceReadwriteAsync (string etag, bool make_backup, GLib.FileCreateFlags flags, int io_priority, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); GLib.FileIOStream ReplaceReadwriteFinish (GLib.AsyncResult res); void StartMountable (GLib.DriveStartFlags flags, GLib.MountOperation start_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool StartMountableFinish (GLib.AsyncResult result); void StopMountable (GLib.MountUnmountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool StopMountableFinish (GLib.AsyncResult result); void UnmountMountableWithOperation (GLib.MountUnmountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool UnmountMountableWithOperationFinish (GLib.AsyncResult result); void EjectMountableWithOperation (GLib.MountUnmountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool EjectMountableWithOperationFinish (GLib.AsyncResult result); void PollMountable (GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb); bool PollMountableFinish (GLib.AsyncResult result); } #endregion }
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 MasterChef.Web.Areas.HelpPage.ModelDescriptions; using MasterChef.Web.Areas.HelpPage.Models; namespace MasterChef.Web.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.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using Trionic5Tools; using System.IO; namespace T5Suite2 { public partial class frmFreeTuneSettings : DevExpress.XtraEditors.XtraForm { public frmFreeTuneSettings() { InitializeComponent(); radioGroup1.EditValue = 0; } public void SetTurboType(TurboType turbo) { comboBoxEdit3.SelectedIndex = (int)turbo; } public void SetInjectorType(InjectorType injectors) { comboBoxEdit2.SelectedIndex = (int)injectors; } public void SetMapSensorType(MapSensorType mapsensor) { comboBoxEdit1.SelectedIndex = (int)mapsensor; } public void SetRPMLimiter(int rpmlimit) { spinEdit3.EditValue = rpmlimit*10; } public int GetRPMLimiter() { return Convert.ToInt32(spinEdit3.EditValue)/10; } public void SetKnockTime(int knockTime) { spinEdit4.EditValue = knockTime; } public int GetKnockTime() { return Convert.ToInt32(spinEdit4.EditValue); } public BPCType GetBCVType() { return (BPCType)comboBoxEdit4.SelectedIndex; } public void SetBPCType(BPCType valve) { comboBoxEdit4.SelectedIndex = (int)valve; } public TurboType GetTurboType() { return (TurboType)comboBoxEdit3.SelectedIndex; } public InjectorType GetInjectorType() { return (InjectorType)comboBoxEdit2.SelectedIndex; } public MapSensorType GetMapSensorType() { return (MapSensorType)comboBoxEdit1.SelectedIndex; } public int GetPeakTorque() { return Convert.ToInt32(spinEdit1.EditValue); } public double GetPeakBoost() { return Convert.ToDouble(spinEdit2.EditValue); } public bool IsTorqueBased { get { if (Convert.ToInt32(radioGroup1.EditValue) == 0) { return true; } return false; } } private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e) { // set max torque achievable (400Nm) UpdateMaxima((TurboType)comboBoxEdit3.SelectedIndex, (InjectorType)comboBoxEdit2.SelectedIndex, (MapSensorType)comboBoxEdit1.SelectedIndex); } private void UpdateMaxima(TurboType turbo, InjectorType injectors, MapSensorType mapSensor) { switch (mapSensor) { case MapSensorType.MapSensor25: // max achievable 400Nm / 1.45 bar if (injectors == InjectorType.Stock) { spinEdit1.Properties.MaxValue = 400; spinEdit2.Properties.MaxValue = (decimal)1.30; } else { spinEdit1.Properties.MaxValue = 450; spinEdit2.Properties.MaxValue = (decimal)1.45; } break; case MapSensorType.MapSensor30: switch (injectors) { case InjectorType.Stock: spinEdit1.Properties.MaxValue = 400; spinEdit2.Properties.MaxValue = (decimal)1.30; break; case InjectorType.GreenGiants: switch (turbo) { case TurboType.Stock: case TurboType.TD0415T: spinEdit1.Properties.MaxValue = 450; spinEdit2.Properties.MaxValue = (decimal)1.45; break; case TurboType.GT28BB: case TurboType.GT28RS: case TurboType.TD0419T: spinEdit1.Properties.MaxValue = 550; spinEdit2.Properties.MaxValue = (decimal)1.70; break; case TurboType.GT3071R: case TurboType.HX35w: spinEdit1.Properties.MaxValue = 550; spinEdit2.Properties.MaxValue = (decimal)1.50; break; case TurboType.HX40w: case TurboType.S400SX371: spinEdit1.Properties.MaxValue = 550; spinEdit2.Properties.MaxValue = (decimal)1.40; break; } break; case InjectorType.Siemens630Dekas: // 3.0 bar sensor, 630cc injectors -> max 600Nm switch (turbo) { case TurboType.Stock: case TurboType.TD0415T: spinEdit1.Properties.MaxValue = 450; spinEdit2.Properties.MaxValue = (decimal)1.45; break; case TurboType.GT28BB: case TurboType.GT28RS: case TurboType.TD0419T: spinEdit1.Properties.MaxValue = 580; spinEdit2.Properties.MaxValue = (decimal)1.75; break; case TurboType.GT3071R: case TurboType.HX35w: spinEdit1.Properties.MaxValue = 600; spinEdit2.Properties.MaxValue = (decimal)1.80; break; case TurboType.HX40w: case TurboType.S400SX371: spinEdit1.Properties.MaxValue = 600; spinEdit2.Properties.MaxValue = (decimal)1.70; break; } break; case InjectorType.Siemens875Dekas: case InjectorType.Siemens1000cc: // 3.0 bar sensor, 630cc injectors -> limit to turbo only switch (turbo) { case TurboType.Stock: case TurboType.TD0415T: spinEdit1.Properties.MaxValue = 450; spinEdit2.Properties.MaxValue = (decimal)1.45; break; case TurboType.GT28BB: case TurboType.GT28RS: case TurboType.TD0419T: spinEdit1.Properties.MaxValue = 580; spinEdit2.Properties.MaxValue = (decimal)1.75; break; case TurboType.GT3071R: case TurboType.HX35w: spinEdit1.Properties.MaxValue = 620; spinEdit2.Properties.MaxValue = (decimal)1.9; break; case TurboType.HX40w: case TurboType.S400SX371: spinEdit1.Properties.MaxValue = 670; spinEdit2.Properties.MaxValue = (decimal)2.0; break; } break; } break; case MapSensorType.MapSensor35: case MapSensorType.MapSensor40: case MapSensorType.MapSensor50: switch (injectors) { case InjectorType.Stock: spinEdit1.Properties.MaxValue = 400; spinEdit2.Properties.MaxValue = (decimal)1.30; break; case InjectorType.GreenGiants: switch (turbo) { case TurboType.Stock: case TurboType.TD0415T: spinEdit1.Properties.MaxValue = 450; spinEdit2.Properties.MaxValue = (decimal)1.45; break; case TurboType.GT28BB: case TurboType.GT28RS: case TurboType.TD0419T: spinEdit1.Properties.MaxValue = 550; spinEdit2.Properties.MaxValue = (decimal)1.70; break; case TurboType.GT3071R: case TurboType.HX35w: spinEdit1.Properties.MaxValue = 550; spinEdit2.Properties.MaxValue = (decimal)1.50; break; case TurboType.HX40w: case TurboType.S400SX371: spinEdit1.Properties.MaxValue = 550; spinEdit2.Properties.MaxValue = (decimal)1.40; break; } break; case InjectorType.Siemens630Dekas: // 3.0 bar sensor, 630cc injectors -> max 600Nm switch (turbo) { case TurboType.Stock: case TurboType.TD0415T: spinEdit1.Properties.MaxValue = 450; spinEdit2.Properties.MaxValue = (decimal)1.45; break; case TurboType.GT28BB: case TurboType.GT28RS: case TurboType.TD0419T: spinEdit1.Properties.MaxValue = 580; spinEdit2.Properties.MaxValue = (decimal)1.75; break; case TurboType.GT3071R: case TurboType.HX35w: spinEdit1.Properties.MaxValue = 600; spinEdit2.Properties.MaxValue = (decimal)1.80; break; case TurboType.HX40w: case TurboType.S400SX371: spinEdit1.Properties.MaxValue = 600; spinEdit2.Properties.MaxValue = (decimal)1.70; break; } break; case InjectorType.Siemens875Dekas: case InjectorType.Siemens1000cc: // 3.0 bar sensor, 630cc injectors -> limit to turbo only switch (turbo) { case TurboType.Stock: case TurboType.TD0415T: spinEdit1.Properties.MaxValue = 450; spinEdit2.Properties.MaxValue = (decimal)1.45; break; case TurboType.GT28BB: case TurboType.GT28RS: case TurboType.TD0419T: spinEdit1.Properties.MaxValue = 580; spinEdit2.Properties.MaxValue = (decimal)1.75; break; case TurboType.GT3071R: case TurboType.HX35w: spinEdit1.Properties.MaxValue = 620; spinEdit2.Properties.MaxValue = (decimal)1.9; break; case TurboType.HX40w: case TurboType.S400SX371: spinEdit1.Properties.MaxValue = 670; spinEdit2.Properties.MaxValue = (decimal)2.2; break; } break; } break; } UpdateStage(); } private void UpdateStage() { // set the correct image Int32 Nm = Convert.ToInt32(spinEdit1.EditValue); Int32 stage = 0; if (Nm < 300) stage = 0; else if (Nm < 350) stage = 1; else if (Nm < 400) stage = 2; else if (Nm < 450) stage = 3; else if (Nm < 500) stage = 4; else if (Nm < 550) stage = 5; else if (Nm < 600) stage = 6; else if (Nm < 650) stage = 7; else stage = 8; string pictureName = Application.StartupPath + "\\imgs\\stage" + stage.ToString() + ".jpg"; if (File.Exists(pictureName)) { pictureBox1.Load(pictureName); } } private void comboBoxEdit2_SelectedIndexChanged(object sender, EventArgs e) { // injectors changed UpdateMaxima((TurboType)comboBoxEdit3.SelectedIndex, (InjectorType)comboBoxEdit2.SelectedIndex, (MapSensorType)comboBoxEdit1.SelectedIndex); } private void comboBoxEdit3_SelectedIndexChanged(object sender, EventArgs e) { UpdateMaxima((TurboType)comboBoxEdit3.SelectedIndex, (InjectorType)comboBoxEdit2.SelectedIndex, (MapSensorType)comboBoxEdit1.SelectedIndex); } private void simpleButton2_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; this.Close(); } private void simpleButton1_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; this.Close(); } private void radioGroup1_EditValueChanged(object sender, EventArgs e) { if (Convert.ToInt32(radioGroup1.EditValue) == 0) { spinEdit1.Enabled = true; spinEdit2.Enabled = false; } else { spinEdit1.Enabled = false; spinEdit2.Enabled = true; } } private void spinEdit1_ValueChanged(object sender, EventArgs e) { UpdateStage(); } private void frmFreeTuneSettings_Shown(object sender, EventArgs e) { UpdateStage(); } } }
//============================================================================= // System : Sandcastle Help File Builder Utilities // File : ImageReferenceCollection.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 06/06/2010 // Note : Copyright 2008-2010, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains a collection class used to hold the conceptual content // image reference information. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.6.0.7 04/24/2008 EFW Created the code // 1.8.0.0 07/25/2008 EFW Reworked to support new MSBuild project format // 1.9.0.0 06/06/2010 EFW Added support for multi-format build output //============================================================================= using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Xml; using Microsoft.Build.Evaluation; using SandcastleBuilder.Utils.BuildEngine; namespace SandcastleBuilder.Utils.ConceptualContent { /// <summary> /// This collection class is used to hold the conceptual content image /// references for a project. /// </summary> public class ImageReferenceCollection : BindingList<ImageReference> { #region Private data members //===================================================================== private SandcastleProject projectFile; #endregion #region Properties //===================================================================== /// <summary> /// This can be used to get an image by its unique ID (case-sensitive) /// </summary> /// <param name="id">The ID of the item to get.</param> /// <value>Returns the image with the specified /// <see cref="ImageReference.Id" /> or null if not found.</value> public ImageReference this[string id] { get { foreach(ImageReference ir in this) if(ir.Id == id) return ir; return null; } } #endregion #region Constructor //===================================================================== /// <summary> /// Constructor /// </summary> /// <param name="project">The project file containing the image /// build items.</param> public ImageReferenceCollection(SandcastleProject project) { projectFile = project; this.Refresh(); } #endregion #region Sort collection //===================================================================== /// <summary> /// This is used to sort the collection /// </summary> /// <remarks>Values are sorted by display title and ID. Comparisons /// are case-insensitive.</remarks> public void Sort() { ((List<ImageReference>)base.Items).Sort((x, y) => { int result = String.Compare(x.DisplayTitle, y.DisplayTitle, StringComparison.CurrentCultureIgnoreCase); if(result == 0) result = String.Compare(x.Id, y.Id, StringComparison.OrdinalIgnoreCase); return result; }); } #endregion #region Write the image reference collection to a map file //===================================================================== /// <summary> /// Write the image reference collection to a map file ready for use /// by <b>BuildAssembler</b>. /// </summary> /// <param name="filename">The file to which the image reference /// collection is saved.</param> /// <param name="imagePath">The path to which the image files /// should be copied.</param> /// <param name="builder">The build process</param> /// <remarks>Images with their <see cref="ImageReference.CopyToMedia" /> /// property set to true are copied to the media folder immediately.</remarks> public void SaveAsSharedContent(string filename, string imagePath, BuildProcess builder) { XmlWriterSettings settings = new XmlWriterSettings(); XmlWriter writer = null; string destFile; builder.EnsureOutputFoldersExist("media"); try { settings.Indent = true; settings.CloseOutput = true; writer = XmlWriter.Create(filename, settings); writer.WriteStartDocument(); // There are normally some attributes on this element but // they aren't used by Sandcastle so we'll ignore them. writer.WriteStartElement("stockSharedContentDefinitions"); foreach(ImageReference ir in this) { writer.WriteStartElement("item"); writer.WriteAttributeString("id", ir.Id); writer.WriteStartElement("image"); // The art build component assumes everything is in a // single, common folder. The build process will ensure // that happens. As such, we only need the filename here. writer.WriteAttributeString("file", ir.Filename); if(!String.IsNullOrEmpty(ir.AlternateText)) { writer.WriteStartElement("altText"); writer.WriteValue(ir.AlternateText); writer.WriteEndElement(); } writer.WriteEndElement(); // </image> writer.WriteEndElement(); // </item> destFile = Path.Combine(imagePath, ir.Filename); if(File.Exists(destFile)) { builder.ReportWarning("BE0010", "Image file '{0}' " + "already exists. It will be replaced by '{1}'.", destFile, ir.FullPath); } builder.ReportProgress(" {0} -> {1}", ir.FullPath, destFile); // The attributes are set to Normal so that it can be deleted after the build File.Copy(ir.FullPath, destFile, true); File.SetAttributes(destFile, FileAttributes.Normal); // Copy it to the output media folders if CopyToMedia is true if(ir.CopyToMedia) foreach(string baseFolder in builder.HelpFormatOutputFolders) { destFile = Path.Combine(baseFolder + "media", ir.Filename); builder.ReportProgress(" {0} -> {1} (Always copied)", ir.FullPath, destFile); File.Copy(ir.FullPath, destFile, true); File.SetAttributes(destFile, FileAttributes.Normal); } } writer.WriteEndElement(); // </stockSharedContentDefinitions> writer.WriteEndDocument(); } finally { if(writer != null) writer.Close(); } } #endregion #region Helper methods //===================================================================== /// <summary> /// This is used to refresh the collection by loading the image /// build items from the project. /// </summary> public void Refresh() { this.Clear(); foreach(ProjectItem item in projectFile.MSBuildProject.GetItems(BuildAction.Image.ToString())) this.Add(new ImageReference(new FileItem(new ProjectElement(projectFile, item)))); this.Sort(); } /// <summary> /// Find the image with the specified ID (case-insensitive). /// </summary> /// <param name="id">The ID to find</param> /// <returns>The image if found or null if not found</returns> public ImageReference FindId(string id) { foreach(ImageReference ir in this) if(String.Compare(ir.Id, id, StringComparison.OrdinalIgnoreCase) == 0) return ir; return null; } /// <summary> /// Find the image with the specified filename. /// </summary> /// <param name="filename">The filename to find</param> /// <returns>The image if found or null if not found</returns> public ImageReference FindImageFile(string filename) { foreach(ImageReference ir in this) if(String.Compare(ir.FullPath, filename, StringComparison.OrdinalIgnoreCase) == 0) return ir; return null; } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.ObjectModel; using System.Diagnostics; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Microsoft.VisualStudio.Debugger.Metadata; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { /// <summary> /// Type member expansion. /// </summary> /// <remarks> /// Includes accesses to static members with instance receivers and /// accesses to instance members with dynamic receivers. /// </remarks> internal sealed class MemberExpansion : Expansion { internal static Expansion CreateExpansion( DkmInspectionContext inspectionContext, Type declaredType, DkmClrValue value, ExpansionFlags flags, Predicate<MemberInfo> predicate, Formatter formatter) { var runtimeType = value.Type.GetLmrType(); // Primitives, enums and null values with a declared type that is an interface have no visible members. Debug.Assert(!runtimeType.IsInterface || value.IsNull); if (formatter.IsPredefinedType(runtimeType) || runtimeType.IsEnum || runtimeType.IsInterface) { return null; } var expansions = ArrayBuilder<Expansion>.GetInstance(); // From the members, collect the fields and properties, // separated into static and instance members. var staticMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance(); var instanceMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance(); var appDomain = value.Type.AppDomain; // Expand members. (Ideally, this should be done lazily.) var allMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance(); var includeInherited = (flags & ExpansionFlags.IncludeBaseMembers) == ExpansionFlags.IncludeBaseMembers; var hideNonPublic = (inspectionContext.EvaluationFlags & DkmEvaluationFlags.HideNonPublicMembers) == DkmEvaluationFlags.HideNonPublicMembers; runtimeType.AppendTypeMembers(allMembers, predicate, declaredType, appDomain, includeInherited, hideNonPublic); foreach (var member in allMembers) { var name = member.Name; if (name.IsCompilerGenerated()) { continue; } if (member.IsStatic) { staticMembers.Add(member); } else if (!value.IsNull) { instanceMembers.Add(member); } } allMembers.Free(); // Public and non-public instance members. Expansion publicInstanceExpansion; Expansion nonPublicInstanceExpansion; GetPublicAndNonPublicMembers( instanceMembers, out publicInstanceExpansion, out nonPublicInstanceExpansion); // Public and non-public static members. Expansion publicStaticExpansion; Expansion nonPublicStaticExpansion; GetPublicAndNonPublicMembers( staticMembers, out publicStaticExpansion, out nonPublicStaticExpansion); if (publicInstanceExpansion != null) { expansions.Add(publicInstanceExpansion); } if ((publicStaticExpansion != null) || (nonPublicStaticExpansion != null)) { var staticExpansions = ArrayBuilder<Expansion>.GetInstance(); if (publicStaticExpansion != null) { staticExpansions.Add(publicStaticExpansion); } if (nonPublicStaticExpansion != null) { staticExpansions.Add(nonPublicStaticExpansion); } Debug.Assert(staticExpansions.Count > 0); var staticMembersExpansion = new StaticMembersExpansion( runtimeType, AggregateExpansion.CreateExpansion(staticExpansions)); staticExpansions.Free(); expansions.Add(staticMembersExpansion); } if (nonPublicInstanceExpansion != null) { expansions.Add(nonPublicInstanceExpansion); } // Include Results View if necessary. if ((flags & ExpansionFlags.IncludeResultsView) != 0) { var resultsViewExpansion = ResultsViewExpansion.CreateExpansion(inspectionContext, value, formatter); if (resultsViewExpansion != null) { expansions.Add(resultsViewExpansion); } } var result = AggregateExpansion.CreateExpansion(expansions); expansions.Free(); return result; } private static void GetPublicAndNonPublicMembers( ArrayBuilder<MemberAndDeclarationInfo> allMembers, out Expansion publicExpansion, out Expansion nonPublicExpansion) { var publicExpansions = ArrayBuilder<Expansion>.GetInstance(); var publicMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance(); var nonPublicMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance(); foreach (var member in allMembers) { if (member.BrowsableState.HasValue) { switch (member.BrowsableState.Value) { case DkmClrDebuggerBrowsableAttributeState.RootHidden: if (publicMembers.Count > 0) { publicExpansions.Add(new MemberExpansion(publicMembers.ToArray())); publicMembers.Clear(); } publicExpansions.Add(new RootHiddenExpansion(member)); continue; case DkmClrDebuggerBrowsableAttributeState.Never: continue; } } if (member.HideNonPublic && !member.IsPublic) { nonPublicMembers.Add(member); } else { publicMembers.Add(member); } } if (publicMembers.Count > 0) { publicExpansions.Add(new MemberExpansion(publicMembers.ToArray())); } publicMembers.Free(); publicExpansion = AggregateExpansion.CreateExpansion(publicExpansions); publicExpansions.Free(); nonPublicExpansion = (nonPublicMembers.Count > 0) ? new NonPublicMembersExpansion( declaredType: null, members: new MemberExpansion(nonPublicMembers.ToArray())) : null; nonPublicMembers.Free(); } private readonly MemberAndDeclarationInfo[] _members; private MemberExpansion(MemberAndDeclarationInfo[] members) { Debug.Assert(members != null); Debug.Assert(members.Length > 0); _members = members; } internal override void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResultDataItem> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index) { int startIndex2; int count2; GetIntersection(startIndex, count, index, _members.Length, out startIndex2, out count2); int offset = startIndex2 - index; for (int i = 0; i < count2; i++) { rows.Add(GetMemberRow(resultProvider, inspectionContext, value, _members[i + offset], parent)); } index += _members.Length; } private static EvalResultDataItem GetMemberRow( ResultProvider resultProvider, DkmInspectionContext inspectionContext, DkmClrValue value, MemberAndDeclarationInfo member, EvalResultDataItem parent) { var memberValue = GetMemberValue(value, member, inspectionContext); return CreateMemberDataItem( resultProvider, inspectionContext, member, memberValue, parent, ExpansionFlags.All); } private static DkmClrValue GetMemberValue(DkmClrValue container, MemberAndDeclarationInfo member, DkmInspectionContext inspectionContext) { // Note: GetMemberValue() may return special value // when func-eval of properties is disabled. return container.GetMemberValue(member.Name, (int)member.MemberType, member.DeclaringType.FullName, inspectionContext); } private sealed class RootHiddenExpansion : Expansion { private readonly MemberAndDeclarationInfo _member; internal RootHiddenExpansion(MemberAndDeclarationInfo member) { _member = member; } internal override void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResultDataItem> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index) { var memberValue = GetMemberValue(value, _member, inspectionContext); if (memberValue.IsError()) { if (InRange(startIndex, count, index)) { var row = new EvalResultDataItem(Resources.ErrorName, errorMessage: (string)memberValue.HostObjectValue); rows.Add(row); } index++; } else { parent = CreateMemberDataItem( resultProvider, inspectionContext, _member, memberValue, parent, ExpansionFlags.IncludeBaseMembers | ExpansionFlags.IncludeResultsView); var expansion = parent.Expansion; if (expansion != null) { expansion.GetRows(resultProvider, rows, inspectionContext, parent, parent.Value, startIndex, count, visitAll, ref index); } } } } /// <summary> /// An explicit user request to bypass "Just My Code" and display /// the inaccessible members of an instance of an imported type. /// </summary> private sealed class NonPublicMembersExpansion : Expansion { private readonly Type _declaredType; private readonly Expansion _members; internal NonPublicMembersExpansion(Type declaredType, Expansion members) { _declaredType = declaredType; _members = members; } internal override void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResultDataItem> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index) { if (InRange(startIndex, count, index)) { rows.Add(GetRow( resultProvider, inspectionContext, _declaredType, value, _members, parent)); } index++; } private static readonly ReadOnlyCollection<string> s_hiddenFormatSpecifiers = new ReadOnlyCollection<string>(new[] { "hidden" }); private static EvalResultDataItem GetRow( ResultProvider resultProvider, DkmInspectionContext inspectionContext, Type declaredType, DkmClrValue value, Expansion expansion, EvalResultDataItem parent) { return new EvalResultDataItem( ExpansionKind.NonPublicMembers, name: Resources.NonPublicMembers, typeDeclaringMember: null, declaredType: declaredType, parent: null, value: value, displayValue: null, expansion: expansion, childShouldParenthesize: parent.ChildShouldParenthesize, fullName: parent.FullNameWithoutFormatSpecifiers, childFullNamePrefixOpt: parent.ChildFullNamePrefix, formatSpecifiers: s_hiddenFormatSpecifiers, category: DkmEvaluationResultCategory.Data, flags: DkmEvaluationResultFlags.ReadOnly, editableValue: null, inspectionContext: inspectionContext); } } /// <summary> /// A transition from an instance of a type to the type itself (for inspecting static members). /// </summary> private sealed class StaticMembersExpansion : Expansion { private readonly Type _declaredType; private readonly Expansion _members; internal StaticMembersExpansion(Type declaredType, Expansion members) { _declaredType = declaredType; _members = members; } internal override void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResultDataItem> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index) { if (InRange(startIndex, count, index)) { rows.Add(GetRow( resultProvider, inspectionContext, _declaredType, value, _members)); } index++; } private static EvalResultDataItem GetRow( ResultProvider resultProvider, DkmInspectionContext inspectionContext, Type declaredType, DkmClrValue value, Expansion expansion) { var formatter = resultProvider.Formatter; var fullName = formatter.GetTypeName(declaredType, escapeKeywordIdentifiers: true); return new EvalResultDataItem( ExpansionKind.StaticMembers, name: formatter.StaticMembersString, typeDeclaringMember: null, declaredType: declaredType, parent: null, value: value, displayValue: null, expansion: expansion, childShouldParenthesize: false, fullName: fullName, childFullNamePrefixOpt: fullName, formatSpecifiers: Formatter.NoFormatSpecifiers, category: DkmEvaluationResultCategory.Class, flags: DkmEvaluationResultFlags.ReadOnly, editableValue: null, inspectionContext: inspectionContext); } } private static EvalResultDataItem CreateMemberDataItem( ResultProvider resultProvider, DkmInspectionContext inspectionContext, MemberAndDeclarationInfo member, DkmClrValue memberValue, EvalResultDataItem parent, ExpansionFlags flags) { var formatter = resultProvider.Formatter; string memberName; var typeDeclaringMember = member.GetExplicitlyImplementedInterface(out memberName) ?? member.DeclaringType; memberName = formatter.GetIdentifierEscapingPotentialKeywords(memberName); var fullName = MakeFullName( formatter, memberName, typeDeclaringMember, member.RequiresExplicitCast, member.IsStatic, parent); return resultProvider.CreateDataItem( inspectionContext, memberName, typeDeclaringMember: (member.IncludeTypeInMemberName || typeDeclaringMember.IsInterface) ? typeDeclaringMember : null, declaredType: member.Type, value: memberValue, parent: parent, expansionFlags: flags, childShouldParenthesize: false, fullName: fullName, formatSpecifiers: Formatter.NoFormatSpecifiers, category: DkmEvaluationResultCategory.Other, flags: memberValue.EvalFlags, evalFlags: DkmEvaluationFlags.None); } private static string MakeFullName( Formatter formatter, string name, Type typeDeclaringMember, bool memberAccessRequiresExplicitCast, bool memberIsStatic, EvalResultDataItem parent) { // If the parent is an exception thrown during evaluation, // there is no valid fullname expression for the child. if (parent.Value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown)) { return null; } var parentFullName = parent.ChildFullNamePrefix; if (parentFullName == null) { return null; } if (parent.ChildShouldParenthesize) { parentFullName = $"({parentFullName})"; } if (!typeDeclaringMember.IsInterface) { string qualifier; if (memberIsStatic) { qualifier = formatter.GetTypeName(typeDeclaringMember, escapeKeywordIdentifiers: false); } else if (memberAccessRequiresExplicitCast) { var typeName = formatter.GetTypeName(typeDeclaringMember, escapeKeywordIdentifiers: true); qualifier = formatter.GetCastExpression( parentFullName, typeName, parenthesizeEntireExpression: true); } else { qualifier = parentFullName; } return $"{qualifier}.{name}"; } else { // NOTE: This should never interact with debugger proxy types: // 1) Interfaces cannot have debugger proxy types. // 2) Debugger proxy types cannot be interfaces. if (typeDeclaringMember.Equals(parent.DeclaredType)) { var memberAccessTemplate = parent.ChildShouldParenthesize ? "({0}).{1}" : "{0}.{1}"; return string.Format(memberAccessTemplate, parent.ChildFullNamePrefix, name); } else { var interfaceName = formatter.GetTypeName(typeDeclaringMember, escapeKeywordIdentifiers: true); var memberAccessTemplate = parent.ChildShouldParenthesize ? "(({0})({1})).{2}" : "(({0}){1}).{2}"; return string.Format(memberAccessTemplate, interfaceName, parent.ChildFullNamePrefix, name); } } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Reflection; using System.Security; using System.Text; using Microsoft.PowerShell.Commands; using Microsoft.Win32; using Dbg = System.Management.Automation.Diagnostics; using Regex = System.Text.RegularExpressions.Regex; namespace System.Management.Automation { internal static class RegistryStrings { /// <summary> /// Root key path under HKLM. /// </summary> internal const string MonadRootKeyPath = "Software\\Microsoft\\PowerShell"; /// <summary> /// Root key name. /// </summary> internal const string MonadRootKeyName = "PowerShell"; /// <summary> /// Key for monad engine. /// </summary> internal const string MonadEngineKey = "PowerShellEngine"; // Name for various values under PSEngine internal const string MonadEngine_ApplicationBase = "ApplicationBase"; internal const string MonadEngine_ConsoleHostAssemblyName = "ConsoleHostAssemblyName"; internal const string MonadEngine_ConsoleHostModuleName = "ConsoleHostModuleName"; internal const string MonadEngine_RuntimeVersion = "RuntimeVersion"; internal const string MonadEngine_MonadVersion = "PowerShellVersion"; /// <summary> /// Key under which all the mshsnapin live. /// </summary> internal const string MshSnapinKey = "PowerShellSnapIns"; // Name of various values for each mshsnapin internal const string MshSnapin_ApplicationBase = "ApplicationBase"; internal const string MshSnapin_AssemblyName = "AssemblyName"; internal const string MshSnapin_ModuleName = "ModuleName"; internal const string MshSnapin_MonadVersion = "PowerShellVersion"; internal const string MshSnapin_BuiltInTypes = "Types"; internal const string MshSnapin_BuiltInFormats = "Formats"; internal const string MshSnapin_Description = "Description"; internal const string MshSnapin_Version = "Version"; internal const string MshSnapin_Vendor = "Vendor"; internal const string MshSnapin_DescriptionResource = "DescriptionIndirect"; internal const string MshSnapin_VendorResource = "VendorIndirect"; internal const string MshSnapin_LogPipelineExecutionDetails = "LogPipelineExecutionDetails"; // Name of default mshsnapins internal const string CoreMshSnapinName = "Microsoft.PowerShell.Core"; internal const string HostMshSnapinName = "Microsoft.PowerShell.Host"; internal const string ManagementMshSnapinName = "Microsoft.PowerShell.Management"; internal const string SecurityMshSnapinName = "Microsoft.PowerShell.Security"; internal const string UtilityMshSnapinName = "Microsoft.PowerShell.Utility"; } /// <summary> /// Contains information about a mshsnapin. /// </summary> public class PSSnapInInfo { internal PSSnapInInfo ( string name, bool isDefault, string applicationBase, string assemblyName, string moduleName, Version psVersion, Version version, Collection<string> types, Collection<string> formats, string descriptionFallback, string vendorFallback ) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } if (string.IsNullOrEmpty(applicationBase)) { throw PSTraceSource.NewArgumentNullException(nameof(applicationBase)); } if (string.IsNullOrEmpty(assemblyName)) { throw PSTraceSource.NewArgumentNullException(nameof(assemblyName)); } if (string.IsNullOrEmpty(moduleName)) { throw PSTraceSource.NewArgumentNullException(nameof(moduleName)); } if (psVersion == null) { throw PSTraceSource.NewArgumentNullException(nameof(psVersion)); } if (version == null) { version = new Version("0.0"); } if (types == null) { types = new Collection<string>(); } if (formats == null) { formats = new Collection<string>(); } if (descriptionFallback == null) { descriptionFallback = string.Empty; } if (vendorFallback == null) { vendorFallback = string.Empty; } Name = name; IsDefault = isDefault; ApplicationBase = applicationBase; AssemblyName = assemblyName; ModuleName = moduleName; PSVersion = psVersion; Version = version; Types = types; Formats = formats; _descriptionFallback = descriptionFallback; _vendorFallback = vendorFallback; } internal PSSnapInInfo ( string name, bool isDefault, string applicationBase, string assemblyName, string moduleName, Version psVersion, Version version, Collection<string> types, Collection<string> formats, string description, string descriptionFallback, string vendor, string vendorFallback ) : this(name, isDefault, applicationBase, assemblyName, moduleName, psVersion, version, types, formats, descriptionFallback, vendorFallback) { _description = description; _vendor = vendor; } internal PSSnapInInfo ( string name, bool isDefault, string applicationBase, string assemblyName, string moduleName, Version psVersion, Version version, Collection<string> types, Collection<string> formats, string description, string descriptionFallback, string descriptionIndirect, string vendor, string vendorFallback, string vendorIndirect ) : this(name, isDefault, applicationBase, assemblyName, moduleName, psVersion, version, types, formats, description, descriptionFallback, vendor, vendorFallback) { // add descriptionIndirect and vendorIndirect only if the mshsnapin is a default mshsnapin if (isDefault) { _descriptionIndirect = descriptionIndirect; _vendorIndirect = vendorIndirect; } } /// <summary> /// Unique Name of the mshsnapin. /// </summary> public string Name { get; } /// <summary> /// Is this mshsnapin default mshsnapin. /// </summary> public bool IsDefault { get; } /// <summary> /// Returns applicationbase for mshsnapin. /// </summary> public string ApplicationBase { get; } /// <summary> /// Strong name of mshSnapIn assembly. /// </summary> public string AssemblyName { get; } /// <summary> /// Name of PSSnapIn module. /// </summary> public string ModuleName { get; } internal string AbsoluteModulePath { get { if (string.IsNullOrEmpty(ModuleName) || Path.IsPathRooted(ModuleName)) { return ModuleName; } else if (!File.Exists(Path.Combine(ApplicationBase, ModuleName))) { return Path.GetFileNameWithoutExtension(ModuleName); } return Path.Combine(ApplicationBase, ModuleName); } } /// <summary> /// Monad version used by mshsnapin. /// </summary> public Version PSVersion { get; } /// <summary> /// Version of mshsnapin. /// </summary> public Version Version { get; } /// <summary> /// Collection of file names containing types information for PSSnapIn. /// </summary> public Collection<string> Types { get; } /// <summary> /// Collection of file names containing format information for PSSnapIn. /// </summary> public Collection<string> Formats { get; } private readonly string _descriptionIndirect; private readonly string _descriptionFallback = string.Empty; private string _description; /// <summary> /// Description of mshsnapin. /// </summary> public string Description { get { if (_description == null) { LoadIndirectResources(); } return _description; } } private readonly string _vendorIndirect; private readonly string _vendorFallback = string.Empty; private string _vendor; /// <summary> /// Vendor of mshsnapin. /// </summary> public string Vendor { get { if (_vendor == null) { LoadIndirectResources(); } return _vendor; } } /// <summary> /// Get/set whether to log Pipeline Execution Detail events. /// </summary> public bool LogPipelineExecutionDetails { get; set; } = false; /// <summary> /// Overrides ToString. /// </summary> /// <returns> /// Name of the PSSnapIn /// </returns> public override string ToString() { return Name; } internal RegistryKey MshSnapinKey { get { RegistryKey mshsnapinKey = null; try { mshsnapinKey = PSSnapInReader.GetMshSnapinKey(Name, PSVersion.Major.ToString(CultureInfo.InvariantCulture)); } catch (ArgumentException) { } catch (SecurityException) { } catch (System.IO.IOException) { } return mshsnapinKey; } } internal void LoadIndirectResources() { using (RegistryStringResourceIndirect resourceReader = RegistryStringResourceIndirect.GetResourceIndirectReader()) { LoadIndirectResources(resourceReader); } } internal void LoadIndirectResources(RegistryStringResourceIndirect resourceReader) { if (IsDefault) { // For default mshsnapins..resource indirects are hardcoded.. // so dont read from the registry _description = resourceReader.GetResourceStringIndirect( AssemblyName, ModuleName, _descriptionIndirect); _vendor = resourceReader.GetResourceStringIndirect( AssemblyName, ModuleName, _vendorIndirect); } else { RegistryKey mshsnapinKey = MshSnapinKey; if (mshsnapinKey != null) { _description = resourceReader.GetResourceStringIndirect( mshsnapinKey, RegistryStrings.MshSnapin_DescriptionResource, AssemblyName, ModuleName); _vendor = resourceReader.GetResourceStringIndirect( mshsnapinKey, RegistryStrings.MshSnapin_VendorResource, AssemblyName, ModuleName); } } if (string.IsNullOrEmpty(_description)) { _description = _descriptionFallback; } if (string.IsNullOrEmpty(_vendor)) { _vendor = _vendorFallback; } } internal PSSnapInInfo Clone() { PSSnapInInfo cloned = new PSSnapInInfo( Name, IsDefault, ApplicationBase, AssemblyName, ModuleName, PSVersion, Version, new Collection<string>(Types), new Collection<string>(Formats), _description, _descriptionFallback, _descriptionIndirect, _vendor, _vendorFallback, _vendorIndirect); return cloned; } /// <summary> /// Returns true if the PSSnapIn Id is valid. A PSSnapIn is valid iff it contains only /// "Alpha Numeric","-","_","." characters. /// </summary> /// <param name="psSnapinId">PSSnapIn Id to validate.</param> internal static bool IsPSSnapinIdValid(string psSnapinId) { if (string.IsNullOrEmpty(psSnapinId)) { return false; } return Regex.IsMatch(psSnapinId, "^[A-Za-z0-9-_\x2E]*$"); } /// <summary> /// Validates the PSSnapIn Id. A PSSnapIn is valid iff it contains only /// "Alpha Numeric","-","_","." characters. /// </summary> /// <param name="psSnapinId">PSSnapIn Id to validate.</param> /// <exception cref="PSArgumentException"> /// 1. Specified PSSnapIn is not valid /// </exception> internal static void VerifyPSSnapInFormatThrowIfError(string psSnapinId) { // PSSnapIn do not conform to the naming convention..so throw // argument exception if (!IsPSSnapinIdValid(psSnapinId)) { throw PSTraceSource.NewArgumentException(nameof(psSnapinId), MshSnapInCmdletResources.InvalidPSSnapInName, psSnapinId); } // Valid SnapId..Just return return; } } /// <summary> /// Internal class to read information about a mshsnapin. /// </summary> internal static class PSSnapInReader { /// <summary> /// Reads all registered mshsnapin for all monad versions. /// </summary> /// <returns> /// A collection of PSSnapInInfo objects /// </returns> /// <exception cref="SecurityException"> /// User doesn't have access to monad/mshsnapin registration information /// </exception> /// <exception cref="ArgumentException"> /// Monad key is not installed /// </exception> internal static Collection<PSSnapInInfo> ReadAll() { Collection<PSSnapInInfo> allMshSnapins = new Collection<PSSnapInInfo>(); RegistryKey monadRootKey = GetMonadRootKey(); string[] versions = monadRootKey.GetSubKeyNames(); if (versions == null) { return allMshSnapins; } // PS V3 snapin information is stored under 1 registry key.. // so no need to iterate over twice. Collection<string> filteredVersions = new Collection<string>(); foreach (string version in versions) { string temp = PSVersionInfo.GetRegistryVersionKeyForSnapinDiscovery(version); if (string.IsNullOrEmpty(temp)) { temp = version; } if (!filteredVersions.Contains(temp)) { filteredVersions.Add(temp); } } foreach (string version in filteredVersions) { if (string.IsNullOrEmpty(version)) { continue; } // found a key which is not version if (!MeetsVersionFormat(version)) { continue; } Collection<PSSnapInInfo> oneVersionMshSnapins = null; try { oneVersionMshSnapins = ReadAll(monadRootKey, version); } // If we cannot get information for one version, continue with other // versions catch (SecurityException) { } catch (ArgumentException) { } if (oneVersionMshSnapins != null) { foreach (PSSnapInInfo info in oneVersionMshSnapins) { allMshSnapins.Add(info); } } } return allMshSnapins; } /// <summary> /// Version should be integer (1, 2, 3 etc) /// </summary> /// <param name="version"></param> /// <returns></returns> private static bool MeetsVersionFormat(string version) { bool r = true; try { LanguagePrimitives.ConvertTo(version, typeof(int), CultureInfo.InvariantCulture); } catch (PSInvalidCastException) { r = false; } return r; } /// <summary> /// Reads all registered mshsnapin for specified psVersion. /// </summary> /// <returns> /// A collection of PSSnapInInfo objects /// </returns> /// <exception cref="SecurityException"> /// User doesn't have permission to read MonadRoot or Version /// </exception> /// <exception cref="ArgumentException"> /// MonadRoot or Version key doesn't exist. /// </exception> internal static Collection<PSSnapInInfo> ReadAll(string psVersion) { if (string.IsNullOrEmpty(psVersion)) { throw PSTraceSource.NewArgumentNullException(nameof(psVersion)); } RegistryKey monadRootKey = GetMonadRootKey(); return ReadAll(monadRootKey, psVersion); } /// <summary> /// Reads all the mshsnapins for a given psVersion. /// </summary> /// <exception cref="SecurityException"> /// The User doesn't have required permission to read the registry key for this version. /// </exception> /// <exception cref="ArgumentException"> /// Specified version doesn't exist. /// </exception> /// <exception cref="SecurityException"> /// User doesn't have permission to read specified version /// </exception> private static Collection<PSSnapInInfo> ReadAll(RegistryKey monadRootKey, string psVersion) { Dbg.Assert(monadRootKey != null, "caller should validate the information"); Dbg.Assert(!string.IsNullOrEmpty(psVersion), "caller should validate the information"); Collection<PSSnapInInfo> mshsnapins = new Collection<PSSnapInInfo>(); RegistryKey versionRoot = GetVersionRootKey(monadRootKey, psVersion); RegistryKey mshsnapinRoot = GetMshSnapinRootKey(versionRoot, psVersion); // get name of all mshsnapin for this version string[] mshsnapinIds = mshsnapinRoot.GetSubKeyNames(); foreach (string id in mshsnapinIds) { if (string.IsNullOrEmpty(id)) { continue; } try { mshsnapins.Add(ReadOne(mshsnapinRoot, id)); } // If we cannot read some mshsnapins, we should continue catch (SecurityException) { } catch (ArgumentException) { } } return mshsnapins; } /// <summary> /// Read mshsnapin for specified mshsnapinId and psVersion. /// </summary> /// <returns> /// MshSnapin info object /// </returns> /// <exception cref="SecurityException"> /// The user does not have the permissions required to read the /// registry key for one of the following: /// 1) Monad /// 2) PSVersion /// 3) MshSnapinId /// </exception> /// <exception cref="ArgumentException"> /// 1) Monad key is not present /// 2) VersionKey is not present /// 3) MshSnapin key is not present /// 4) MshSnapin key is not valid /// </exception> internal static PSSnapInInfo Read(string psVersion, string mshsnapinId) { if (string.IsNullOrEmpty(psVersion)) { throw PSTraceSource.NewArgumentNullException(nameof(psVersion)); } if (string.IsNullOrEmpty(mshsnapinId)) { throw PSTraceSource.NewArgumentNullException(nameof(mshsnapinId)); } // PSSnapIn Reader wont service invalid mshsnapins // Monad has specific restrictions on the mshsnapinid like // mshsnapinid should be A-Za-z0-9.-_ etc. PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(mshsnapinId); RegistryKey rootKey = GetMonadRootKey(); RegistryKey versionRoot = GetVersionRootKey(rootKey, psVersion); RegistryKey mshsnapinRoot = GetMshSnapinRootKey(versionRoot, psVersion); return ReadOne(mshsnapinRoot, mshsnapinId); } /// <summary> /// Reads the mshsnapin info for a specific key under specific monad version. /// </summary> /// <remarks> /// ReadOne will never create a default PSSnapInInfo object. /// </remarks> /// <exception cref="SecurityException"> /// The user does not have the permissions required to read the /// registry key for specified mshsnapin. /// </exception> /// <exception cref="ArgumentException"> /// 1) Specified mshsnapin is not installed. /// 2) Specified mshsnapin is not correctly installed. /// </exception> private static PSSnapInInfo ReadOne(RegistryKey mshSnapInRoot, string mshsnapinId) { Dbg.Assert(!string.IsNullOrEmpty(mshsnapinId), "caller should validate the parameter"); Dbg.Assert(mshSnapInRoot != null, "caller should validate the parameter"); RegistryKey mshsnapinKey; mshsnapinKey = mshSnapInRoot.OpenSubKey(mshsnapinId); if (mshsnapinKey == null) { s_mshsnapinTracer.TraceError("Error opening registry key {0}\\{1}.", mshSnapInRoot.Name, mshsnapinId); throw PSTraceSource.NewArgumentException(nameof(mshsnapinId), MshSnapinInfo.MshSnapinDoesNotExist, mshsnapinId); } string applicationBase = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_ApplicationBase, true); string assemblyName = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_AssemblyName, true); string moduleName = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_ModuleName, true); Version monadVersion = ReadVersionValue(mshsnapinKey, RegistryStrings.MshSnapin_MonadVersion, true); Version version = ReadVersionValue(mshsnapinKey, RegistryStrings.MshSnapin_Version, false); string description = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_Description, false); if (description == null) { s_mshsnapinTracer.WriteLine("No description is specified for mshsnapin {0}. Using empty string for description.", mshsnapinId); description = string.Empty; } string vendor = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_Vendor, false); if (vendor == null) { s_mshsnapinTracer.WriteLine("No vendor is specified for mshsnapin {0}. Using empty string for description.", mshsnapinId); vendor = string.Empty; } bool logPipelineExecutionDetails = false; string logPipelineExecutionDetailsStr = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_LogPipelineExecutionDetails, false); if (!string.IsNullOrEmpty(logPipelineExecutionDetailsStr)) { if (string.Equals("1", logPipelineExecutionDetailsStr, StringComparison.OrdinalIgnoreCase)) logPipelineExecutionDetails = true; } Collection<string> types = ReadMultiStringValue(mshsnapinKey, RegistryStrings.MshSnapin_BuiltInTypes, false); Collection<string> formats = ReadMultiStringValue(mshsnapinKey, RegistryStrings.MshSnapin_BuiltInFormats, false); s_mshsnapinTracer.WriteLine("Successfully read registry values for mshsnapin {0}. Constructing PSSnapInInfo object.", mshsnapinId); PSSnapInInfo mshSnapinInfo = new PSSnapInInfo(mshsnapinId, false, applicationBase, assemblyName, moduleName, monadVersion, version, types, formats, description, vendor); mshSnapinInfo.LogPipelineExecutionDetails = logPipelineExecutionDetails; return mshSnapinInfo; } /// <summary> /// Gets multistring value for name. /// </summary> /// <param name="mshsnapinKey"></param> /// <param name="name"></param> /// <param name="mandatory"></param> /// <returns></returns> /// <exception cref="ArgumentException"> /// if value is not present and mandatory is true /// </exception> private static Collection<string> ReadMultiStringValue(RegistryKey mshsnapinKey, string name, bool mandatory) { object value = mshsnapinKey.GetValue(name); if (value == null) { // If this key should be present..throw error if (mandatory) { s_mshsnapinTracer.TraceError("Mandatory property {0} not specified for registry key {1}", name, mshsnapinKey.Name); throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.MandatoryValueNotPresent, name, mshsnapinKey.Name); } else { return null; } } // value cannot be null here... string[] msv = value as string[]; if (msv == null) { // Check if the value is in string format string singleValue = value as string; if (singleValue != null) { msv = new string[1]; msv[0] = singleValue; } } if (msv == null) { if (mandatory) { s_mshsnapinTracer.TraceError("Cannot get string/multi-string value for mandatory property {0} in registry key {1}", name, mshsnapinKey.Name); throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.MandatoryValueNotInCorrectFormatMultiString, name, mshsnapinKey.Name); } else { return null; } } s_mshsnapinTracer.WriteLine("Successfully read property {0} from {1}", name, mshsnapinKey.Name); return new Collection<string>(msv); } /// <summary> /// Get the value for name. /// </summary> /// <param name="mshsnapinKey"></param> /// <param name="name"></param> /// <param name="mandatory"></param> /// <returns></returns> /// <exception cref="ArgumentException"> /// if no value is available and mandatory is true. /// </exception> internal static string ReadStringValue(RegistryKey mshsnapinKey, string name, bool mandatory) { Dbg.Assert(!string.IsNullOrEmpty(name), "caller should validate the parameter"); Dbg.Assert(mshsnapinKey != null, "Caller should validate the parameter"); object value = mshsnapinKey.GetValue(name); if (value == null && mandatory) { s_mshsnapinTracer.TraceError("Mandatory property {0} not specified for registry key {1}", name, mshsnapinKey.Name); throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.MandatoryValueNotPresent, name, mshsnapinKey.Name); } string s = value as string; if (string.IsNullOrEmpty(s) && mandatory) { s_mshsnapinTracer.TraceError("Value is null or empty for mandatory property {0} in {1}", name, mshsnapinKey.Name); throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.MandatoryValueNotInCorrectFormat, name, mshsnapinKey.Name); } s_mshsnapinTracer.WriteLine("Successfully read value {0} for property {1} from {2}", s, name, mshsnapinKey.Name); return s; } internal static Version ReadVersionValue(RegistryKey mshsnapinKey, string name, bool mandatory) { string temp = ReadStringValue(mshsnapinKey, name, mandatory); if (temp == null) { s_mshsnapinTracer.TraceError("Cannot read value for property {0} in registry key {1}", name, mshsnapinKey.ToString()); Dbg.Assert(!mandatory, "mandatory is true, ReadStringValue should have thrown exception"); return null; } Version v; try { v = new Version(temp); } catch (ArgumentOutOfRangeException) { s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } catch (ArgumentException) { s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } catch (OverflowException) { s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } catch (FormatException) { s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } s_mshsnapinTracer.WriteLine("Successfully converted string {0} to version format.", v); return v; } internal static void ReadRegistryInfo(out Version assemblyVersion, out string publicKeyToken, out string culture, out string architecture, out string applicationBase, out Version psVersion) { applicationBase = Utils.DefaultPowerShellAppBase; Dbg.Assert( !string.IsNullOrEmpty(applicationBase), string.Format(CultureInfo.CurrentCulture, "{0} is empty or null", RegistryStrings.MonadEngine_ApplicationBase)); // Get the PSVersion from Utils..this is hardcoded psVersion = PSVersionInfo.PSVersion; Dbg.Assert( psVersion != null, string.Format(CultureInfo.CurrentCulture, "{0} is null", RegistryStrings.MonadEngine_MonadVersion)); // Get version number in x.x.x.x format // This information is available from the executing assembly // // PROBLEM: The following code assumes all assemblies have the same version, // culture, publickeytoken...This will break the scenarios where only one of // the assemblies is patched. ie., all monad assemblies should have the // same version number. Assembly currentAssembly = typeof(PSSnapInReader).Assembly; AssemblyName assemblyName = currentAssembly.GetName(); assemblyVersion = assemblyName.Version; byte[] publicTokens = assemblyName.GetPublicKeyToken(); if (publicTokens.Length == 0) { throw PSTraceSource.NewArgumentException("PublicKeyToken", MshSnapinInfo.PublicKeyTokenAccessFailed); } publicKeyToken = ConvertByteArrayToString(publicTokens); // save some cpu cycles by hardcoding the culture to neutral // assembly should never be targeted to a particular culture culture = "neutral"; // Hardcoding the architecture MSIL as PowerShell assemblies are architecture neutral, this should // be changed if the assumption is broken. Preferred hardcoded string to using (for perf reasons): // string architecture = currentAssembly.GetName().ProcessorArchitecture.ToString() architecture = "MSIL"; } /// <summary> /// PublicKeyToken is in the form of byte[]. Use this function to convert to a string. /// </summary> /// <param name="tokens">Array of byte's.</param> /// <returns></returns> internal static string ConvertByteArrayToString(byte[] tokens) { Dbg.Assert(tokens != null, "Input tokens should never be null"); StringBuilder tokenBuilder = new StringBuilder(tokens.Length * 2); foreach (byte b in tokens) { tokenBuilder.Append(b.ToString("x2", CultureInfo.InvariantCulture)); } return tokenBuilder.ToString(); } /// <summary> /// Reads core snapin for monad engine. /// </summary> /// <returns> /// A PSSnapInInfo object /// </returns> internal static PSSnapInInfo ReadCoreEngineSnapIn() { Version assemblyVersion, psVersion; string publicKeyToken = null; string culture = null; string architecture = null; string applicationBase = null; ReadRegistryInfo(out assemblyVersion, out publicKeyToken, out culture, out architecture, out applicationBase, out psVersion); // System.Management.Automation formats & types files Collection<string> types = new Collection<string>(new string[] { "types.ps1xml", "typesv3.ps1xml" }); Collection<string> formats = new Collection<string>(new string[] {"Certificate.format.ps1xml", "DotNetTypes.format.ps1xml", "FileSystem.format.ps1xml", "Help.format.ps1xml", "HelpV3.format.ps1xml", "PowerShellCore.format.ps1xml", "PowerShellTrace.format.ps1xml", "Registry.format.ps1xml"}); string strongName = string.Format(CultureInfo.InvariantCulture, "{0}, Version={1}, Culture={2}, PublicKeyToken={3}, ProcessorArchitecture={4}", s_coreSnapin.AssemblyName, assemblyVersion, culture, publicKeyToken, architecture); string moduleName = Path.Combine(applicationBase, s_coreSnapin.AssemblyName + ".dll"); PSSnapInInfo coreMshSnapin = new PSSnapInInfo( s_coreSnapin.PSSnapInName, isDefault: true, applicationBase, strongName, moduleName, psVersion, assemblyVersion, types, formats, description: null, s_coreSnapin.Description, s_coreSnapin.DescriptionIndirect, vendor: null, vendorFallback: null, s_coreSnapin.VendorIndirect); #if !UNIX // NOTE: On Unix, logging has to be deferred until after command-line parsing // complete. On Windows, deferring the call is not needed // and this is in the startup code path. SetSnapInLoggingInformation(coreMshSnapin); #endif return coreMshSnapin; } /// <summary> /// Reads all registered mshsnapins for currently executing monad engine. /// </summary> /// <returns> /// A collection of PSSnapInInfo objects /// </returns> internal static Collection<PSSnapInInfo> ReadEnginePSSnapIns() { Version assemblyVersion, psVersion; string publicKeyToken = null; string culture = null; string architecture = null; string applicationBase = null; ReadRegistryInfo(out assemblyVersion, out publicKeyToken, out culture, out architecture, out applicationBase, out psVersion); // System.Management.Automation formats & types files Collection<string> smaFormats = new Collection<string>(new string[] {"Certificate.format.ps1xml", "DotNetTypes.format.ps1xml", "FileSystem.format.ps1xml", "Help.format.ps1xml", "HelpV3.format.ps1xml", "PowerShellCore.format.ps1xml", "PowerShellTrace.format.ps1xml", "Registry.format.ps1xml"}); Collection<string> smaTypes = new Collection<string>(new string[] { "types.ps1xml", "typesv3.ps1xml" }); // create default mshsnapininfo objects.. Collection<PSSnapInInfo> engineMshSnapins = new Collection<PSSnapInInfo>(); string assemblyVersionString = assemblyVersion.ToString(); for (int item = 0; item < DefaultMshSnapins.Count; item++) { DefaultPSSnapInInformation defaultMshSnapinInfo = DefaultMshSnapins[item]; string strongName = string.Format( CultureInfo.InvariantCulture, "{0}, Version={1}, Culture={2}, PublicKeyToken={3}, ProcessorArchitecture={4}", defaultMshSnapinInfo.AssemblyName, assemblyVersionString, culture, publicKeyToken, architecture); Collection<string> formats = null; Collection<string> types = null; if (defaultMshSnapinInfo.AssemblyName.Equals("System.Management.Automation", StringComparison.OrdinalIgnoreCase)) { formats = smaFormats; types = smaTypes; } else if (defaultMshSnapinInfo.AssemblyName.Equals("Microsoft.PowerShell.Commands.Diagnostics", StringComparison.OrdinalIgnoreCase)) { types = new Collection<string>(new string[] { "GetEvent.types.ps1xml" }); formats = new Collection<string>(new string[] { "Event.format.ps1xml", "Diagnostics.format.ps1xml" }); } else if (defaultMshSnapinInfo.AssemblyName.Equals("Microsoft.WSMan.Management", StringComparison.OrdinalIgnoreCase)) { formats = new Collection<string>(new string[] { "WSMan.format.ps1xml" }); } string moduleName = Path.Combine(applicationBase, defaultMshSnapinInfo.AssemblyName + ".dll"); PSSnapInInfo defaultMshSnapin = new PSSnapInInfo( defaultMshSnapinInfo.PSSnapInName, isDefault: true, applicationBase, strongName, moduleName, psVersion, assemblyVersion, types, formats, description: null, defaultMshSnapinInfo.Description, defaultMshSnapinInfo.DescriptionIndirect, vendor: null, vendorFallback: null, defaultMshSnapinInfo.VendorIndirect); SetSnapInLoggingInformation(defaultMshSnapin); engineMshSnapins.Add(defaultMshSnapin); } return engineMshSnapins; } /// <summary> /// Enable Snapin logging based on group policy. /// </summary> private static void SetSnapInLoggingInformation(PSSnapInInfo psSnapInInfo) { IEnumerable<string> names; ModuleCmdletBase.ModuleLoggingGroupPolicyStatus status = ModuleCmdletBase.GetModuleLoggingInformation(out names); if (status != ModuleCmdletBase.ModuleLoggingGroupPolicyStatus.Undefined) { SetSnapInLoggingInformation(psSnapInInfo, status, names); } } /// <summary> /// Enable Snapin logging based on group policy. /// </summary> private static void SetSnapInLoggingInformation(PSSnapInInfo psSnapInInfo, ModuleCmdletBase.ModuleLoggingGroupPolicyStatus status, IEnumerable<string> moduleOrSnapinNames) { if (((status & ModuleCmdletBase.ModuleLoggingGroupPolicyStatus.Enabled) != 0) && moduleOrSnapinNames != null) { foreach (string currentGPModuleOrSnapinName in moduleOrSnapinNames) { if (string.Equals(psSnapInInfo.Name, currentGPModuleOrSnapinName, StringComparison.OrdinalIgnoreCase)) { psSnapInInfo.LogPipelineExecutionDetails = true; } else if (WildcardPattern.ContainsWildcardCharacters(currentGPModuleOrSnapinName)) { WildcardPattern wildcard = WildcardPattern.Get(currentGPModuleOrSnapinName, WildcardOptions.IgnoreCase); if (wildcard.IsMatch(psSnapInInfo.Name)) { psSnapInInfo.LogPipelineExecutionDetails = true; } } } } } /// <summary> /// Get the key to monad root. /// </summary> /// <returns></returns> /// <exception cref="SecurityException"> /// Caller doesn't have access to monad registration information. /// </exception> /// <exception cref="ArgumentException"> /// Monad registration information is not available. /// </exception> internal static RegistryKey GetMonadRootKey() { RegistryKey rootKey = Registry.LocalMachine.OpenSubKey(RegistryStrings.MonadRootKeyPath); if (rootKey == null) { // This should never occur because this code is running // because monad is installed. { well this can occur if someone // deletes the registry key after starting monad Dbg.Assert(false, "Root Key of Monad installation is not present"); throw PSTraceSource.NewArgumentException("monad", MshSnapinInfo.MonadRootRegistryAccessFailed); } return rootKey; } /// <summary> /// Get the registry key to PSEngine. /// </summary> /// <returns>RegistryKey.</returns> /// <param name="psVersion">Major version in string format.</param> /// <exception cref="ArgumentException"> /// Monad registration information is not available. /// </exception> internal static RegistryKey GetPSEngineKey(string psVersion) { RegistryKey rootKey = GetMonadRootKey(); // root key wont be null Dbg.Assert(rootKey != null, "Root Key of Monad installation is not present"); RegistryKey versionRootKey = GetVersionRootKey(rootKey, psVersion); // version root key wont be null Dbg.Assert(versionRootKey != null, "Version Rootkey of Monad installation is not present"); RegistryKey psEngineParentKey = rootKey.OpenSubKey(psVersion); if (psEngineParentKey == null) { throw PSTraceSource.NewArgumentException("monad", MshSnapinInfo.MonadEngineRegistryAccessFailed); } RegistryKey psEngineKey = psEngineParentKey.OpenSubKey(RegistryStrings.MonadEngineKey); if (psEngineKey == null) { throw PSTraceSource.NewArgumentException("monad", MshSnapinInfo.MonadEngineRegistryAccessFailed); } return psEngineKey; } /// <summary> /// Gets the version root key for specified monad version. /// </summary> /// <param name="rootKey"></param> /// <param name="psVersion"></param> /// <returns></returns> /// <exception cref="SecurityException"> /// Caller doesn't have permission to read the version key /// </exception> /// <exception cref="ArgumentException"> /// specified psVersion key is not present /// </exception> internal static RegistryKey GetVersionRootKey(RegistryKey rootKey, string psVersion) { Dbg.Assert(!string.IsNullOrEmpty(psVersion), "caller should validate the parameter"); Dbg.Assert(rootKey != null, "caller should validate the parameter"); string versionKey = PSVersionInfo.GetRegistryVersionKeyForSnapinDiscovery(psVersion); RegistryKey versionRoot = rootKey.OpenSubKey(versionKey); if (versionRoot == null) { throw PSTraceSource.NewArgumentException(nameof(psVersion), MshSnapinInfo.SpecifiedVersionNotFound, versionKey); } return versionRoot; } /// <summary> /// Gets the mshsnapin root key for specified monad version. /// </summary> /// <param name="versionRootKey"></param> /// <param name="psVersion"></param> /// <returns></returns> /// <exception cref="SecurityException"> /// Caller doesn't have permission to read the mshsnapin key /// </exception> /// <exception cref="ArgumentException"> /// mshsnapin key is not present /// </exception> private static RegistryKey GetMshSnapinRootKey(RegistryKey versionRootKey, string psVersion) { Dbg.Assert(versionRootKey != null, "caller should validate the parameter"); RegistryKey mshsnapinRoot = versionRootKey.OpenSubKey(RegistryStrings.MshSnapinKey); if (mshsnapinRoot == null) { throw PSTraceSource.NewArgumentException(nameof(psVersion), MshSnapinInfo.NoMshSnapinPresentForVersion, psVersion); } return mshsnapinRoot; } /// <summary> /// Gets the mshsnapin key for specified monad version and mshsnapin name. /// </summary> /// <param name="mshSnapInName"></param> /// <param name="psVersion"></param> /// <returns></returns> /// <exception cref="SecurityException"> /// Caller doesn't have permission to read the mshsnapin key /// </exception> /// <exception cref="ArgumentException"> /// mshsnapin key is not present /// </exception> internal static RegistryKey GetMshSnapinKey(string mshSnapInName, string psVersion) { RegistryKey monadRootKey = GetMonadRootKey(); RegistryKey versionRootKey = GetVersionRootKey(monadRootKey, psVersion); RegistryKey mshsnapinRoot = versionRootKey.OpenSubKey(RegistryStrings.MshSnapinKey); if (mshsnapinRoot == null) { throw PSTraceSource.NewArgumentException(nameof(psVersion), MshSnapinInfo.NoMshSnapinPresentForVersion, psVersion); } RegistryKey mshsnapinKey = mshsnapinRoot.OpenSubKey(mshSnapInName); return mshsnapinKey; } #region Default MshSnapins related structure /// <summary> /// This structure is meant to hold mshsnapin information for default mshsnapins. /// This is private only. /// </summary> private struct DefaultPSSnapInInformation { // since this is a private structure..making it as simple as possible public string PSSnapInName; public string AssemblyName; public string Description; public string DescriptionIndirect; public string VendorIndirect; public DefaultPSSnapInInformation(string sName, string sAssemblyName, string sDescription, string sDescriptionIndirect, string sVendorIndirect) { PSSnapInName = sName; AssemblyName = sAssemblyName; Description = sDescription; DescriptionIndirect = sDescriptionIndirect; VendorIndirect = sVendorIndirect; } } private static DefaultPSSnapInInformation s_coreSnapin = new DefaultPSSnapInInformation("Microsoft.PowerShell.Core", "System.Management.Automation", null, "CoreMshSnapInResources,Description", "CoreMshSnapInResources,Vendor"); /// <summary> /// </summary> private static IList<DefaultPSSnapInInformation> DefaultMshSnapins { get { if (s_defaultMshSnapins == null) { lock (s_syncObject) { if (s_defaultMshSnapins == null) { s_defaultMshSnapins = new List<DefaultPSSnapInInformation>() { #if !UNIX new DefaultPSSnapInInformation("Microsoft.PowerShell.Diagnostics", "Microsoft.PowerShell.Commands.Diagnostics", null, "GetEventResources,Description", "GetEventResources,Vendor"), #endif new DefaultPSSnapInInformation("Microsoft.PowerShell.Host", "Microsoft.PowerShell.ConsoleHost", null, "HostMshSnapInResources,Description", "HostMshSnapInResources,Vendor"), s_coreSnapin, new DefaultPSSnapInInformation("Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Commands.Utility", null, "UtilityMshSnapInResources,Description", "UtilityMshSnapInResources,Vendor"), new DefaultPSSnapInInformation("Microsoft.PowerShell.Management", "Microsoft.PowerShell.Commands.Management", null, "ManagementMshSnapInResources,Description", "ManagementMshSnapInResources,Vendor"), new DefaultPSSnapInInformation("Microsoft.PowerShell.Security", "Microsoft.PowerShell.Security", null, "SecurityMshSnapInResources,Description", "SecurityMshSnapInResources,Vendor") }; #if !UNIX if (!Utils.IsWinPEHost()) { s_defaultMshSnapins.Add(new DefaultPSSnapInInformation("Microsoft.WSMan.Management", "Microsoft.WSMan.Management", null, "WsManResources,Description", "WsManResources,Vendor")); } #endif } } } return s_defaultMshSnapins; } } private static IList<DefaultPSSnapInInformation> s_defaultMshSnapins = null; private static readonly object s_syncObject = new object(); #endregion private static readonly PSTraceSource s_mshsnapinTracer = PSTraceSource.GetTracer("MshSnapinLoadUnload", "Loading and unloading mshsnapins", false); } }
using UnityEngine; namespace UnitySampleAssets.ImageEffects { [ExecuteInEditMode] [RequireComponent(typeof (Camera))] [AddComponentMenu("Image Effects/Tonemapping")] public class Tonemapping : PostEffectsBase { public enum TonemapperType { SimpleReinhard, UserCurve, Hable, Photographic, OptimizedHejiDawson, AdaptiveReinhard, AdaptiveReinhardAutoWhite, }; public enum AdaptiveTexSize { Square16 = 16, Square32 = 32, Square64 = 64, Square128 = 128, Square256 = 256, Square512 = 512, Square1024 = 1024, }; public TonemapperType type = TonemapperType.Photographic; public AdaptiveTexSize adaptiveTextureSize = AdaptiveTexSize.Square256; // CURVE parameter public AnimationCurve remapCurve; private Texture2D curveTex = null; // UNCHARTED parameter public float exposureAdjustment = 1.5f; // REINHARD parameter public float middleGrey = 0.4f; public float white = 2.0f; public float adaptionSpeed = 1.5f; // usual & internal stuff public Shader tonemapper = null; public bool validRenderTextureFormat = true; private Material tonemapMaterial = null; private RenderTexture rt = null; private RenderTextureFormat rtFormat = RenderTextureFormat.ARGBHalf; protected override bool CheckResources() { CheckSupport(false, true); tonemapMaterial = CheckShaderAndCreateMaterial(tonemapper, tonemapMaterial); if (!curveTex && type == TonemapperType.UserCurve) { curveTex = new Texture2D(256, 1, TextureFormat.ARGB32, false, true); curveTex.filterMode = FilterMode.Bilinear; curveTex.wrapMode = TextureWrapMode.Clamp; curveTex.hideFlags = HideFlags.DontSave; } if (!isSupported) ReportAutoDisable(); return isSupported; } public float UpdateCurve() { float range = 1.0f; if (remapCurve.keys.Length < 1) remapCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(2, 1)); if (remapCurve != null) { if (remapCurve.length != 0) range = remapCurve[remapCurve.length - 1].time; for (float i = 0.0f; i <= 1.0f; i += 1.0f/255.0f) { float c = remapCurve.Evaluate(i*1.0f*range); curveTex.SetPixel((int) Mathf.Floor(i*255.0f), 0, new Color(c, c, c)); } curveTex.Apply(); } return 1.0f/range; } private void OnDisable() { if (rt) { DestroyImmediate(rt); rt = null; } if (tonemapMaterial) { DestroyImmediate(tonemapMaterial); tonemapMaterial = null; } if (curveTex) { DestroyImmediate(curveTex); curveTex = null; } } private bool CreateInternalRenderTexture() { if (rt) { return false; } rtFormat = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RGHalf) ? RenderTextureFormat.RGHalf : RenderTextureFormat.ARGBHalf; rt = new RenderTexture(1, 1, 0, rtFormat); rt.hideFlags = HideFlags.DontSave; return true; } // a new attribute we introduced in 3.5 indicating that the image filter chain will continue in LDR [ImageEffectTransformsToLDR] private void OnRenderImage(RenderTexture source, RenderTexture destination) { if (CheckResources() == false) { Graphics.Blit(source, destination); return; } #if UNITY_EDITOR validRenderTextureFormat = true; if (source.format != RenderTextureFormat.ARGBHalf) { validRenderTextureFormat = false; } #endif // clamp some values to not go out of a valid range exposureAdjustment = exposureAdjustment < 0.001f ? 0.001f : exposureAdjustment; // SimpleReinhard tonemappers (local, non adaptive) if (type == TonemapperType.UserCurve) { float rangeScale = UpdateCurve(); tonemapMaterial.SetFloat("_RangeScale", rangeScale); tonemapMaterial.SetTexture("_Curve", curveTex); Graphics.Blit(source, destination, tonemapMaterial, 4); return; } if (type == TonemapperType.SimpleReinhard) { tonemapMaterial.SetFloat("_ExposureAdjustment", exposureAdjustment); Graphics.Blit(source, destination, tonemapMaterial, 6); return; } if (type == TonemapperType.Hable) { tonemapMaterial.SetFloat("_ExposureAdjustment", exposureAdjustment); Graphics.Blit(source, destination, tonemapMaterial, 5); return; } if (type == TonemapperType.Photographic) { tonemapMaterial.SetFloat("_ExposureAdjustment", exposureAdjustment); Graphics.Blit(source, destination, tonemapMaterial, 8); return; } if (type == TonemapperType.OptimizedHejiDawson) { tonemapMaterial.SetFloat("_ExposureAdjustment", 0.5f*exposureAdjustment); Graphics.Blit(source, destination, tonemapMaterial, 7); return; } // still here? // => adaptive tone mapping: // builds an average log luminance, tonemaps according to // middle grey and white values (user controlled) // AdaptiveReinhardAutoWhite will calculate white value automagically bool freshlyBrewedInternalRt = CreateInternalRenderTexture(); // this retrieves rtFormat, so should happen before rt allocations RenderTexture rtSquared = RenderTexture.GetTemporary((int) adaptiveTextureSize, (int) adaptiveTextureSize, 0, rtFormat); Graphics.Blit(source, rtSquared); int downsample = (int) Mathf.Log(rtSquared.width*1.0f, 2); int div = 2; RenderTexture[] rts = new RenderTexture[downsample]; for (int i = 0; i < downsample; i++) { rts[i] = RenderTexture.GetTemporary(rtSquared.width/div, rtSquared.width/div, 0, rtFormat); div *= 2; } //float ar = (source.width*1.0f)/(source.height*1.0f); // downsample pyramid var lumRt = rts[downsample - 1]; Graphics.Blit(rtSquared, rts[0], tonemapMaterial, 1); if (type == TonemapperType.AdaptiveReinhardAutoWhite) { for (int i = 0; i < downsample - 1; i++) { Graphics.Blit(rts[i], rts[i + 1], tonemapMaterial, 9); lumRt = rts[i + 1]; } } else if (type == TonemapperType.AdaptiveReinhard) { for (int i = 0; i < downsample - 1; i++) { Graphics.Blit(rts[i], rts[i + 1]); lumRt = rts[i + 1]; } } // we have the needed values, let's apply adaptive tonemapping adaptionSpeed = adaptionSpeed < 0.001f ? 0.001f : adaptionSpeed; tonemapMaterial.SetFloat("_AdaptionSpeed", adaptionSpeed); #if UNITY_EDITOR if (Application.isPlaying && !freshlyBrewedInternalRt) Graphics.Blit(lumRt, rt, tonemapMaterial, 2); else Graphics.Blit(lumRt, rt, tonemapMaterial, 3); #else Graphics.Blit (lumRt, rt, tonemapMaterial, freshlyBrewedInternalRt ? 3 : 2); #endif middleGrey = middleGrey < 0.001f ? 0.001f : middleGrey; tonemapMaterial.SetVector("_HdrParams", new Vector4(middleGrey, middleGrey, middleGrey, white*white)); tonemapMaterial.SetTexture("_SmallTex", rt); if (type == TonemapperType.AdaptiveReinhard) { Graphics.Blit(source, destination, tonemapMaterial, 0); } else if (type == TonemapperType.AdaptiveReinhardAutoWhite) { Graphics.Blit(source, destination, tonemapMaterial, 10); } else { Debug.LogError("No valid adaptive tonemapper type found!"); Graphics.Blit(source, destination); // at least we get the TransformToLDR effect } // cleanup for adaptive for (int i = 0; i < downsample; i++) { RenderTexture.ReleaseTemporary(rts[i]); } RenderTexture.ReleaseTemporary(rtSquared); } } }
using System; using UnityEngine; namespace InControl { public class InputControl { public static readonly InputControl Null = new InputControl( "NullInputControl" ); public string Handle { get; protected set; } public InputControlType Target { get; protected set; } public ulong UpdateTick { get; protected set; } public float Sensitivity = 1.0f; public float LowerDeadZone = 0.0f; public float UpperDeadZone = 1.0f; public bool IsButton { get; protected set; } InputControlState thisState; InputControlState lastState; InputControlState tempState; ulong zeroTick; private InputControl( string handle ) { Handle = handle; } public InputControl( string handle, InputControlType target ) { Handle = handle; Target = target; IsButton = (target >= InputControlType.Action1 && target <= InputControlType.Action4) || (target >= InputControlType.Button0 && target <= InputControlType.Button19); } public void UpdateWithState( bool state, ulong updateTick ) { if (IsNull) { throw new InvalidOperationException( "A null control cannot be updated." ); } if (UpdateTick > updateTick) { throw new InvalidOperationException( "A control cannot be updated with an earlier tick." ); } tempState.Set( state || tempState.State ); } public void UpdateWithValue( float value, ulong updateTick ) { if (IsNull) { throw new InvalidOperationException( "A null control cannot be updated." ); } if (UpdateTick > updateTick) { throw new InvalidOperationException( "A control cannot be updated with an earlier tick." ); } if (Mathf.Abs( value ) > Mathf.Abs( tempState.Value )) { tempState.Set( value ); } } internal void PreUpdate( ulong updateTick ) { RawValue = null; PreValue = null; lastState = thisState; tempState.Reset(); } internal void PostUpdate( ulong updateTick ) { thisState = tempState; if (thisState != lastState) { UpdateTick = updateTick; } } internal void SetZeroTick() { zeroTick = UpdateTick; } internal bool IsOnZeroTick { get { return UpdateTick == zeroTick; } } public bool State { get { return thisState.State; } } public bool LastState { get { return lastState.State; } } public float Value { get { return thisState.Value; } } public float LastValue { get { return lastState.Value; } } public bool HasChanged { get { return thisState != lastState; } } public bool IsPressed { get { return thisState.State; } } public bool WasPressed { get { return thisState && !lastState; } } public bool WasReleased { get { return !thisState && lastState; } } public bool IsNull { get { return this == Null; } } public bool IsNotNull { get { return this != Null; } } public override string ToString() { return string.Format( "[InputControl: Handle={0}, Value={1}]", Handle, Value ); } public static implicit operator bool( InputControl control ) { return control.State; } public static implicit operator float( InputControl control ) { return control.Value; } public InputControlType? Obverse { get { switch (Target) { case InputControlType.LeftStickX: return InputControlType.LeftStickY; case InputControlType.LeftStickY: return InputControlType.LeftStickX; case InputControlType.RightStickX: return InputControlType.RightStickY; case InputControlType.RightStickY: return InputControlType.RightStickX; default: return null; } } } // This is for internal use only and is not always set. internal float? RawValue; internal float? PreValue; } }
using System; using System.Collections.Generic; using System.Globalization; using System.Runtime.CompilerServices; using System.Xml; using System.Xml.XPath; using Umbraco.Core.Configuration; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Xml; using Umbraco.Web.Routing; using umbraco; using System.Linq; using umbraco.BusinessLogic; using umbraco.presentation.preview; using Umbraco.Core.Services; using GlobalSettings = umbraco.GlobalSettings; namespace Umbraco.Web.PublishedCache.XmlPublishedCache { internal class PublishedContentCache : IPublishedContentCache { #region Routes cache private readonly RoutesCache _routesCache = new RoutesCache(!UnitTesting); private DomainHelper _domainHelper; private DomainHelper GetDomainHelper(IDomainService domainService) { return _domainHelper ?? (_domainHelper = new DomainHelper(domainService)); } // for INTERNAL, UNIT TESTS use ONLY internal RoutesCache RoutesCache { get { return _routesCache; } } // for INTERNAL, UNIT TESTS use ONLY internal static bool UnitTesting = false; public virtual IPublishedContent GetByRoute(UmbracoContext umbracoContext, bool preview, string route, bool? hideTopLevelNode = null) { if (route == null) throw new ArgumentNullException("route"); // try to get from cache if not previewing var contentId = preview ? 0 : _routesCache.GetNodeId(route); // if found id in cache then get corresponding content // and clear cache if not found - for whatever reason IPublishedContent content = null; if (contentId > 0) { content = GetById(umbracoContext, preview, contentId); if (content == null) _routesCache.ClearNode(contentId); } // still have nothing? actually determine the id hideTopLevelNode = hideTopLevelNode ?? GlobalSettings.HideTopLevelNodeFromPath; // default = settings content = content ?? DetermineIdByRoute(umbracoContext, preview, route, hideTopLevelNode.Value); // cache if we have a content and not previewing if (content != null && preview == false) AddToCacheIfDeepestRoute(umbracoContext, content, route); return content; } private void AddToCacheIfDeepestRoute(UmbracoContext umbracoContext, IPublishedContent content, string route) { var domainRootNodeId = route.StartsWith("/") ? -1 : int.Parse(route.Substring(0, route.IndexOf('/'))); // so we have a route that maps to a content... say "1234/path/to/content" - however, there could be a // domain set on "to" and route "4567/content" would also map to the same content - and due to how // urls computing work (by walking the tree up to the first domain we find) it is that second route // that would be returned - the "deepest" route - and that is the route we want to cache, *not* the // longer one - so make sure we don't cache the wrong route var deepest = UnitTesting == false && DomainHelper.ExistsDomainInPath(umbracoContext.Application.Services.DomainService.GetAll(false), content.Path, domainRootNodeId) == false; if (deepest) _routesCache.Store(content.Id, route, true); // trusted route } public virtual string GetRouteById(UmbracoContext umbracoContext, bool preview, int contentId) { // try to get from cache if not previewing var route = preview ? null : _routesCache.GetRoute(contentId); // if found in cache then return if (route != null) return route; // else actually determine the route route = DetermineRouteById(umbracoContext, preview, contentId); // node not found if (route == null) return null; // cache the route BUT do NOT trust it as it can be a colliding route // meaning if we GetRouteById again, we'll get it from cache, but it // won't be used for inbound routing if (preview == false) _routesCache.Store(contentId, route, false); return route; } IPublishedContent DetermineIdByRoute(UmbracoContext umbracoContext, bool preview, string route, bool hideTopLevelNode) { if (route == null) throw new ArgumentNullException("route"); //the route always needs to be lower case because we only store the urlName attribute in lower case route = route.ToLowerInvariant(); var pos = route.IndexOf('/'); var path = pos == 0 ? route : route.Substring(pos); var startNodeId = pos == 0 ? 0 : int.Parse(route.Substring(0, pos)); //check if we can find the node in our xml cache var id = NavigateRoute(umbracoContext, preview, startNodeId, path, hideTopLevelNode); return id > 0 ? GetById(umbracoContext, preview, id) : null; } private static XmlElement GetXmlElementChildWithLowestSortOrder(XmlNode element) { XmlElement elt = null; var min = int.MaxValue; foreach (var n in element.ChildNodes) { var e = n as XmlElement; if (e == null) continue; var sortOrder = int.Parse(e.GetAttribute("sortOrder")); if (sortOrder >= min) continue; min = sortOrder; elt = e; } return elt; } private int NavigateRoute(UmbracoContext umbracoContext, bool preview, int startNodeId, string path, bool hideTopLevelNode) { var xml = GetXml(umbracoContext, preview); XmlElement elt; // empty path if (path == string.Empty || path == "/") { if (startNodeId > 0) { elt = xml.GetElementById(startNodeId.ToString(CultureInfo.InvariantCulture)); return elt == null ? -1 : startNodeId; } elt = GetXmlElementChildWithLowestSortOrder(xml.DocumentElement); return elt == null ? -1 : int.Parse(elt.GetAttribute("id")); } // non-empty path elt = startNodeId <= 0 ? xml.DocumentElement : xml.GetElementById(startNodeId.ToString(CultureInfo.InvariantCulture)); if (elt == null) return -1; var urlParts = path.Split(SlashChar, StringSplitOptions.RemoveEmptyEntries); if (hideTopLevelNode && startNodeId <= 0) { //Don't use OfType<T> or Cast<T>, this is critical code, all ChildNodes are XmlElement so explicitly cast // https://gist.github.com/Shazwazza/04e2e5642a316f4a87e52dada2901198 foreach (var n in elt.ChildNodes) { var e = n as XmlElement; if (e == null) continue; var id = NavigateElementRoute(e, urlParts); if (id > 0) return id; } if (urlParts.Length > 1) return -1; } return NavigateElementRoute(elt, urlParts); } private static bool UseLegacySchema { get { return UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema; } } private static int NavigateElementRoute(XmlElement elt, string[] urlParts) { var found = true; var i = 0; while (found && i < urlParts.Length) { found = false; //Don't use OfType<T> or Cast<T>, this is critical code, all ChildNodes are XmlElement so explicitly cast // https://gist.github.com/Shazwazza/04e2e5642a316f4a87e52dada2901198 var sortOrder = -1; foreach (var o in elt.ChildNodes) { var child = o as XmlElement; if (child == null) continue; var noNode = UseLegacySchema ? child.Name != "node" : child.GetAttributeNode("isDoc") == null; if (noNode) continue; if (child.GetAttribute("urlName") != urlParts[i]) continue; found = true; var so = int.Parse(child.GetAttribute("sortOrder")); if (sortOrder >= 0 && so >= sortOrder) continue; sortOrder = so; elt = child; } i++; } return found ? int.Parse(elt.GetAttribute("id")) : -1; } string DetermineRouteById(UmbracoContext umbracoContext, bool preview, int contentId) { var xml = GetXml(umbracoContext, preview); var elt = xml.GetElementById(contentId.ToString(CultureInfo.InvariantCulture)); if (elt == null) return null; var domainHelper = GetDomainHelper(umbracoContext.Application.Services.DomainService); // walk up from that node until we hit a node with a domain, // or we reach the content root, collecting urls in the way var pathParts = new List<string>(); var eltId = int.Parse(elt.GetAttribute("id")); var eltParentId = int.Parse(((XmlElement) elt.ParentNode).GetAttribute("id")); var e = elt; var id = eltId; var hasDomains = domainHelper.NodeHasDomains(id); while (hasDomains == false && id != -1) { // get the url var urlName = e.GetAttribute("urlName"); pathParts.Add(urlName); // move to parent node e = (XmlElement) e.ParentNode; id = int.Parse(e.GetAttribute("id"), CultureInfo.InvariantCulture); hasDomains = id != -1 && domainHelper.NodeHasDomains(id); } // no domain, respect HideTopLevelNodeFromPath for legacy purposes if (hasDomains == false && GlobalSettings.HideTopLevelNodeFromPath) { if (eltParentId == -1) { var rootNode = GetXmlElementChildWithLowestSortOrder(xml.DocumentElement); if (rootNode != null && rootNode == elt) pathParts.RemoveAt(pathParts.Count - 1); } else { pathParts.RemoveAt(pathParts.Count - 1); } } // assemble the route pathParts.Reverse(); var path = "/" + string.Join("/", pathParts); // will be "/" or "/foo" or "/foo/bar" etc var route = (id == -1 ? "" : id.ToString(CultureInfo.InvariantCulture)) + path; return route; } #endregion #region XPath Strings class XPathStringsDefinition { public int Version { get; private set; } public string RootDocuments { get; private set; } public XPathStringsDefinition(int version) { Version = version; switch (version) { // legacy XML schema case 0: RootDocuments = "/root/node"; break; // default XML schema as of 4.10 case 1: RootDocuments = "/root/* [@isDoc]"; break; default: throw new Exception(string.Format("Unsupported Xml schema version '{0}').", version)); } } } static XPathStringsDefinition _xPathStringsValue; static XPathStringsDefinition XPathStrings { get { // in theory XPathStrings should be a static variable that // we should initialize in a static ctor - but then test cases // that switch schemas fail - so cache and refresh when needed, // ie never when running the actual site var version = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? 0 : 1; if (_xPathStringsValue == null || _xPathStringsValue.Version != version) _xPathStringsValue = new XPathStringsDefinition(version); return _xPathStringsValue; } } #endregion #region Converters private static IPublishedContent ConvertToDocument(XmlNode xmlNode, bool isPreviewing) { return xmlNode == null ? null : XmlPublishedContent.Get(xmlNode, isPreviewing); } private static IEnumerable<IPublishedContent> ConvertToDocuments(XmlNodeList xmlNodes, bool isPreviewing) { return xmlNodes.Cast<XmlNode>() .Select(xmlNode => XmlPublishedContent.Get(xmlNode, isPreviewing)); } #endregion #region Getters public virtual IPublishedContent GetById(UmbracoContext umbracoContext, bool preview, int nodeId) { return ConvertToDocument(GetXml(umbracoContext, preview).GetElementById(nodeId.ToString(CultureInfo.InvariantCulture)), preview); } public virtual IEnumerable<IPublishedContent> GetAtRoot(UmbracoContext umbracoContext, bool preview) { return ConvertToDocuments(GetXml(umbracoContext, preview).SelectNodes(XPathStrings.RootDocuments), preview); } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, string xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); if (string.IsNullOrWhiteSpace(xpath)) return null; var xml = GetXml(umbracoContext, preview); var node = vars == null ? xml.SelectSingleNode(xpath) : xml.SelectSingleNode(xpath, vars); return ConvertToDocument(node, preview); } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); var xml = GetXml(umbracoContext, preview); var node = vars == null ? xml.SelectSingleNode(xpath) : xml.SelectSingleNode(xpath, vars); return ConvertToDocument(node, preview); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, string xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); if (string.IsNullOrWhiteSpace(xpath)) return Enumerable.Empty<IPublishedContent>(); var xml = GetXml(umbracoContext, preview); var nodes = vars == null ? xml.SelectNodes(xpath) : xml.SelectNodes(xpath, vars); return ConvertToDocuments(nodes, preview); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); var xml = GetXml(umbracoContext, preview); var nodes = vars == null ? xml.SelectNodes(xpath) : xml.SelectNodes(xpath, vars); return ConvertToDocuments(nodes, preview); } public virtual bool HasContent(UmbracoContext umbracoContext, bool preview) { var xml = GetXml(umbracoContext, preview); if (xml == null) return false; var node = xml.SelectSingleNode(XPathStrings.RootDocuments); return node != null; } public virtual XPathNavigator GetXPathNavigator(UmbracoContext umbracoContext, bool preview) { var xml = GetXml(umbracoContext, preview); return xml.CreateNavigator(); } public virtual bool XPathNavigatorIsNavigable { get { return false; } } #endregion #region Legacy Xml static readonly ConditionalWeakTable<UmbracoContext, PreviewContent> PreviewContentCache = new ConditionalWeakTable<UmbracoContext, PreviewContent>(); private Func<UmbracoContext, bool, XmlDocument> _xmlDelegate; /// <summary> /// Gets/sets the delegate used to retrieve the Xml content, generally the setter is only used for unit tests /// and by default if it is not set will use the standard delegate which ONLY works when in the context an Http Request /// </summary> /// <remarks> /// If not defined, we will use the standard delegate which ONLY works when in the context an Http Request /// mostly because the 'content' object heavily relies on HttpContext, SQL connections and a bunch of other stuff /// that when run inside of a unit test fails. /// </remarks> internal Func<UmbracoContext, bool, XmlDocument> GetXmlDelegate { get { return _xmlDelegate ?? (_xmlDelegate = (context, preview) => { if (preview) { var previewContent = PreviewContentCache.GetOrCreateValue(context); // will use the ctor with no parameters previewContent.EnsureInitialized(context.UmbracoUser, StateHelper.Cookies.Preview.GetValue(), true, () => { if (previewContent.ValidPreviewSet) previewContent.LoadPreviewset(); }); if (previewContent.ValidPreviewSet) return previewContent.XmlContent; } return content.Instance.XmlContent; }); } set { _xmlDelegate = value; } } internal XmlDocument GetXml(UmbracoContext umbracoContext, bool preview) { var xml = GetXmlDelegate(umbracoContext, preview); if (xml == null) throw new Exception("The Xml cache is corrupt. Use the Health Check data integrity dashboard to fix it."); return xml; } #endregion #region XPathQuery static readonly char[] SlashChar = new[] { '/' }; #endregion #region Detached public IPublishedProperty CreateDetachedProperty(PublishedPropertyType propertyType, object value, bool isPreviewing) { if (propertyType.IsDetachedOrNested == false) throw new ArgumentException("Property type is neither detached nor nested.", "propertyType"); return new XmlPublishedProperty(propertyType, isPreviewing, value.ToString()); } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="RequestCachingSection.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net.Configuration { using Microsoft.Win32; using System.Configuration; using System.Globalization; using System.Net.Cache; using System.Threading; public sealed class RequestCachingSection : ConfigurationSection { public RequestCachingSection() { this.properties.Add(this.disableAllCaching); this.properties.Add(this.defaultPolicyLevel); this.properties.Add(this.isPrivateCache); this.properties.Add(this.defaultHttpCachePolicy); this.properties.Add(this.defaultFtpCachePolicy); this.properties.Add(this.unspecifiedMaximumAge); } [ConfigurationProperty(ConfigurationStrings.DefaultHttpCachePolicy)] public HttpCachePolicyElement DefaultHttpCachePolicy { get { return (HttpCachePolicyElement)this[this.defaultHttpCachePolicy]; } } [ConfigurationProperty(ConfigurationStrings.DefaultFtpCachePolicy)] public FtpCachePolicyElement DefaultFtpCachePolicy { get { return (FtpCachePolicyElement)this[this.defaultFtpCachePolicy]; } } [ConfigurationProperty(ConfigurationStrings.DefaultPolicyLevel, DefaultValue=(RequestCacheLevel) RequestCacheLevel.BypassCache)] public RequestCacheLevel DefaultPolicyLevel { get { return (RequestCacheLevel)this[this.defaultPolicyLevel]; } set { this[this.defaultPolicyLevel] = value; } } #if !FEATURE_PAL // FEATURE_PAL - Caching is not supported by default [ConfigurationProperty(ConfigurationStrings.DisableAllCaching, DefaultValue=false)] #else // !FEATURE_PAL [ConfigurationProperty(ConfigurationStrings.DisableAllCaching, DefaultValue=true)] #endif // !FEATURE_PAL public bool DisableAllCaching { get { return (bool)this[this.disableAllCaching]; } set { this[this.disableAllCaching] = value; } } [ConfigurationProperty(ConfigurationStrings.IsPrivateCache, DefaultValue=true)] public bool IsPrivateCache { get { return (bool)this[this.isPrivateCache]; } set { this[this.isPrivateCache] = value; } } [ConfigurationProperty(ConfigurationStrings.UnspecifiedMaximumAge, DefaultValue = "1.00:00:00")] public TimeSpan UnspecifiedMaximumAge { get { return (TimeSpan)this[this.unspecifiedMaximumAge]; } set { this[this.unspecifiedMaximumAge] = value; } } // // If DisableAllCaching is set once to true it will not change. // protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey) { bool tempDisableAllCaching = this.DisableAllCaching; base.DeserializeElement(reader, serializeCollectionKey); if (tempDisableAllCaching) { this.DisableAllCaching = true; } } protected override void PostDeserialize() { // Perf optimization. If the configuration is coming from machine.config // It is safe and we don't need to check for permissions. if (EvaluationContext.IsMachineLevel) return; try { ExceptionHelper.WebPermissionUnrestricted.Demand(); } catch (Exception exception) { throw new ConfigurationErrorsException( SR.GetString(SR.net_config_section_permission, ConfigurationStrings.RequestCachingSectionName), exception); } } protected override ConfigurationPropertyCollection Properties { get { return this.properties; } } ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection(); readonly ConfigurationProperty defaultHttpCachePolicy = new ConfigurationProperty(ConfigurationStrings.DefaultHttpCachePolicy, typeof(HttpCachePolicyElement), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty defaultFtpCachePolicy = new ConfigurationProperty(ConfigurationStrings.DefaultFtpCachePolicy, typeof(FtpCachePolicyElement), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty defaultPolicyLevel = new ConfigurationProperty(ConfigurationStrings.DefaultPolicyLevel, typeof(RequestCacheLevel), RequestCacheLevel.BypassCache, ConfigurationPropertyOptions.None); readonly ConfigurationProperty disableAllCaching = #if !FEATURE_PAL // FEATURE_PAL - Caching is not supported by default new ConfigurationProperty(ConfigurationStrings.DisableAllCaching, typeof(bool), false, ConfigurationPropertyOptions.None); #else // !FEATURE_PAL new ConfigurationProperty(ConfigurationStrings.DisableAllCaching, typeof(bool), true, ConfigurationPropertyOptions.None); #endif // !FEATURE_PAL readonly ConfigurationProperty isPrivateCache = new ConfigurationProperty(ConfigurationStrings.IsPrivateCache, typeof(bool), true, ConfigurationPropertyOptions.None); readonly ConfigurationProperty unspecifiedMaximumAge = new ConfigurationProperty(ConfigurationStrings.UnspecifiedMaximumAge, typeof(TimeSpan), TimeSpan.FromDays(1), ConfigurationPropertyOptions.None); } internal sealed class RequestCachingSectionInternal { private RequestCachingSectionInternal() { } internal RequestCachingSectionInternal(RequestCachingSection section) { #if !FEATURE_PAL // IE caching //ROTORTODO: Review // IE caching //CORIOLISTODO: Review // IE caching if (!section.DisableAllCaching) { this.defaultCachePolicy = new RequestCachePolicy(section.DefaultPolicyLevel); // default should be RequestCacheLevel.BypassCache this.isPrivateCache = section.IsPrivateCache; this.unspecifiedMaximumAge = section.UnspecifiedMaximumAge; //default should be TimeSpan.FromDays(1) } else { this.disableAllCaching = true; } this.httpRequestCacheValidator = new HttpRequestCacheValidator(false, this.UnspecifiedMaximumAge); this.ftpRequestCacheValidator = new FtpRequestCacheValidator(false, this.UnspecifiedMaximumAge); this.defaultCache = new Microsoft.Win32.WinInetCache(this.IsPrivateCache, true, true); if (section.DisableAllCaching) return; HttpCachePolicyElement httpPolicy = section.DefaultHttpCachePolicy; if (httpPolicy.WasReadFromConfig) { if (httpPolicy.PolicyLevel == HttpRequestCacheLevel.Default) { HttpCacheAgeControl cacheAgeControl = (httpPolicy.MinimumFresh != TimeSpan.MinValue ? HttpCacheAgeControl.MaxAgeAndMinFresh : HttpCacheAgeControl.MaxAgeAndMaxStale); this.defaultHttpCachePolicy = new HttpRequestCachePolicy(cacheAgeControl, httpPolicy.MaximumAge, (httpPolicy.MinimumFresh != TimeSpan.MinValue ? httpPolicy.MinimumFresh : httpPolicy.MaximumStale)); } else { this.defaultHttpCachePolicy = new HttpRequestCachePolicy(httpPolicy.PolicyLevel); } } #else //!FEATURE_PAL // IE caching #if CORIOLIS if (section.DisableAllCaching) { this.httpRequestCacheValidator = new HttpRequestCacheValidator(false, this.UnspecifiedMaximumAge); this.disableAllCaching = true; } else { // Caching needs to be disabled in the configuration since Coriolis // does not support it. // This is a validity check, that it is actually disabled. throw new NotImplementedException("ROTORTODO - RequestCaching - IE caching"); } #else // CORIOLIS this.httpRequestCacheValidator = new HttpRequestCacheValidator(false, this.UnspecifiedMaximumAge); this.disableAllCaching = true; #endif #endif //!FEATURE_PAL // IE caching FtpCachePolicyElement ftpPolicy = section.DefaultFtpCachePolicy; if (ftpPolicy.WasReadFromConfig) { this.defaultFtpCachePolicy = new RequestCachePolicy(ftpPolicy.PolicyLevel); } } internal static object ClassSyncObject { get { if (classSyncObject == null) { object o = new object(); Interlocked.CompareExchange(ref classSyncObject, o, null); } return classSyncObject; } } internal bool DisableAllCaching { get { return this.disableAllCaching; } } internal RequestCache DefaultCache { get { return this.defaultCache; } } internal RequestCachePolicy DefaultCachePolicy { get { return this.defaultCachePolicy; } } internal bool IsPrivateCache { get { return this.isPrivateCache; } } internal TimeSpan UnspecifiedMaximumAge { get { return this.unspecifiedMaximumAge; } } internal HttpRequestCachePolicy DefaultHttpCachePolicy { get { return this.defaultHttpCachePolicy; } } internal RequestCachePolicy DefaultFtpCachePolicy { get { return this.defaultFtpCachePolicy; } } internal HttpRequestCacheValidator DefaultHttpValidator { get { return this.httpRequestCacheValidator; } } internal FtpRequestCacheValidator DefaultFtpValidator { get { return this.ftpRequestCacheValidator; } } static internal RequestCachingSectionInternal GetSection() { lock (RequestCachingSectionInternal.ClassSyncObject) { RequestCachingSection section = PrivilegedConfigurationManager.GetSection(ConfigurationStrings.RequestCachingSectionPath) as RequestCachingSection; if (section == null) return null; try { return new RequestCachingSectionInternal(section); } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) throw; throw new ConfigurationErrorsException(SR.GetString(SR.net_config_requestcaching), exception); } } } static object classSyncObject; RequestCache defaultCache; HttpRequestCachePolicy defaultHttpCachePolicy; RequestCachePolicy defaultFtpCachePolicy; RequestCachePolicy defaultCachePolicy; bool disableAllCaching; HttpRequestCacheValidator httpRequestCacheValidator; FtpRequestCacheValidator ftpRequestCacheValidator; bool isPrivateCache; TimeSpan unspecifiedMaximumAge; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; using static System.Linq.Expressions.CachedReflectionInfo; namespace System.Linq.Expressions.Compiler { internal partial class LambdaCompiler { #region Conditional private void EmitConditionalExpression(Expression expr, CompilationFlags flags) { ConditionalExpression node = (ConditionalExpression)expr; Debug.Assert(node.Test.Type == typeof(bool)); Label labFalse = _ilg.DefineLabel(); EmitExpressionAndBranch(false, node.Test, labFalse); EmitExpressionAsType(node.IfTrue, node.Type, flags); if (NotEmpty(node.IfFalse)) { Label labEnd = _ilg.DefineLabel(); if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) { // We know the conditional expression is at the end of the lambda, // so it is safe to emit Ret here. _ilg.Emit(OpCodes.Ret); } else { _ilg.Emit(OpCodes.Br, labEnd); } _ilg.MarkLabel(labFalse); EmitExpressionAsType(node.IfFalse, node.Type, flags); _ilg.MarkLabel(labEnd); } else { _ilg.MarkLabel(labFalse); } } /// <summary> /// returns true if the expression is not empty, otherwise false. /// </summary> private static bool NotEmpty(Expression node) { var empty = node as DefaultExpression; if (empty == null || empty.Type != typeof(void)) { return true; } return false; } /// <summary> /// returns true if the expression is NOT empty and is not debug info, /// or a block that contains only insignificant expressions. /// </summary> private static bool Significant(Expression node) { var block = node as BlockExpression; if (block != null) { for (int i = 0; i < block.ExpressionCount; i++) { if (Significant(block.GetExpression(i))) { return true; } } return false; } return NotEmpty(node) && !(node is DebugInfoExpression); } #endregion #region Coalesce private void EmitCoalesceBinaryExpression(Expression expr) { BinaryExpression b = (BinaryExpression)expr; Debug.Assert(b.Method == null); if (TypeUtils.IsNullableType(b.Left.Type)) { EmitNullableCoalesce(b); } else if (b.Left.Type.GetTypeInfo().IsValueType) { throw Error.CoalesceUsedOnNonNullType(); } else if (b.Conversion != null) { EmitLambdaReferenceCoalesce(b); } else { EmitReferenceCoalesceWithoutConversion(b); } } private void EmitNullableCoalesce(BinaryExpression b) { Debug.Assert(b.Method == null); LocalBuilder loc = GetLocal(b.Left.Type); Label labIfNull = _ilg.DefineLabel(); Label labEnd = _ilg.DefineLabel(); EmitExpression(b.Left); _ilg.Emit(OpCodes.Stloc, loc); _ilg.Emit(OpCodes.Ldloca, loc); _ilg.EmitHasValue(b.Left.Type); _ilg.Emit(OpCodes.Brfalse, labIfNull); Type nnLeftType = TypeUtils.GetNonNullableType(b.Left.Type); if (b.Conversion != null) { Debug.Assert(b.Conversion.Parameters.Count == 1); ParameterExpression p = b.Conversion.Parameters[0]; Debug.Assert(p.Type.IsAssignableFrom(b.Left.Type) || p.Type.IsAssignableFrom(nnLeftType)); // emit the delegate instance EmitLambdaExpression(b.Conversion); // emit argument if (!p.Type.IsAssignableFrom(b.Left.Type)) { _ilg.Emit(OpCodes.Ldloca, loc); _ilg.EmitGetValueOrDefault(b.Left.Type); } else { _ilg.Emit(OpCodes.Ldloc, loc); } // emit call to invoke _ilg.Emit(OpCodes.Callvirt, b.Conversion.Type.GetMethod("Invoke")); } else if (!TypeUtils.AreEquivalent(b.Type, nnLeftType)) { _ilg.Emit(OpCodes.Ldloca, loc); _ilg.EmitGetValueOrDefault(b.Left.Type); _ilg.EmitConvertToType(nnLeftType, b.Type, true); } else { _ilg.Emit(OpCodes.Ldloca, loc); _ilg.EmitGetValueOrDefault(b.Left.Type); } FreeLocal(loc); _ilg.Emit(OpCodes.Br, labEnd); _ilg.MarkLabel(labIfNull); EmitExpression(b.Right); if (!TypeUtils.AreEquivalent(b.Right.Type, b.Type)) { _ilg.EmitConvertToType(b.Right.Type, b.Type, true); } _ilg.MarkLabel(labEnd); } private void EmitLambdaReferenceCoalesce(BinaryExpression b) { LocalBuilder loc = GetLocal(b.Left.Type); Label labEnd = _ilg.DefineLabel(); Label labNotNull = _ilg.DefineLabel(); EmitExpression(b.Left); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Stloc, loc); _ilg.Emit(OpCodes.Ldnull); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Brfalse, labNotNull); EmitExpression(b.Right); _ilg.Emit(OpCodes.Br, labEnd); // if not null, call conversion _ilg.MarkLabel(labNotNull); Debug.Assert(b.Conversion.Parameters.Count == 1); // emit the delegate instance EmitLambdaExpression(b.Conversion); // emit argument _ilg.Emit(OpCodes.Ldloc, loc); FreeLocal(loc); // emit call to invoke _ilg.Emit(OpCodes.Callvirt, b.Conversion.Type.GetMethod("Invoke")); _ilg.MarkLabel(labEnd); } private void EmitReferenceCoalesceWithoutConversion(BinaryExpression b) { Label labEnd = _ilg.DefineLabel(); Label labCast = _ilg.DefineLabel(); EmitExpression(b.Left); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Ldnull); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Brfalse, labCast); _ilg.Emit(OpCodes.Pop); EmitExpression(b.Right); if (!TypeUtils.AreEquivalent(b.Right.Type, b.Type)) { if (b.Right.Type.GetTypeInfo().IsValueType) { _ilg.Emit(OpCodes.Box, b.Right.Type); } _ilg.Emit(OpCodes.Castclass, b.Type); } _ilg.Emit(OpCodes.Br_S, labEnd); _ilg.MarkLabel(labCast); if (!TypeUtils.AreEquivalent(b.Left.Type, b.Type)) { Debug.Assert(!b.Left.Type.GetTypeInfo().IsValueType); _ilg.Emit(OpCodes.Castclass, b.Type); } _ilg.MarkLabel(labEnd); } #endregion #region AndAlso private void EmitLiftedAndAlso(BinaryExpression b) { Type type = typeof(bool?); Label labComputeRight = _ilg.DefineLabel(); Label labReturnFalse = _ilg.DefineLabel(); Label labReturnNull = _ilg.DefineLabel(); Label labReturnValue = _ilg.DefineLabel(); Label labExit = _ilg.DefineLabel(); LocalBuilder locLeft = GetLocal(type); LocalBuilder locRight = GetLocal(type); EmitExpression(b.Left); _ilg.Emit(OpCodes.Stloc, locLeft); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Brfalse, labComputeRight); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitGetValueOrDefault(type); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Brtrue, labReturnFalse); // compute right _ilg.MarkLabel(labComputeRight); EmitExpression(b.Right); _ilg.Emit(OpCodes.Stloc, locRight); _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Brfalse_S, labReturnNull); _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitGetValueOrDefault(type); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Brtrue_S, labReturnFalse); // check left for null again _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Brfalse, labReturnNull); // return true _ilg.Emit(OpCodes.Ldc_I4_1); _ilg.Emit(OpCodes.Br_S, labReturnValue); // return false _ilg.MarkLabel(labReturnFalse); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Br_S, labReturnValue); _ilg.MarkLabel(labReturnValue); ConstructorInfo ci = type.GetConstructor(ArrayOfType_Bool); _ilg.Emit(OpCodes.Newobj, ci); _ilg.Emit(OpCodes.Stloc, locLeft); _ilg.Emit(OpCodes.Br, labExit); // return null _ilg.MarkLabel(labReturnNull); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.Emit(OpCodes.Initobj, type); _ilg.MarkLabel(labExit); _ilg.Emit(OpCodes.Ldloc, locLeft); FreeLocal(locLeft); FreeLocal(locRight); } private void EmitMethodAndAlso(BinaryExpression b, CompilationFlags flags) { Label labEnd = _ilg.DefineLabel(); EmitExpression(b.Left); _ilg.Emit(OpCodes.Dup); MethodInfo opFalse = TypeUtils.GetBooleanOperator(b.Method.DeclaringType, "op_False"); Debug.Assert(opFalse != null, "factory should check that the method exists"); _ilg.Emit(OpCodes.Call, opFalse); _ilg.Emit(OpCodes.Brtrue, labEnd); //store the value of the left value before emitting b.Right to empty the evaluation stack LocalBuilder locLeft = GetLocal(b.Left.Type); _ilg.Emit(OpCodes.Stloc, locLeft); EmitExpression(b.Right); //store the right value to local LocalBuilder locRight = GetLocal(b.Right.Type); _ilg.Emit(OpCodes.Stloc, locRight); Debug.Assert(b.Method.IsStatic); _ilg.Emit(OpCodes.Ldloc, locLeft); _ilg.Emit(OpCodes.Ldloc, locRight); if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) { _ilg.Emit(OpCodes.Tailcall); } _ilg.Emit(OpCodes.Call, b.Method); FreeLocal(locLeft); FreeLocal(locRight); _ilg.MarkLabel(labEnd); } private void EmitUnliftedAndAlso(BinaryExpression b) { Label @else = _ilg.DefineLabel(); Label end = _ilg.DefineLabel(); EmitExpressionAndBranch(false, b.Left, @else); EmitExpression(b.Right); _ilg.Emit(OpCodes.Br, end); _ilg.MarkLabel(@else); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.MarkLabel(end); } private void EmitAndAlsoBinaryExpression(Expression expr, CompilationFlags flags) { BinaryExpression b = (BinaryExpression)expr; if (b.Method != null && !b.IsLiftedLogical) { EmitMethodAndAlso(b, flags); } else if (b.Left.Type == typeof(bool?)) { EmitLiftedAndAlso(b); } else if (b.IsLiftedLogical) { EmitExpression(b.ReduceUserdefinedLifted()); } else { EmitUnliftedAndAlso(b); } } #endregion #region OrElse private void EmitLiftedOrElse(BinaryExpression b) { Type type = typeof(bool?); Label labComputeRight = _ilg.DefineLabel(); Label labReturnTrue = _ilg.DefineLabel(); Label labReturnNull = _ilg.DefineLabel(); Label labReturnValue = _ilg.DefineLabel(); Label labExit = _ilg.DefineLabel(); LocalBuilder locLeft = GetLocal(type); LocalBuilder locRight = GetLocal(type); EmitExpression(b.Left); _ilg.Emit(OpCodes.Stloc, locLeft); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Brfalse, labComputeRight); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitGetValueOrDefault(type); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Brfalse, labReturnTrue); // compute right _ilg.MarkLabel(labComputeRight); EmitExpression(b.Right); _ilg.Emit(OpCodes.Stloc, locRight); _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Brfalse_S, labReturnNull); _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitGetValueOrDefault(type); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Brfalse_S, labReturnTrue); // check left for null again _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Brfalse, labReturnNull); // return false _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Br_S, labReturnValue); // return true _ilg.MarkLabel(labReturnTrue); _ilg.Emit(OpCodes.Ldc_I4_1); _ilg.Emit(OpCodes.Br_S, labReturnValue); _ilg.MarkLabel(labReturnValue); ConstructorInfo ci = type.GetConstructor(ArrayOfType_Bool); _ilg.Emit(OpCodes.Newobj, ci); _ilg.Emit(OpCodes.Stloc, locLeft); _ilg.Emit(OpCodes.Br, labExit); // return null _ilg.MarkLabel(labReturnNull); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.Emit(OpCodes.Initobj, type); _ilg.MarkLabel(labExit); _ilg.Emit(OpCodes.Ldloc, locLeft); FreeLocal(locLeft); FreeLocal(locRight); } private void EmitUnliftedOrElse(BinaryExpression b) { Label @else = _ilg.DefineLabel(); Label end = _ilg.DefineLabel(); EmitExpressionAndBranch(false, b.Left, @else); _ilg.Emit(OpCodes.Ldc_I4_1); _ilg.Emit(OpCodes.Br, end); _ilg.MarkLabel(@else); EmitExpression(b.Right); _ilg.MarkLabel(end); } private void EmitMethodOrElse(BinaryExpression b, CompilationFlags flags) { Label labEnd = _ilg.DefineLabel(); EmitExpression(b.Left); _ilg.Emit(OpCodes.Dup); MethodInfo opTrue = TypeUtils.GetBooleanOperator(b.Method.DeclaringType, "op_True"); Debug.Assert(opTrue != null, "factory should check that the method exists"); _ilg.Emit(OpCodes.Call, opTrue); _ilg.Emit(OpCodes.Brtrue, labEnd); //store the value of the left value before emitting b.Right to empty the evaluation stack LocalBuilder locLeft = GetLocal(b.Left.Type); _ilg.Emit(OpCodes.Stloc, locLeft); EmitExpression(b.Right); //store the right value to local LocalBuilder locRight = GetLocal(b.Right.Type); _ilg.Emit(OpCodes.Stloc, locRight); Debug.Assert(b.Method.IsStatic); _ilg.Emit(OpCodes.Ldloc, locLeft); _ilg.Emit(OpCodes.Ldloc, locRight); if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) { _ilg.Emit(OpCodes.Tailcall); } _ilg.Emit(OpCodes.Call, b.Method); FreeLocal(locLeft); FreeLocal(locRight); _ilg.MarkLabel(labEnd); } private void EmitOrElseBinaryExpression(Expression expr, CompilationFlags flags) { BinaryExpression b = (BinaryExpression)expr; if (b.Method != null && !b.IsLiftedLogical) { EmitMethodOrElse(b, flags); } else if (b.Left.Type == typeof(bool?)) { EmitLiftedOrElse(b); } else if (b.IsLiftedLogical) { EmitExpression(b.ReduceUserdefinedLifted()); } else { EmitUnliftedOrElse(b); } } #endregion #region Optimized branching /// <summary> /// Emits the expression and then either brtrue/brfalse to the label. /// </summary> /// <param name="branchValue">True for brtrue, false for brfalse.</param> /// <param name="node">The expression to emit.</param> /// <param name="label">The label to conditionally branch to.</param> /// <remarks> /// This function optimizes equality and short circuiting logical /// operators to avoid double-branching, minimize instruction count, /// and generate similar IL to the C# compiler. This is important for /// the JIT to optimize patterns like: /// x != null AndAlso x.GetType() == typeof(SomeType) /// /// One optimization we don't do: we always emits at least one /// conditional branch to the label, and always possibly falls through, /// even if we know if the branch will always succeed or always fail. /// We do this to avoid generating unreachable code, which is fine for /// the CLR JIT, but doesn't verify with peverify. /// /// This kind of optimization could be implemented safely, by doing /// constant folding over conditionals and logical expressions at the /// tree level. /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] private void EmitExpressionAndBranch(bool branchValue, Expression node, Label label) { CompilationFlags startEmitted = EmitExpressionStart(node); try { if (node.Type == typeof(bool)) { switch (node.NodeType) { case ExpressionType.Not: EmitBranchNot(branchValue, (UnaryExpression)node, label); return; case ExpressionType.AndAlso: case ExpressionType.OrElse: EmitBranchLogical(branchValue, (BinaryExpression)node, label); return; case ExpressionType.Block: EmitBranchBlock(branchValue, (BlockExpression)node, label); return; case ExpressionType.Equal: case ExpressionType.NotEqual: EmitBranchComparison(branchValue, (BinaryExpression)node, label); return; } } EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart); EmitBranchOp(branchValue, label); } finally { EmitExpressionEnd(startEmitted); } } private void EmitBranchOp(bool branch, Label label) { _ilg.Emit(branch ? OpCodes.Brtrue : OpCodes.Brfalse, label); } private void EmitBranchNot(bool branch, UnaryExpression node, Label label) { if (node.Method != null) { EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart); EmitBranchOp(branch, label); return; } EmitExpressionAndBranch(!branch, node.Operand, label); } private void EmitBranchComparison(bool branch, BinaryExpression node, Label label) { Debug.Assert(node.NodeType == ExpressionType.Equal || node.NodeType == ExpressionType.NotEqual); Debug.Assert(!node.IsLiftedToNull); // To share code paths, we want to treat NotEqual as an inverted Equal bool branchWhenEqual = branch == (node.NodeType == ExpressionType.Equal); if (node.Method != null) { EmitBinaryMethod(node, CompilationFlags.EmitAsNoTail); // EmitBinaryMethod takes into account the Equal/NotEqual // node kind, so use the original branch value EmitBranchOp(branch, label); } else if (ConstantCheck.IsNull(node.Left)) { if (TypeUtils.IsNullableType(node.Right.Type)) { EmitAddress(node.Right, node.Right.Type); _ilg.EmitHasValue(node.Right.Type); } else { Debug.Assert(!node.Right.Type.GetTypeInfo().IsValueType); EmitExpression(GetEqualityOperand(node.Right)); } EmitBranchOp(!branchWhenEqual, label); } else if (ConstantCheck.IsNull(node.Right)) { if (TypeUtils.IsNullableType(node.Left.Type)) { EmitAddress(node.Left, node.Left.Type); _ilg.EmitHasValue(node.Left.Type); } else { Debug.Assert(!node.Left.Type.GetTypeInfo().IsValueType); EmitExpression(GetEqualityOperand(node.Left)); } EmitBranchOp(!branchWhenEqual, label); } else if (TypeUtils.IsNullableType(node.Left.Type) || TypeUtils.IsNullableType(node.Right.Type)) { EmitBinaryExpression(node); // EmitBinaryExpression takes into account the Equal/NotEqual // node kind, so use the original branch value EmitBranchOp(branch, label); } else { EmitExpression(GetEqualityOperand(node.Left)); EmitExpression(GetEqualityOperand(node.Right)); if (branchWhenEqual) { _ilg.Emit(OpCodes.Beq, label); } else { _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Brfalse, label); } } } // For optimized Equal/NotEqual, we can eliminate reference // conversions. IL allows comparing managed pointers regardless of // type. See ECMA-335 "Binary Comparison or Branch Operations", in // Partition III, Section 1.5 Table 4. private static Expression GetEqualityOperand(Expression expression) { if (expression.NodeType == ExpressionType.Convert) { var convert = (UnaryExpression)expression; if (TypeUtils.AreReferenceAssignable(convert.Type, convert.Operand.Type)) { return convert.Operand; } } return expression; } private void EmitBranchLogical(bool branch, BinaryExpression node, Label label) { Debug.Assert(node.NodeType == ExpressionType.AndAlso || node.NodeType == ExpressionType.OrElse); Debug.Assert(!node.IsLiftedToNull); if (node.Method != null || node.IsLifted) { EmitExpression(node); EmitBranchOp(branch, label); return; } bool isAnd = node.NodeType == ExpressionType.AndAlso; // To share code, we make the following substitutions: // if (!(left || right)) branch value // becomes: // if (!left && !right) branch value // and: // if (!(left && right)) branch value // becomes: // if (!left || !right) branch value // // The observation is that "brtrue(x && y)" has the same codegen as // "brfalse(x || y)" except the branches have the opposite sign. // Same for "brfalse(x && y)" and "brtrue(x || y)". // if (branch == isAnd) { EmitBranchAnd(branch, node, label); } else { EmitBranchOr(branch, node, label); } } // Generates optimized AndAlso with branch == true // or optimized OrElse with branch == false private void EmitBranchAnd(bool branch, BinaryExpression node, Label label) { // if (left) then // if (right) branch label // endif Label endif = _ilg.DefineLabel(); EmitExpressionAndBranch(!branch, node.Left, endif); EmitExpressionAndBranch(branch, node.Right, label); _ilg.MarkLabel(endif); } // Generates optimized OrElse with branch == true // or optimized AndAlso with branch == false private void EmitBranchOr(bool branch, BinaryExpression node, Label label) { // if (left OR right) branch label EmitExpressionAndBranch(branch, node.Left, label); EmitExpressionAndBranch(branch, node.Right, label); } private void EmitBranchBlock(bool branch, BlockExpression node, Label label) { EnterScope(node); int count = node.ExpressionCount; for (int i = 0; i < count - 1; i++) { EmitExpressionAsVoid(node.GetExpression(i)); } EmitExpressionAndBranch(branch, node.GetExpression(count - 1), label); ExitScope(node); } #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.ObjectModel; using System.Dynamic.Utils; using System.Linq.Expressions; using System.Runtime.CompilerServices; using DelegateHelpers = System.Linq.Expressions.Compiler.DelegateHelpers; namespace System.Dynamic { /// <summary> /// The dynamic call site binder that participates in the <see cref="DynamicMetaObject"/> binding protocol. /// </summary> /// <remarks> /// The <see cref="CallSiteBinder"/> performs the binding of the dynamic operation using the runtime values /// as input. On the other hand, the <see cref="DynamicMetaObjectBinder"/> participates in the <see cref="DynamicMetaObject"/> /// binding protocol. /// </remarks> public abstract class DynamicMetaObjectBinder : CallSiteBinder { #region Public APIs /// <summary> /// Initializes a new instance of the <see cref="DynamicMetaObjectBinder"/> class. /// </summary> protected DynamicMetaObjectBinder() { } /// <summary> /// The result type of the operation. /// </summary> public virtual Type ReturnType { get { return typeof(object); } } /// <summary> /// Performs the runtime binding of the dynamic operation on a set of arguments. /// </summary> /// <param name="args">An array of arguments to the dynamic operation.</param> /// <param name="parameters">The array of <see cref="ParameterExpression"/> instances that represent the parameters of the call site in the binding process.</param> /// <param name="returnLabel">A LabelTarget used to return the result of the dynamic binding.</param> /// <returns> /// An Expression that performs tests on the dynamic operation arguments, and /// performs the dynamic operation if the tests are valid. If the tests fail on /// subsequent occurrences of the dynamic operation, Bind will be called again /// to produce a new <see cref="Expression"/> for the new argument types. /// </returns> public sealed override Expression Bind(object[] args, ReadOnlyCollection<ParameterExpression> parameters, LabelTarget returnLabel) { ContractUtils.RequiresNotNull(args, "args"); ContractUtils.RequiresNotNull(parameters, "parameters"); ContractUtils.RequiresNotNull(returnLabel, "returnLabel"); if (args.Length == 0) { throw Error.OutOfRange("args.Length", 1); } if (parameters.Count == 0) { throw Error.OutOfRange("parameters.Count", 1); } if (args.Length != parameters.Count) { throw new ArgumentOutOfRangeException(nameof(args)); } // Ensure that the binder's ReturnType matches CallSite's return // type. We do this so meta objects and language binders can // compose trees together without needing to insert converts. Type expectedResult; if (IsStandardBinder) { expectedResult = ReturnType; if (returnLabel.Type != typeof(void) && !TypeUtils.AreReferenceAssignable(returnLabel.Type, expectedResult)) { throw Error.BinderNotCompatibleWithCallSite(expectedResult, this, returnLabel.Type); } } else { // Even for non-standard binders, we have to at least make sure // it works with the CallSite's type to build the return. expectedResult = returnLabel.Type; } DynamicMetaObject target = DynamicMetaObject.Create(args[0], parameters[0]); DynamicMetaObject[] metaArgs = CreateArgumentMetaObjects(args, parameters); DynamicMetaObject binding = Bind(target, metaArgs); if (binding == null) { throw Error.BindingCannotBeNull(); } Expression body = binding.Expression; BindingRestrictions restrictions = binding.Restrictions; // Ensure the result matches the expected result type. if (expectedResult != typeof(void) && !TypeUtils.AreReferenceAssignable(expectedResult, body.Type)) { // // Blame the last person that handled the result: assume it's // the dynamic object (if any), otherwise blame the language. // if (target.Value is IDynamicMetaObjectProvider) { throw Error.DynamicObjectResultNotAssignable(body.Type, target.Value.GetType(), this, expectedResult); } else { throw Error.DynamicBinderResultNotAssignable(body.Type, this, expectedResult); } } // if the target is IDO, standard binders ask it to bind the rule so we may have a target-specific binding. // it makes sense to restrict on the target's type in such cases. // ideally IDO metaobjects should do this, but they often miss that type of "this" is significant. if (IsStandardBinder && args[0] as IDynamicMetaObjectProvider != null) { if (restrictions == BindingRestrictions.Empty) { throw Error.DynamicBindingNeedsRestrictions(target.Value.GetType(), this); } } // Add the return if (body.NodeType != ExpressionType.Goto) { body = Expression.Return(returnLabel, body); } // Finally, add restrictions if (restrictions != BindingRestrictions.Empty) { body = Expression.IfThen(restrictions.ToExpression(), body); } return body; } private static DynamicMetaObject[] CreateArgumentMetaObjects(object[] args, ReadOnlyCollection<ParameterExpression> parameters) { DynamicMetaObject[] mos; if (args.Length != 1) { mos = new DynamicMetaObject[args.Length - 1]; for (int i = 1; i < args.Length; i++) { mos[i - 1] = DynamicMetaObject.Create(args[i], parameters[i]); } } else { mos = DynamicMetaObject.EmptyMetaObjects; } return mos; } /// <summary> /// When overridden in the derived class, performs the binding of the dynamic operation. /// </summary> /// <param name="target">The target of the dynamic operation.</param> /// <param name="args">An array of arguments of the dynamic operation.</param> /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public abstract DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args); /// <summary> /// Gets an expression that will cause the binding to be updated. It /// indicates that the expression's binding is no longer valid. /// This is typically used when the "version" of a dynamic object has /// changed. /// </summary> /// <param name="type">The <see cref="Expression.Type">Type</see> property of the resulting expression; any type is allowed.</param> /// <returns>The update expression.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public Expression GetUpdateExpression(Type type) { return Expression.Goto(CallSiteBinder.UpdateLabel, type); } /// <summary> /// Defers the binding of the operation until later time when the runtime values of all dynamic operation arguments have been computed. /// </summary> /// <param name="target">The target of the dynamic operation.</param> /// <param name="args">An array of arguments of the dynamic operation.</param> /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public DynamicMetaObject Defer(DynamicMetaObject target, params DynamicMetaObject[] args) { ContractUtils.RequiresNotNull(target, "target"); if (args == null) { return MakeDeferred(target.Restrictions, target); } else { return MakeDeferred( target.Restrictions.Merge(BindingRestrictions.Combine(args)), args.AddFirst(target) ); } } /// <summary> /// Defers the binding of the operation until later time when the runtime values of all dynamic operation arguments have been computed. /// </summary> /// <param name="args">An array of arguments of the dynamic operation.</param> /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public DynamicMetaObject Defer(params DynamicMetaObject[] args) { return MakeDeferred(BindingRestrictions.Combine(args), args); } private DynamicMetaObject MakeDeferred(BindingRestrictions rs, params DynamicMetaObject[] args) { var exprs = DynamicMetaObject.GetExpressions(args); Type delegateType = DelegateHelpers.MakeDeferredSiteDelegate(args, ReturnType); // Because we know the arguments match the delegate type (we just created the argument types) // we go directly to DynamicExpression.Make to avoid a bunch of unnecessary argument validation return new DynamicMetaObject( DynamicExpression.Make(ReturnType, delegateType, this, new TrueReadOnlyCollection<Expression>(exprs)), rs ); } #endregion // used to detect standard MetaObjectBinders. internal virtual bool IsStandardBinder { get { return false; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Windows.Threading; using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Security ; using MS.Internal ; using MS.Win32; using MS.Utility; using System.Runtime.InteropServices; using System.Security.Permissions; using Microsoft.Internal; using System.Windows.Input.StylusPlugIns; using System.Windows.Interop; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using MS.Internal.PresentationCore; // SecurityHelper namespace System.Windows.Input { ///////////////////////////////////////////////////////////////////////// internal sealed class PenContexts { ///////////////////////////////////////////////////////////////////////// ///<SecurityNote> /// Critical - InputManager ctor is critical, ergo this is critical data. /// Called by Stylus.RegisterHwndForInput. /// TreatAsSafe boundary is Stylus.RegisterHwndForInput called when a window is created. ///</SecurityNote> [SecurityCritical] internal PenContexts(StylusLogic stylusLogic, PresentationSource inputSource) { HwndSource hwndSource = inputSource as HwndSource; if(hwndSource == null || IntPtr.Zero == (hwndSource).CriticalHandle) { throw new InvalidOperationException(SR.Get(SRID.Stylus_PenContextFailure)); } _stylusLogic = stylusLogic; _inputSource = new SecurityCriticalData<HwndSource>(hwndSource); } ///////////////////////////////////////////////////////////////////////// ///<SecurityNote> /// Critical - Calls SecurityCritical code (TabletDevices.CreateContexts and PenContext.Enable) and accesses /// SecurityCritical data (_inputSource.Value and _contexts). /// Called by Stylus.EnableCore, Stylus.RegisterHwndForInput, Stylus.OnScreenMeasurementsChanged. /// TreatAsSafe boundry is Stylus.EnableCore, Stylus.RegisterHwndForInput /// and HwndWrapperHook class (via HwndSource.InputFilterMessage when /// a WM_DISPLAYCHANGE is processed by HwndStylusInputProvider). ///</SecurityNote> [SecurityCritical] internal void Enable() { if (_contexts == null) { // create contexts _contexts = _stylusLogic.TabletDevices.CreateContexts(_inputSource.Value.CriticalHandle, this); foreach(PenContext context in _contexts) { context.Enable(); } } } ///<SecurityNote> /// Critical - Accesses SecurityCritical data (_contexts). /// Called by Stylus.UnregisterHwndForInput and Dispose. /// TreatAsSafe boundry is Stylus.UnregisterHwndForInput /// and HwndStylusInputProvider.Dispose(bool). ///</SecurityNote> [SecurityCritical] internal void Disable(bool shutdownWorkerThread) { if (_contexts != null) { foreach(PenContext context in _contexts) { context.Disable(shutdownWorkerThread); } _contexts = null; // release refs on PenContext objects } } internal bool IsWindowDisabled { get { return _isWindowDisabled; } set { _isWindowDisabled = value; } } internal Point DestroyedLocation { get { return _destroyedLocation; } set { _destroyedLocation = value; } } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical - Calls SecurityCritical code ProcessInput. /// Called by PenContext.FirePenDown. /// TreatAsSafe boundary is PenThread.ThreadProc. /// </SecurityNote> [SecurityCritical] internal void OnPenDown(PenContext penContext, int tabletDeviceId, int stylusPointerId, int[] data, int timestamp) { ProcessInput(RawStylusActions.Down, penContext, tabletDeviceId, stylusPointerId, data, timestamp); } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical - Calls SecurityCritical code ProcessInput. /// Called by PenContext.FirePenUp. /// TreatAsSafe boundary is PenThread.ThreadProc. /// </SecurityNote> [SecurityCritical] internal void OnPenUp(PenContext penContext, int tabletDeviceId, int stylusPointerId, int[] data, int timestamp) { ProcessInput(RawStylusActions.Up, penContext, tabletDeviceId, stylusPointerId, data, timestamp); } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical - Calls SecurityCritical code ProcessInput. /// Called by PenContext.FirePackets. /// TreatAsSafe boundary is PenThread.ThreadProc. /// </SecurityNote> [SecurityCritical] internal void OnPackets(PenContext penContext, int tabletDeviceId, int stylusPointerId, int[] data, int timestamp) { ProcessInput(RawStylusActions.Move, penContext, tabletDeviceId, stylusPointerId, data, timestamp); } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical - Calls SecurityCritical code ProcessInput. /// Called by PenContext.FirePackets. /// TreatAsSafe boundary is PenThread.ThreadProc. /// </SecurityNote> [SecurityCritical] internal void OnInAirPackets(PenContext penContext, int tabletDeviceId, int stylusPointerId, int[] data, int timestamp) { ProcessInput(RawStylusActions.InAirMove, penContext, tabletDeviceId, stylusPointerId, data, timestamp); } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical - Calls SecurityCritical code ProcessInput. /// Called by PenContext.FirePenInRange. /// TreatAsSafe boundary is PenThread.ThreadProc. /// </SecurityNote> [SecurityCritical] internal void OnPenInRange(PenContext penContext, int tabletDeviceId, int stylusPointerId, int[] data, int timestamp) { ProcessInput(RawStylusActions.InRange, penContext, tabletDeviceId, stylusPointerId, data, timestamp); } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical - Calls SecurityCritical code ProcessInput. /// Called by PenContext.FirePenOutOfRange. /// TreatAsSafe boundary is PenThread.ThreadProc. /// </SecurityNote> [SecurityCritical] internal void OnPenOutOfRange(PenContext penContext, int tabletDeviceId, int stylusPointerId, int timestamp) { ProcessInput(RawStylusActions.OutOfRange, penContext, tabletDeviceId, stylusPointerId, new int[]{}, timestamp); } ///////////////////////////////////////////////////////////////////// ///<SecurityNote> /// Critical: Uses critical data _inputSource and calls SecurityCritical code /// StylusLogic.ProcessSystemEvent. /// Called by PenContext.FireSystemGesture. /// TreatAsSafe boundary is PenThread.ThreadProc. ///</SecurityNote> [SecurityCritical] internal void OnSystemEvent(PenContext penContext, int tabletDeviceId, int stylusPointerId, int timestamp, SystemGesture id, int gestureX, int gestureY, int buttonState) { _stylusLogic.ProcessSystemEvent(penContext, tabletDeviceId, stylusPointerId, timestamp, id, gestureX, gestureY, buttonState, _inputSource.Value); } ///////////////////////////////////////////////////////////////////// ///<SecurityNote> /// Critical: Uses critical data _inputSource and calls SecurityCritical /// code StylusLogic.ProcessInput. /// Called by OnPenDown, OnPenUp, OnPackets, OnInAirPackets, OnPenInRange and OnPenOutOfRange. /// TreatAsSafe boundary is PenThread.ThreadProc. ///</SecurityNote> [SecurityCritical] void ProcessInput( RawStylusActions actions, PenContext penContext, int tabletDeviceId, int stylusPointerId, int[] data, int timestamp) { // (all events but SystemEvent go thru here) _stylusLogic.ProcessInput( actions, penContext, tabletDeviceId, stylusPointerId, data, timestamp, _inputSource.Value); } ///////////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical since it accesses SecurityCritical data _contexts and /// returns SecurityCritical data PenContext. /// </SecurityNote> [SecurityCritical] internal PenContext GetTabletDeviceIDPenContext(int tabletDeviceId) { if (_contexts != null) { for (int i = 0; i < _contexts.Length; i++) { PenContext context = _contexts[i]; if (context.TabletDeviceId == tabletDeviceId) return context; } } return null; } ///////////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical since it accesses SecurityCritical data _contexts. /// </SecurityNote> [SecurityCritical] internal bool ConsiderInRange(int timestamp) { if (_contexts != null) { for (int i = 0; i < _contexts.Length; i++) { PenContext context = _contexts[i]; // We consider it InRange if we have a queued up context event or // the timestamp - LastInRangeTime <= 500 (seen one in the last 500ms) // Here's some info on how this works... // int.MaxValue - int.MinValue = -1 (subtracting any negative # from MaxValue keeps this negative) // int.MinValue - int.MaxValue = 1 (subtracting any positive # from MinValue keeps this positive) // So subtracting wrapping values will return proper sign depending on which was earlier. // We do have the assumption that these values will be relative close in time. If the // time wraps we'll say yet but the only harm is that we may defer a mouse move event temporarily // which won't cause any harm. if (context.QueuedInRangeCount > 0 || (Math.Abs(unchecked(timestamp - context.LastInRangeTime)) <= 500)) return true; } } return false; } ///////////////////////////////////////////////////////////////////// /// <summary> /// This method adds the specified pen context index in response /// to the WM_TABLET_ADDED notification /// </summary> ///<SecurityNote> /// Critical - Calls SecurityCritical code (Disable and TabletDevice.CreateContext) /// and accesses SecurityCritical data (_contexts). /// Called by Stylus.OnTabletAdded. /// TreatAsSafe boundary is HwndWrapperHook class (via HwndSource.InputFilterMessage). ///</SecurityNote> [SecurityCritical] internal void AddContext(uint index) { // We only tear down the old context when PenContexts are enabled without being // dispose and we have a valid index. Otherwise, no-op here. if (_contexts != null && index <= _contexts.Length && _inputSource.Value.CriticalHandle != IntPtr.Zero) { PenContext[] ctxs = new PenContext[_contexts.Length + 1]; uint preCopyCount = index; uint postCopyCount = (uint)_contexts.Length - index; Array.Copy(_contexts, 0, ctxs, 0, preCopyCount); PenContext newContext = _stylusLogic.TabletDevices[(int)index].CreateContext(_inputSource.Value.CriticalHandle, this); ctxs[index] = newContext; Array.Copy(_contexts, index, ctxs, index+1, postCopyCount); _contexts = ctxs; newContext.Enable(); } } ///////////////////////////////////////////////////////////////////// /// <summary> /// This method removes the specified pen context index in response /// to the WM_TABLET_REMOVED notification /// </summary> ///<SecurityNote> /// Critical - Calls SecurityCritical code (Disable and PenContext constructor) and /// accesses SecurityCritical data (_contexts). /// Called by Stylus.OnTabletRemoved. /// TreatAsSafe boundary is HwndWrapperHook class (via HwndSource.InputFilterMessage). ///</SecurityNote> [SecurityCritical] internal void RemoveContext(uint index) { // We only tear down the old context when PenContexts are enabled without being // dispose and we have a valid index. Otherwise, no-op here. if (_contexts != null && index < _contexts.Length) { PenContext removeCtx = _contexts[index]; PenContext[] ctxs = new PenContext[_contexts.Length - 1]; uint preCopyCount = index; uint postCopyCount = (uint)_contexts.Length - index - 1; Array.Copy(_contexts, 0, ctxs, 0, preCopyCount); Array.Copy(_contexts, index+1, ctxs, index, postCopyCount); removeCtx.Disable(false); // shut down this context. _contexts = ctxs; } } ///////////////////////////////////////////////////////////////////// internal object SyncRoot { get { return __rtiLock; } } internal void AddStylusPlugInCollection(StylusPlugInCollection pic) { // must be called from inside of lock(__rtiLock) // insert in ZOrder _plugInCollectionList.Insert(FindZOrderIndex(pic), pic); } internal void RemoveStylusPlugInCollection(StylusPlugInCollection pic) { // must be called from inside of lock(__rtiLock) _plugInCollectionList.Remove(pic); } internal int FindZOrderIndex(StylusPlugInCollection spicAdding) { //should be called inside of lock(__rtiLock) DependencyObject spicAddingVisual = spicAdding.Element as Visual; int i; for (i=0; i < _plugInCollectionList.Count; i++) { // first see if parent of node, if it is then we can just scan till we find the // first non parent and we're done DependencyObject curV = _plugInCollectionList[i].Element as Visual; if (VisualTreeHelper.IsAncestorOf(spicAddingVisual, curV)) { i++; while (i < _plugInCollectionList.Count) { curV = _plugInCollectionList[i].Element as Visual; if (!VisualTreeHelper.IsAncestorOf(spicAddingVisual, curV)) break; // done i++; } return i; } else { // Look to see if spicAddingVisual is higher in ZOrder than i, if so then we're done DependencyObject commonParent = VisualTreeHelper.FindCommonAncestor(spicAddingVisual, curV); // If no common parent found then we must have multiple plugincollection elements // that have been removed from the visual tree and we haven't been notified yet of // that change. In this case just ignore this plugincollection element and go to // the next. if (commonParent == null) continue; // If curV is the commonParent we find then we're done. This new plugin should be // above this one. if (curV == commonParent) return i; // now find first child for each under that common visual that these fall under (not they must be different or common parent is sort of busted. while (VisualTreeHelper.GetParentInternal(spicAddingVisual) != commonParent) spicAddingVisual = VisualTreeHelper.GetParentInternal(spicAddingVisual); while (VisualTreeHelper.GetParentInternal(curV) != commonParent) curV = VisualTreeHelper.GetParentInternal(curV); // now see which is higher in zorder int count = VisualTreeHelper.GetChildrenCount(commonParent); for (int j = 0; j < count; j++) { DependencyObject child = VisualTreeHelper.GetChild(commonParent, j); if (child == spicAddingVisual) return i; else if (child == curV) break; // look at next index in _piList. } } } return i; // this wasn't higher so return last index. } /// <SecurityNote> /// Critical - Calls into security critical code TargetPlugInCollection. /// Called by StylusLogic.CallPluginsForMouse. /// TreatAsSafe boundary is mainly PenThread.ThreadProc and HwndWrapperHook class (via HwndSource.InputFilterMessage). /// It can also be called via anyone with priviledge to call InputManager.ProcessInput(). /// </SecurityNote> [SecurityCritical] internal StylusPlugInCollection InvokeStylusPluginCollectionForMouse(RawStylusInputReport inputReport, IInputElement directlyOver, StylusPlugInCollection currentPlugInCollection) { StylusPlugInCollection newPlugInCollection = null; // lock to make sure only one event is processed at a time and no changes to state can // be made until we finish routing this event. lock(__rtiLock) { //Debug.Assert(inputReport.Actions == RawStylusActions.Down || // inputReport.Actions == RawStylusActions.Up || // inputReport.Actions == RawStylusActions.Move); // Find new target plugin collection if (directlyOver != null) { UIElement uiElement = InputElement.GetContainingUIElement(directlyOver as DependencyObject) as UIElement; if (uiElement != null) { newPlugInCollection = FindPlugInCollection(uiElement); } } // Fire Leave event to old pluginCollection if we need to. if (currentPlugInCollection != null && currentPlugInCollection != newPlugInCollection) { // NOTE: input report points for mouse are in avalon measured units and not device! RawStylusInput tempRawStylusInput = new RawStylusInput(inputReport, currentPlugInCollection.ViewToElement, currentPlugInCollection); currentPlugInCollection.FireEnterLeave(false, tempRawStylusInput, true); } if (newPlugInCollection != null) { // NOTE: input report points for mouse are in avalon measured units and not device! RawStylusInput rawStylusInput = new RawStylusInput(inputReport, newPlugInCollection.ViewToElement, newPlugInCollection); inputReport.RawStylusInput = rawStylusInput; if (newPlugInCollection != currentPlugInCollection) { newPlugInCollection.FireEnterLeave(true, rawStylusInput, true); } // We are on the pen thread, just call directly. newPlugInCollection.FireRawStylusInput(rawStylusInput); // Fire custom data events (always confirmed for mouse) foreach (RawStylusInputCustomData customData in rawStylusInput.CustomDataList) { customData.Owner.FireCustomData(customData.Data, inputReport.Actions, true); } } } return newPlugInCollection; } /// <SecurityNote> /// Critical - Calls into security critical code TargetPlugInCollection. /// Called by StylusLogic.InvokeStylusPluginCollection. /// TreatAsSafe boundary is mainly PenThread.ThreadProc and HwndWrapperHook class (via HwndSource.InputFilterMessage). /// It can also be called via anyone with priviledge to call InputManager.ProcessInput(). /// </SecurityNote> [SecurityCritical] internal void InvokeStylusPluginCollection(RawStylusInputReport inputReport) { // Find PenContexts object for this inputReport. StylusPlugInCollection pic = null; // lock to make sure only one event is processed at a time and no changes to state can // be made until we finish routing this event. lock(__rtiLock) { switch (inputReport.Actions) { case RawStylusActions.Down: case RawStylusActions.Move: case RawStylusActions.Up: // Figure out current target plugincollection. pic = TargetPlugInCollection(inputReport); break; default: return; // Nothing to do unless one of the above events } StylusPlugInCollection currentPic = inputReport.StylusDevice.CurrentNonVerifiedTarget; // Fire Leave event if we need to. if (currentPic != null && currentPic != pic) { // Create new RawStylusInput to send GeneralTransformGroup transformTabletToView = new GeneralTransformGroup(); transformTabletToView.Children.Add(new MatrixTransform(_stylusLogic.GetTabletToViewTransform(inputReport.StylusDevice.TabletDevice))); // this gives matrix in measured units (not device) transformTabletToView.Children.Add(currentPic.ViewToElement); // Make it relative to the element. transformTabletToView.Freeze(); // Must be frozen for multi-threaded access. RawStylusInput tempRawStylusInput = new RawStylusInput(inputReport, transformTabletToView, currentPic); currentPic.FireEnterLeave(false, tempRawStylusInput, false); inputReport.StylusDevice.CurrentNonVerifiedTarget = null; } if (pic != null) { // NOTE: PenContext info will not change (it gets rebuilt instead so keeping ref is fine) // The transformTabletToView matrix and plugincollection rects though can change based // off of layout events which is why we need to lock this. GeneralTransformGroup transformTabletToView = new GeneralTransformGroup(); transformTabletToView.Children.Add(new MatrixTransform(_stylusLogic.GetTabletToViewTransform(inputReport.StylusDevice.TabletDevice))); // this gives matrix in measured units (not device) transformTabletToView.Children.Add(pic.ViewToElement); // Make it relative to the element. transformTabletToView.Freeze(); // Must be frozen for multi-threaded access. RawStylusInput rawStylusInput = new RawStylusInput(inputReport, transformTabletToView, pic); inputReport.RawStylusInput = rawStylusInput; if (pic != currentPic) { inputReport.StylusDevice.CurrentNonVerifiedTarget = pic; pic.FireEnterLeave(true, rawStylusInput, false); } // We are on the pen thread, just call directly. pic.FireRawStylusInput(rawStylusInput); } } // lock(__rtiLock) } /// <SecurityNote> /// Critical - InputReport.InputSource has a LinkDemand so we need to be SecurityCritical. /// Called by InvokeStylusPluginCollection. /// TreatAsSafe boundary is mainly PenThread.ThreadProc and HwndWrapperHook class (via HwndSource.InputFilterMessage). /// It can also be called via anyone with priviledge to call InputManager.ProcessInput(). /// </SecurityNote> [SecurityCritical] internal StylusPlugInCollection TargetPlugInCollection(RawStylusInputReport inputReport) { // Caller must make call to this routine inside of lock(__rtiLock)! StylusPlugInCollection pic = null; // We should only be called when not on the application thread! System.Diagnostics.Debug.Assert(!inputReport.StylusDevice.CheckAccess()); // We're on the pen thread so can't touch visual tree. Use capturedPlugIn (if capture on) or cached rects. bool elementHasCapture = false; pic = inputReport.StylusDevice.GetCapturedPlugInCollection(ref elementHasCapture); int pointLength = inputReport.PenContext.StylusPointDescription.GetInputArrayLengthPerPoint(); // Make sure that the captured Plugin Collection is still in the list. CaptureChanges are // deferred so there is a window where the stylus device is not updated yet. This protects us // from using a bogus plugin collecton for an element that is in an invalid state. if (elementHasCapture && !_plugInCollectionList.Contains(pic)) { elementHasCapture = false; // force true hittesting to be done! } if (!elementHasCapture && inputReport.Data != null && inputReport.Data.Length >= pointLength) { int[] data = inputReport.Data; System.Diagnostics.Debug.Assert(data.Length % pointLength == 0); Point ptTablet = new Point(data[data.Length - pointLength], data[data.Length - pointLength + 1]); // Note: the StylusLogic data inside DeviceUnitsFromMeasurUnits is protected by __rtiLock. ptTablet = ptTablet * inputReport.StylusDevice.TabletDevice.TabletToScreen; ptTablet.X = (int)Math.Round(ptTablet.X); // Make sure we snap to whole window pixels. ptTablet.Y = (int)Math.Round(ptTablet.Y); ptTablet = _stylusLogic.MeasureUnitsFromDeviceUnits(ptTablet); // change to measured units now. pic = HittestPlugInCollection(ptTablet); // Use cached rectangles for UIElements. } return pic; } ///////////////////////////////////////////////////////////////////// // NOTE: this should only be called inside of app Dispatcher internal StylusPlugInCollection FindPlugInCollection(UIElement element) { // Since we are only called on app Dispatcher this cannot change out from under us. // System.Diagnostics.Debug.Assert(_stylusLogic.Dispatcher.CheckAccess()); foreach (StylusPlugInCollection plugInCollection in _plugInCollectionList) { // If same element or element is child of the plugincollection element than say we hit it. if (plugInCollection.Element == element || (plugInCollection.Element as Visual).IsAncestorOf(element as Visual)) { return plugInCollection; } } return null; } ///////////////////////////////////////////////////////////////////// // NOTE: this is called on pen thread (outside of apps Dispatcher) StylusPlugInCollection HittestPlugInCollection(Point pt) { // Caller must make call to this routine inside of lock(__rtiLock)! foreach (StylusPlugInCollection plugInCollection in _plugInCollectionList) { if (plugInCollection.IsHit(pt)) { return plugInCollection; } } return null; } ///////////////////////////////////////////////////////////////////// ///<SecurityNote> /// Critical - PresentationSource is critical ///</SecurityNote> internal SecurityCriticalData<HwndSource> _inputSource; /// <SecurityNote> /// Critical to prevent accidental spread to transparent code /// </SecurityNote> [SecurityCritical] StylusLogic _stylusLogic; object __rtiLock = new object(); List<StylusPlugInCollection> _plugInCollectionList = new List<StylusPlugInCollection>(); /// <SecurityNote> /// Critical to prevent accidental spread to transparent code /// </SecurityNote> [SecurityCritical] PenContext[] _contexts; bool _isWindowDisabled; Point _destroyedLocation = new Point(0,0); } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Data.SqlClient; using System.Data.OleDb; using System.Data.Odbc; using System.Data.OracleClient; using System.Data.Common; namespace Rainbow.Framwork.Data { /// <summary> /// Summary description for ParameterCache /// </summary> /// <summary> /// ParameterCache provides functions to leverage a static cache of procedure parameters, and the /// ability to discover parameters for stored procedures at run-time. /// </summary> internal static class ParameterCache { #region private methods, variables, and constructors private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable()); /// <summary> /// Resolve at run time the appropriate set of DbParameters for a stored procedure /// </summary> /// <param name="connection">A valid DbConnection object</param> /// <param name="spName">The name of the stored procedure</param> /// <param name="includeReturnValueParameter">Whether or not to include their return value parameter</param> /// <returns>The parameter array discovered.</returns> private static DbParameter[] DiscoverSpParameterSet(DbConnection connection, string spName, bool includeReturnValueParameter) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); DbCommand cmd = connection.CreateCommand(); cmd.CommandText = spName; cmd.CommandType = CommandType.StoredProcedure; connection.Open(); if (connection is SqlConnection) { SqlCommandBuilder.DeriveParameters((SqlCommand)cmd); } else if(connection is OracleConnection) { OracleCommandBuilder.DeriveParameters((OracleCommand)cmd); } else if (connection is OdbcConnection) { OdbcCommandBuilder.DeriveParameters((OdbcCommand)cmd); } else if (connection is OleDbConnection) { OleDbCommandBuilder.DeriveParameters((OleDbCommand)cmd); } connection.Close(); if (!includeReturnValueParameter) { cmd.Parameters.RemoveAt(0); } DbParameter[] discoveredParameters = new DbParameter[cmd.Parameters.Count]; cmd.Parameters.CopyTo(discoveredParameters, 0); // Init the parameters with a DBNull value foreach (DbParameter discoveredParameter in discoveredParameters) { discoveredParameter.Value = DBNull.Value; } return discoveredParameters; } /// <summary> /// Deep copy of cached DbParameter array /// </summary> /// <param name="originalParameters"></param> /// <returns></returns> private static DbParameter[] CloneParameters(DbParameter[] originalParameters) { DbParameter[] clonedParameters = new DbParameter[originalParameters.Length]; for (int i = 0, j = originalParameters.Length; i < j; i++) { clonedParameters[i] = (DbParameter)((ICloneable)originalParameters[i]).Clone(); } return clonedParameters; } #endregion private methods, variables, and constructors #region caching functions /// <summary> /// Add parameter array to the cache /// </summary> /// <param name="connectionString">A valid connection string for a DbConnection</param> /// <param name="commandText">The stored procedure name or T-SQL command</param> /// <param name="commandParameters">An array of SqlParamters to be cached</param> public static void CacheParameterSet(string connectionString, string commandText, params DbParameter[] commandParameters) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText"); string hashKey = connectionString + ":" + commandText; paramCache[hashKey] = commandParameters; } /// <summary> /// Retrieve a parameter array from the cache /// </summary> /// <param name="connectionString">A valid connection string for a DbConnection</param> /// <param name="commandText">The stored procedure name or T-SQL command</param> /// <returns>An array of SqlParamters</returns> public static DbParameter[] GetCachedParameterSet(string connectionString, string commandText) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText"); string hashKey = connectionString + ":" + commandText; SqlParameter[] cachedParameters = paramCache[hashKey] as SqlParameter[]; if (cachedParameters == null) { return null; } else { return CloneParameters(cachedParameters); } } #endregion caching functions #region Parameter Discovery Functions /// <summary> /// Retrieves the set of DbParameters appropriate for the stored procedure /// </summary> /// <remarks> /// This method will query the database for this information, and then store it in a cache for future requests. /// </remarks> /// <param name="factory">DbProviderFactory object to be used to create provider specific connection object</param> /// <param name="connectionString">A valid connection string for a DbConnection</param> /// <param name="spName">The name of the stored procedure</param> /// <returns>An array of DbParameters</returns> public static DbParameter[] GetSpParameterSet(DbProviderFactory factory, string connectionString, string spName) { return GetSpParameterSet(factory, connectionString, spName, false); } /// <summary> /// Retrieves the set of DbParameters appropriate for the stored procedure /// </summary> /// <remarks> /// This method will query the database for this information, and then store it in a cache for future requests. /// </remarks> /// <param name="factory">DbProviderFactory object to be used to create provider specific connection object</param> /// <param name="connectionString">A valid connection string for a bConnection</param> /// <param name="spName">The name of the stored procedure</param> /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param> /// <returns>An array of DbParameters</returns> public static DbParameter[] GetSpParameterSet(DbProviderFactory factory, string connectionString, string spName, bool includeReturnValueParameter) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); using (DbConnection connection = factory.CreateConnection()) { connection.ConnectionString = connectionString; return GetSpParameterSetInternal(connection, spName, includeReturnValueParameter); } } /// <summary> /// Retrieves the set of DbParameters appropriate for the stored procedure /// </summary> /// <remarks> /// This method will query the database for this information, and then store it in a cache for future requests. /// </remarks> /// <param name="connection">A valid DbConnection object</param> /// <param name="spName">The name of the stored procedure</param> /// <returns>An array of DbParameters</returns> internal static DbParameter[] GetSpParameterSet(DbConnection connection, string spName) { return GetSpParameterSet(connection, spName, false); } /// <summary> /// Retrieves the set of SqlParameters appropriate for the stored procedure /// </summary> /// <remarks> /// This method will query the database for this information, and then store it in a cache for future requests. /// </remarks> /// <param name="connection">A valid SqlConnection object</param> /// <param name="spName">The name of the stored procedure</param> /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param> /// <returns>An array of SqlParameters</returns> internal static DbParameter[] GetSpParameterSet(DbConnection connection, string spName, bool includeReturnValueParameter) { if (connection == null) throw new ArgumentNullException("connection"); using (DbConnection clonedConnection = (DbConnection)((ICloneable)connection).Clone()) { return GetSpParameterSetInternal(clonedConnection, spName, includeReturnValueParameter); } } /// <summary> /// Retrieves the set of DbParameters appropriate for the stored procedure /// </summary> /// <param name="connection">A valid DbConnection object</param> /// <param name="spName">The name of the stored procedure</param> /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param> /// <returns>An array of DbParameters</returns> private static DbParameter[] GetSpParameterSetInternal(DbConnection connection, string spName, bool includeReturnValueParameter) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); string hashKey = connection.ConnectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter" : ""); DbParameter[] cachedParameters; cachedParameters = paramCache[hashKey] as DbParameter[]; if (cachedParameters == null) { DbParameter[] spParameters = DiscoverSpParameterSet(connection, spName, includeReturnValueParameter); paramCache[hashKey] = spParameters; cachedParameters = spParameters; } return CloneParameters(cachedParameters); } #endregion Parameter Discovery Functions } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using System; using System.ComponentModel; using System.Threading; using Common; using Internal; using System.Collections.Generic; /// <summary> /// Provides asynchronous, buffered execution of target writes. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/AsyncWrapper-target">Documentation on NLog Wiki</seealso> /// <remarks> /// <p> /// Asynchronous target wrapper allows the logger code to execute more quickly, by queueing /// messages and processing them in a separate thread. You should wrap targets /// that spend a non-trivial amount of time in their Write() method with asynchronous /// target to speed up logging. /// </p> /// <p> /// Because asynchronous logging is quite a common scenario, NLog supports a /// shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to /// the &lt;targets/&gt; element in the configuration file. /// </p> /// <code lang="XML"> /// <![CDATA[ /// <targets async="true"> /// ... your targets go here ... /// </targets> /// ]]></code> /// </remarks> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/AsyncWrapper/NLog.config" /> /// <p> /// The above examples assume just one target and a single rule. See below for /// a programmatic configuration that's equivalent to the above config file: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/AsyncWrapper/Wrapping File/Example.cs" /> /// </example> [Target("AsyncWrapper", IsWrapper = true)] public class AsyncTargetWrapper : WrapperTargetBase { private readonly object lockObject = new object(); private Timer lazyWriterTimer; private readonly Queue<AsyncContinuation> flushAllContinuations = new Queue<AsyncContinuation>(); private readonly object continuationQueueLock = new object(); /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> public AsyncTargetWrapper() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> public AsyncTargetWrapper(Target wrappedTarget) : this(wrappedTarget, 10000, AsyncTargetWrapperOverflowAction.Discard) { } /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="queueLimit">Maximum number of requests in the queue.</param> /// <param name="overflowAction">The action to be taken when the queue overflows.</param> public AsyncTargetWrapper(Target wrappedTarget, int queueLimit, AsyncTargetWrapperOverflowAction overflowAction) { this.RequestQueue = new AsyncRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard); this.TimeToSleepBetweenBatches = 50; this.BatchSize = 100; this.WrappedTarget = wrappedTarget; this.QueueLimit = queueLimit; this.OverflowAction = overflowAction; } /// <summary> /// Gets or sets the number of log events that should be processed in a batch /// by the lazy writer thread. /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(100)] public int BatchSize { get; set; } /// <summary> /// Gets or sets the time in milliseconds to sleep between batches. /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(50)] public int TimeToSleepBetweenBatches { get; set; } /// <summary> /// Gets or sets the action to be taken when the lazy writer thread request queue count /// exceeds the set limit. /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue("Discard")] public AsyncTargetWrapperOverflowAction OverflowAction { get { return this.RequestQueue.OnOverflow; } set { this.RequestQueue.OnOverflow = value; } } /// <summary> /// Gets or sets the limit on the number of requests in the lazy writer thread request queue. /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(10000)] public int QueueLimit { get { return this.RequestQueue.RequestLimit; } set { this.RequestQueue.RequestLimit = value; } } /// <summary> /// Gets the queue of lazy writer thread requests. /// </summary> internal AsyncRequestQueue RequestQueue { get; private set; } /// <summary> /// Waits for the lazy writer thread to finish writing messages. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { lock (continuationQueueLock) { this.flushAllContinuations.Enqueue(asyncContinuation); } } /// <summary> /// Initializes the target by starting the lazy writer timer. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); this.RequestQueue.Clear(); this.lazyWriterTimer = new Timer(this.ProcessPendingEvents, null, Timeout.Infinite, Timeout.Infinite); this.StartLazyWriterTimer(); } /// <summary> /// Shuts down the lazy writer timer. /// </summary> protected override void CloseTarget() { this.StopLazyWriterThread(); if (this.RequestQueue.RequestCount > 0) { ProcessPendingEvents(null); } base.CloseTarget(); } /// <summary> /// Starts the lazy writer thread which periodically writes /// queued log messages. /// </summary> protected virtual void StartLazyWriterTimer() { lock (this.lockObject) { if (this.lazyWriterTimer != null) { this.lazyWriterTimer.Change(this.TimeToSleepBetweenBatches, Timeout.Infinite); } } } /// <summary> /// Starts the lazy writer thread. /// </summary> protected virtual void StopLazyWriterThread() { lock (this.lockObject) { if (this.lazyWriterTimer != null) { this.lazyWriterTimer.Change(Timeout.Infinite, Timeout.Infinite); this.lazyWriterTimer = null; } } } /// <summary> /// Adds the log event to asynchronous queue to be processed by /// the lazy writer thread. /// </summary> /// <param name="logEvent">The log event.</param> /// <remarks> /// The <see cref="Target.PrecalculateVolatileLayouts"/> is called /// to ensure that the log event can be processed in another thread. /// </remarks> protected override void Write(AsyncLogEventInfo logEvent) { this.MergeEventProperties(logEvent.LogEvent); this.PrecalculateVolatileLayouts(logEvent.LogEvent); this.RequestQueue.Enqueue(logEvent); } private void ProcessPendingEvents(object state) { AsyncContinuation[] continuations; lock (this.continuationQueueLock) { continuations = this.flushAllContinuations.Count > 0 ? this.flushAllContinuations.ToArray() : new AsyncContinuation[] { null }; this.flushAllContinuations.Clear(); } try { foreach (var continuation in continuations) { int count = this.BatchSize; if (continuation != null) { count = this.RequestQueue.RequestCount; InternalLogger.Trace("Flushing {0} events.", count); } if (this.RequestQueue.RequestCount == 0) { if (continuation != null) { continuation(null); } } AsyncLogEventInfo[] logEventInfos = this.RequestQueue.DequeueBatch(count); if (continuation != null) { // write all events, then flush, then call the continuation this.WrappedTarget.WriteAsyncLogEvents(logEventInfos, ex => this.WrappedTarget.Flush(continuation)); } else { // just write all events this.WrappedTarget.WriteAsyncLogEvents(logEventInfos); } } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error in lazy writer timer procedure: {0}", exception); } finally { this.StartLazyWriterTimer(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class CtorTests { [Fact] public static void TestDefaultConstructor() { using (X509Certificate2 c = new X509Certificate2()) { VerifyDefaultConstructor(c); } } private static void VerifyDefaultConstructor(X509Certificate2 c) { IntPtr h = c.Handle; object ignored; Assert.Equal(IntPtr.Zero, h); Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash()); Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithm()); Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParameters()); Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParametersString()); Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKey()); Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumber()); Assert.ThrowsAny<CryptographicException>(() => ignored = c.Issuer); Assert.ThrowsAny<CryptographicException>(() => ignored = c.Subject); Assert.ThrowsAny<CryptographicException>(() => ignored = c.RawData); Assert.ThrowsAny<CryptographicException>(() => ignored = c.Thumbprint); Assert.ThrowsAny<CryptographicException>(() => ignored = c.SignatureAlgorithm); Assert.ThrowsAny<CryptographicException>(() => ignored = c.HasPrivateKey); Assert.ThrowsAny<CryptographicException>(() => ignored = c.Version); Assert.ThrowsAny<CryptographicException>(() => ignored = c.Archived); Assert.ThrowsAny<CryptographicException>(() => c.Archived = false); Assert.ThrowsAny<CryptographicException>(() => c.FriendlyName = "Hi"); Assert.ThrowsAny<CryptographicException>(() => ignored = c.SubjectName); Assert.ThrowsAny<CryptographicException>(() => ignored = c.IssuerName); Assert.ThrowsAny<CryptographicException>(() => c.GetCertHashString()); Assert.ThrowsAny<CryptographicException>(() => c.GetEffectiveDateString()); Assert.ThrowsAny<CryptographicException>(() => c.GetExpirationDateString()); Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKeyString()); Assert.ThrowsAny<CryptographicException>(() => c.GetRawCertData()); Assert.ThrowsAny<CryptographicException>(() => c.GetRawCertDataString()); Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumberString()); #pragma warning disable 0618 Assert.ThrowsAny<CryptographicException>(() => c.GetIssuerName()); Assert.ThrowsAny<CryptographicException>(() => c.GetName()); #pragma warning restore 0618 } [Fact] public static void TestConstructor_DER() { byte[] expectedThumbPrint = new byte[] { 0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c, 0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a, 0xc3, 0x13, 0x87, 0xfe, }; Action<X509Certificate2> assert = (c) => { IntPtr h = c.Handle; Assert.NotEqual(IntPtr.Zero, h); byte[] actualThumbprint = c.GetCertHash(); Assert.Equal(expectedThumbPrint, actualThumbprint); }; using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate)) { assert(c); using (X509Certificate2 c2 = new X509Certificate2(c)) { assert(c2); } } } [Fact] public static void TestConstructor_PEM() { byte[] expectedThumbPrint = { 0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c, 0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a, 0xc3, 0x13, 0x87, 0xfe, }; Action<X509Certificate2> assert = (cert) => { IntPtr h = cert.Handle; Assert.NotEqual(IntPtr.Zero, h); byte[] actualThumbprint = cert.GetCertHash(); Assert.Equal(expectedThumbPrint, actualThumbprint); }; using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificatePemBytes)) { assert(c); using (X509Certificate2 c2 = new X509Certificate2(c)) { assert(c2); } } } [Fact] public static void TestSerializeDeserialize_DER() { byte[] expectedThumbPrint = new byte[] { 0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c, 0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a, 0xc3, 0x13, 0x87, 0xfe, }; Action<X509Certificate2> assert = (c) => { IntPtr h = c.Handle; Assert.NotEqual(IntPtr.Zero, h); byte[] actualThumbprint = c.GetCertHash(); Assert.Equal(expectedThumbPrint, actualThumbprint); }; using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate)) { assert(c); using (X509Certificate2 c2 = System.Runtime.Serialization.Formatters.Tests.BinaryFormatterHelpers.Clone(c)) { assert(c2); } } } [Fact] public static void TestCopyConstructor_NoPal() { using (var c1 = new X509Certificate2()) using (var c2 = new X509Certificate2(c1)) { VerifyDefaultConstructor(c1); VerifyDefaultConstructor(c2); } } [Fact] public static void TestSerializeDeserialize_NoPal() { using (var c1 = new X509Certificate2()) using (var c2 = System.Runtime.Serialization.Formatters.Tests.BinaryFormatterHelpers.Clone(c1)) { VerifyDefaultConstructor(c1); VerifyDefaultConstructor(c2); } } [Fact] public static void TestCopyConstructor_Pal() { using (var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) using (var c2 = new X509Certificate2(c1)) { Assert.Equal(c1.GetCertHash(), c2.GetCertHash()); Assert.Equal(c1.GetKeyAlgorithm(), c2.GetKeyAlgorithm()); Assert.Equal(c1.GetKeyAlgorithmParameters(), c2.GetKeyAlgorithmParameters()); Assert.Equal(c1.GetKeyAlgorithmParametersString(), c2.GetKeyAlgorithmParametersString()); Assert.Equal(c1.GetPublicKey(), c2.GetPublicKey()); Assert.Equal(c1.GetSerialNumber(), c2.GetSerialNumber()); Assert.Equal(c1.Issuer, c2.Issuer); Assert.Equal(c1.Subject, c2.Subject); Assert.Equal(c1.RawData, c2.RawData); Assert.Equal(c1.Thumbprint, c2.Thumbprint); Assert.Equal(c1.SignatureAlgorithm.Value, c2.SignatureAlgorithm.Value); Assert.Equal(c1.HasPrivateKey, c2.HasPrivateKey); Assert.Equal(c1.Version, c2.Version); Assert.Equal(c1.Archived, c2.Archived); Assert.Equal(c1.SubjectName.Name, c2.SubjectName.Name); Assert.Equal(c1.IssuerName.Name, c2.IssuerName.Name); Assert.Equal(c1.GetCertHashString(), c2.GetCertHashString()); Assert.Equal(c1.GetEffectiveDateString(), c2.GetEffectiveDateString()); Assert.Equal(c1.GetExpirationDateString(), c2.GetExpirationDateString()); Assert.Equal(c1.GetPublicKeyString(), c2.GetPublicKeyString()); Assert.Equal(c1.GetRawCertData(), c2.GetRawCertData()); Assert.Equal(c1.GetRawCertDataString(), c2.GetRawCertDataString()); Assert.Equal(c1.GetSerialNumberString(), c2.GetSerialNumberString()); #pragma warning disable 0618 Assert.Equal(c1.GetIssuerName(), c2.GetIssuerName()); Assert.Equal(c1.GetName(), c2.GetName()); #pragma warning restore 0618 } } [Fact] public static void TestCopyConstructor_Lifetime_Independent() { var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword); using (var c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { RSA rsa = c2.GetRSAPrivateKey(); byte[] hash = new byte[20]; byte[] sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig); c1.Dispose(); rsa.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); // Verify other cert and previous key do not affect cert using (rsa = c2.GetRSAPrivateKey()) { hash = new byte[20]; sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig); } } } [Fact] public static void TestCopyConstructor_Lifetime_Cloned() { var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword); var c2 = new X509Certificate2(c1); TestPrivateKey(c1, true); TestPrivateKey(c2, true); c1.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); TestPrivateKey(c1, false); TestPrivateKey(c2, true); c2.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); TestPrivateKey(c2, false); } [Fact] public static void TestCopyConstructor_Lifetime_Cloned_Reversed() { var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword); var c2 = new X509Certificate2(c1); TestPrivateKey(c1, true); TestPrivateKey(c2, true); c2.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); TestPrivateKey(c1, true); TestPrivateKey(c2, false); c1.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); TestPrivateKey(c1, false); } private static void TestPrivateKey(X509Certificate2 c, bool expectSuccess) { if (expectSuccess) { using (RSA rsa = c.GetRSAPrivateKey()) { byte[] hash = new byte[20]; byte[] sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig); } } else { Assert.ThrowsAny<CryptographicException>(() => c.GetRSAPrivateKey()); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // StoreSavedAsSerializedCerData not supported on Unix public static void TestConstructor_SerializedCert_Windows() { const string ExpectedThumbPrint = "71CB4E2B02738AD44F8B382C93BD17BA665F9914"; Action<X509Certificate2> assert = (cert) => { IntPtr h = cert.Handle; Assert.NotEqual(IntPtr.Zero, h); Assert.Equal(ExpectedThumbPrint, cert.Thumbprint); }; using (X509Certificate2 c = new X509Certificate2(TestData.StoreSavedAsSerializedCerData)) { assert(c); using (X509Certificate2 c2 = new X509Certificate2(c)) { assert(c2); } } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // StoreSavedAsSerializedCerData not supported on Unix public static void TestByteArrayConstructor_SerializedCert_Unix() { Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.StoreSavedAsSerializedCerData)); } [Fact] public static void TestNullConstructorArguments() { Assert.Throws<ArgumentNullException>(() => new X509Certificate2((string)null)); Assert.Throws<ArgumentException>(() => new X509Certificate2(IntPtr.Zero)); Assert.Throws<ArgumentException>(() => new X509Certificate2((byte[])null, (string)null)); Assert.Throws<ArgumentException>(() => new X509Certificate2(Array.Empty<byte>(), (string)null)); Assert.Throws<ArgumentException>(() => new X509Certificate2((byte[])null, (string)null, X509KeyStorageFlags.DefaultKeySet)); Assert.Throws<ArgumentException>(() => new X509Certificate2(Array.Empty<byte>(), (string)null, X509KeyStorageFlags.DefaultKeySet)); // A null string password does not throw using (new X509Certificate2(TestData.MsCertificate, (string)null)) { } using (new X509Certificate2(TestData.MsCertificate, (string)null, X509KeyStorageFlags.DefaultKeySet)) { } Assert.Throws<ArgumentNullException>(() => X509Certificate.CreateFromCertFile(null)); Assert.Throws<ArgumentNullException>(() => X509Certificate.CreateFromSignedFile(null)); AssertExtensions.Throws<ArgumentNullException>("cert", () => new X509Certificate2((X509Certificate2)null)); AssertExtensions.Throws<ArgumentException>("handle", () => new X509Certificate2(IntPtr.Zero)); // A null SecureString password does not throw using (new X509Certificate2(TestData.MsCertificate, (SecureString)null)) { } using (new X509Certificate2(TestData.MsCertificate, (SecureString)null, X509KeyStorageFlags.DefaultKeySet)) { } // For compat reasons, the (byte[]) constructor (and only that constructor) treats a null or 0-length array as the same // as calling the default constructor. { using (X509Certificate2 c = new X509Certificate2((byte[])null)) { IntPtr h = c.Handle; Assert.Equal(IntPtr.Zero, h); Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash()); } } { using (X509Certificate2 c = new X509Certificate2(Array.Empty<byte>())) { IntPtr h = c.Handle; Assert.Equal(IntPtr.Zero, h); Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash()); } } } [Fact] public static void InvalidCertificateBlob() { CryptographicException ex = Assert.ThrowsAny<CryptographicException>( () => new X509Certificate2(new byte[] { 0x01, 0x02, 0x03 })); CryptographicException defaultException = new CryptographicException(); Assert.NotEqual(defaultException.Message, ex.Message); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(unchecked((int)0x80092009), ex.HResult); // TODO (3233): Test that Message is also set correctly //Assert.Equal("Cannot find the requested object.", ex.Message); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Assert.Equal(-25257, ex.HResult); } else // Any Unix { Assert.Equal(0x0D07803A, ex.HResult); Assert.Equal("error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error", ex.Message); } } [Fact] public static void InvalidStorageFlags() { byte[] nonEmptyBytes = new byte[1]; Assert.Throws<ArgumentException>( "keyStorageFlags", () => new X509Certificate(nonEmptyBytes, string.Empty, (X509KeyStorageFlags)0xFF)); Assert.Throws<ArgumentException>( "keyStorageFlags", () => new X509Certificate(string.Empty, string.Empty, (X509KeyStorageFlags)0xFF)); Assert.Throws<ArgumentException>( "keyStorageFlags", () => new X509Certificate2(nonEmptyBytes, string.Empty, (X509KeyStorageFlags)0xFF)); Assert.Throws<ArgumentException>( "keyStorageFlags", () => new X509Certificate2(string.Empty, string.Empty, (X509KeyStorageFlags)0xFF)); // No test is performed here for the ephemeral flag failing downlevel, because the live // binary is always used by default, meaning it doesn't know EphemeralKeySet doesn't exist. } #if netcoreapp [Fact] public static void InvalidStorageFlags_PersistedEphemeral() { const X509KeyStorageFlags PersistedEphemeral = X509KeyStorageFlags.EphemeralKeySet | X509KeyStorageFlags.PersistKeySet; byte[] nonEmptyBytes = new byte[1]; Assert.Throws<ArgumentException>( "keyStorageFlags", () => new X509Certificate(nonEmptyBytes, string.Empty, PersistedEphemeral)); Assert.Throws<ArgumentException>( "keyStorageFlags", () => new X509Certificate(string.Empty, string.Empty, PersistedEphemeral)); Assert.Throws<ArgumentException>( "keyStorageFlags", () => new X509Certificate2(nonEmptyBytes, string.Empty, PersistedEphemeral)); Assert.Throws<ArgumentException>( "keyStorageFlags", () => new X509Certificate2(string.Empty, string.Empty, PersistedEphemeral)); } #endif } }
#region License /* ********************************************************************************** * Copyright (c) Robert Nees (https://github.com/sushihangover/Irony) * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ //Original Windows.Form Version by Roman Ivantsov //with Windows.Form contributions by Andrew Bradnan and Alexey Yakovlev #endregion using Gtk; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using System.Reflection; using System.Linq; using Mono.TextEditor; using Mono.TextEditor.Highlighting; using Medsphere.Widgets; using Pinta.Core; using IgeMacIntegration; using Irony.Ast; using Irony.Parsing; using Irony.GrammarExplorer; using Irony.Interpreter; namespace Irony.GrammarExplorer { // Settings conflict with Gtk.Settings using MyApp = Irony.GrammarExplorer.Properties; public partial class MainWindow: Gtk.Window { // UI vars private bool _fullScreen; private GridView _gridCompileErrors; private GridView _gridParserTrace; private TextEditor _teEditor; private TextEditor _txtTerms; private TextEditor _txtNonTerms; private TextEditor _txtParserStates; // Mono.TextEditor Syntax Modes (XML resources plus the addition of dymanic keywords private IronySyntaxMode _IronySyntaxMode; private IronyParserStatesSyntaxMode _IronyParserStatesSyntaxMode; private System.Text.RegularExpressions.Regex _regexCleanWhiteSpace = new System.Text.RegularExpressions.Regex (@" [ ]{2,}", RegexOptions.None); // Irony vars private Grammar _grammar; private LanguageData _language; private Parser _parser; private ParseTree _parseTree; private ScriptException _runtimeError; private GrammarLoader _grammarLoader = new GrammarLoader (); bool _loaded; public MainWindow () : base (Gtk.WindowType.Toplevel) { _teEditor = new TextEditor (); _txtTerms = new TextEditor (); _txtNonTerms = new TextEditor (); _txtParserStates = new TextEditor (); Build (); _grammarLoader.AssemblyUpdated += GrammarAssemblyUpdated; // Setup GTK Models(listStore) as no way to do this in MonoDevelop/Stetic, so dumb...yuk.... SetupModel_gridGrammarErrors (); SetupModel_gridCompileErrors (); SetupModel_cboGrammars (); SetModel_gridParserTrace (); SetModel_lstTokens (); SetupModel_btnManageGrammars (); SetupModel_tvParseTree (); SetupModel_tvAST (); SetOSX_Menus (); try { swEditor.Child = _teEditor; TextEditorOptions overrideOptions = new TextEditorOptions (); _teEditor.Options = overrideOptions; _teEditor.Options.ColorScheme = "Default"; _teEditor.Options.ShowIconMargin = false; _teEditor.Options.ShowFoldMargin = false; _teEditor.Options.ShowRuler = false; _teEditor.Options.WrapLines = true; _teEditor.SelectionChanged += (object sender, EventArgs e) => OnBtnLocateClicked(sender, e); swEditor.ShowAll (); sWinTerminals.Child = _txtTerms; sWinTerminals.ShowAll (); _txtTerms.Document.ReadOnly = true; // ColorScheme of the TextEditor.Options = "Default, TangoLight, Visual Studio, IrBlack, GEdit, Brown, C64, Oblivion" _txtTerms.Options.ColorScheme = "Default"; _txtTerms.Options.ShowIconMargin = false; _txtTerms.Options.ShowFoldMargin = false; _txtTerms.Options.ShowRuler = false; sWinNonTerminals.Child = _txtNonTerms; sWinNonTerminals.ShowAll (); _txtNonTerms.Document.ReadOnly = true; sWinParserStates.Child = _txtParserStates; sWinParserStates.ShowAll (); _txtParserStates.Document.ReadOnly = true; StartParserStatesHighlighter(); } catch (Exception error) { dlgShowException showExceptionDialog = new dlgShowException (error.Message); showExceptionDialog.Response += (object o, ResponseArgs args) => showExceptionDialog.Destroy (); Application.Quit (); } tabGrammar.CurrentPage = 0; tabBottom.CurrentPage = 0; fmExploreGrammarWindowLoad (); this.Present (); } private void SetOSX_Menus () { if (SystemManager.GetOperatingSystem() == OS.Mac) { mbExplorer.Hide (); IgeMacMenu.GlobalKeyHandlerEnabled = true; IgeMacMenu.MenuBar = mbExplorer; // TOOD Fix the quit action via menu to call proper event so user.config is updated IgeMacMenu.QuitMenuItem = QuitAction; } } protected void OnDeleteEvent (object sender, DeleteEventArgs a) { fmExploreGrammarWindowClosing (); Application.Quit (); a.RetVal = true; } private void SetupModel_tvAST () { tvAST.AppendColumn ("AST Tree", new Gtk.CellRendererText (), "text", 0); TreeStore modelAstTree = new TreeStore (typeof(string), typeof(IBrowsableAstNode)); tvAST.HeadersVisible = false; tvAST.Model = modelAstTree; } private void SetupModel_tvParseTree () { tvParseTree.AppendColumn ("ParseTree", new Gtk.CellRendererText (), "text", 0); TreeStore modelParseTree = new TreeStore (typeof(string), typeof(ParseTreeNode)); tvParseTree.HeadersVisible = false; tvParseTree.Model = modelParseTree; } private void SetupModel_gridGrammarErrors () { // err.Level.ToString(), err.Message, err.State) gridGrammarErrors.AppendColumn ("Error Level", new Gtk.CellRendererText (), "text", 0); gridGrammarErrors.AppendColumn ("Description", new Gtk.CellRendererText (), "text", 1); gridGrammarErrors.AppendColumn ("State", new Gtk.CellRendererText (), "text", 2); ListStore modelGridGrammarErrors = new ListStore (typeof(string), typeof(string), typeof(string)); gridGrammarErrors.Model = modelGridGrammarErrors; } private void SetModel_gridParserTrace () { int n_columns = 4; ListStore modelParserTrace = new ListStore (typeof(string), typeof(string), typeof(string), typeof(string), typeof(LogMessage)); _gridParserTrace = new GridView (); _gridParserTrace.HscrollbarPolicy = PolicyType.Automatic; _gridParserTrace.VscrollbarPolicy = PolicyType.Automatic; swParseTrace.AddWithViewport(_gridParserTrace); _gridParserTrace.CellPressEvent += (object o, CellPressEventArgs args) => { Debug.Print("Parser State CELL: {0} {1}", args.Column, args.Row); OnParseStateCellClicked(o, args); }; for (int x = 0; x < n_columns; x++) { CellRendererText renderer = new CellRendererText (); _gridParserTrace.AppendColumn (renderer, "Text", x); } _gridParserTrace.Model = modelParserTrace; } private void SetupModel_gridCompileErrors () { int n_columns = 3; ListStore modelGridCompileErrors = new ListStore (typeof(string), typeof(string), typeof(string), typeof(LogMessage)); _gridCompileErrors = new GridView (); _gridCompileErrors.HscrollbarPolicy = PolicyType.Automatic; _gridCompileErrors.VscrollbarPolicy = PolicyType.Automatic; swCompileErrors.AddWithViewport (_gridCompileErrors); _gridCompileErrors.CellPressEvent += (object o, CellPressEventArgs args) => { Debug.Print("CELL: {0} {1}", args.Column, args.Row); OnGridCompileErrorsClick(o, args); }; for (int x = 0; x < n_columns; x++) { CellRendererText renderer = new CellRendererText (); _gridCompileErrors.AppendColumn (renderer, "Text", x); } _gridCompileErrors.Model = modelGridCompileErrors; } private void SetupModel_cboGrammars () { // Setup the combobox to handle storing/display of GrammarItem class ListStore listStore = new Gtk.ListStore (typeof(GrammarItem), typeof(string)); cboGrammars.Model = listStore; CellRendererText text = new CellRendererText (); cboGrammars.PackStart (text, false); cboGrammars.AddAttribute (text, "text", 1); } private void SetModel_lstTokens () { ListStore modelLstTokens = new ListStore (typeof(string), typeof(Token)); lstTokens.AppendColumn ("Tokens", new Gtk.CellRendererText (), "text", 0, "foreground"); lstTokens.Model = modelLstTokens; } private void SetupModel_btnManageGrammars () { //TODO // Setup the combobox to handle storing/display of Grammar Options and related function calls ListStore listStore = new Gtk.ListStore (typeof(string), typeof(System.Action)); System.Action goselection = SelectGrammarAssembly; System.Action goselection2 = RemoveCurrentGrammar; System.Action goselection3 = RemoveAllGrammarsInList; listStore.AppendValues ("Load Grammars...", goselection); listStore.AppendValues ("Remove Selected", goselection2); listStore.AppendValues ("Remove All", goselection3); btnManageGrammars.Model = listStore; CellRendererText text = new CellRendererText (); btnManageGrammars.PackStart (text, false); // Only display the text column, not the function column btnManageGrammars.AddAttribute (text, "text", 0); } #region Form load/unload events private void fmExploreGrammarWindowLoad () { // ClearLanguageInfo (); try { _teEditor.Text = MyApp.Settings.Default.SourceSample; txtSearch.Text = MyApp.Settings.Default.SearchPattern; GrammarItemList grammars = GrammarItemList.FromXml (MyApp.Settings.Default.Grammars); UpdateModelFromGrammarList (grammars, cboGrammars.Model as ListStore); chkParserTrace.Active = MyApp.Settings.Default.EnableTrace; chkDisableHili.Active = MyApp.Settings.Default.DisableHili; chkAutoRefresh.Active = MyApp.Settings.Default.AutoRefresh; TreeIter ti; cboGrammars.Model.GetIterFromString (out ti, MyApp.Settings.Default.LanguageIndex); if (!ti.Equals (null)) { cboGrammars.SetActiveIter (ti); } } catch { } _loaded = true; } private void fmExploreGrammarWindowClosing () { MyApp.Settings.Default.SourceSample = _teEditor.Text; MyApp.Settings.Default.SearchPattern = txtSearch.Text; MyApp.Settings.Default.EnableTrace = chkParserTrace.Active; MyApp.Settings.Default.DisableHili = chkDisableHili.Active; MyApp.Settings.Default.AutoRefresh = chkAutoRefresh.Active; TreeIter ti; cboGrammars.GetActiveIter (out ti); MyApp.Settings.Default.LanguageIndex = cboGrammars.Model.GetStringFromIter (ti); Console.Write (cboGrammars.Model.GetStringFromIter (ti)); var grammars = GetGrammarListFromModel (cboGrammars.Model as ListStore); MyApp.Settings.Default.Grammars = grammars.ToXml (); MyApp.Settings.Default.Save (); } private void UpdateModelFromGrammarList (GrammarItemList list, ListStore listStore) { // Following crashes when not on main Window thread, which makes sense: // listStore.Clear(); // But even when using Gtk.Application.Invoke (delegate {}); to do it on the main UI thread... // crash on GTK+ delegate, so hack it for now. ListStore newlistStore = new Gtk.ListStore (typeof(GrammarItem), typeof(string)); cboGrammars.Model = newlistStore; // prevent the hack from leaking memory listStore.Dispose (); foreach (GrammarItem item in list) { newlistStore.AppendValues (item, item.Caption); } } private GrammarItemList GetGrammarListFromModel (ListStore listStore) { GrammarItemList list = new GrammarItemList (); foreach (Array item in listStore) { list.Add (item.GetValue (0) as GrammarItem); } return list; } #endregion #region Parsing and running private void CreateGrammar () { _grammar = _grammarLoader.CreateGrammar (); } private void CreateParser () { StopTestSourceHighlighter (); btnRun.Sensitive = false; txtOutput.Buffer.Text = string.Empty; _parseTree = null; btnRun.Sensitive = _grammar is ICanRunSample; _language = new LanguageData (_grammar); _parser = new Parser (_language); ShowParserConstructionResults (); StartParserStatesHighlighter (); } private void ParseSample () { ClearParserOutput (); if (_parser == null || !_parser.Language.CanParse ()) return; _parseTree = null; System.GC.Collect (); //to avoid disruption of perf times with occasional collections _parser.Context.TracingEnabled = chkParserTrace.Active; try { _parser.Parse (_teEditor.Text, "<source>"); } catch (Exception ex) { (_gridCompileErrors.Model as ListStore).AppendValues (null, ex.Message, null); tabBottom.CurrentPage = 2; //pageParserOutput; throw; } finally { _parseTree = _parser.Context.CurrentParseTree; ShowCompilerErrors (); if (chkParserTrace.Active) { ShowParseTrace (); } ShowCompileStats (); ShowParseTree (); ShowAstTree (); } } private void RunSample () { ClearRuntimeInfo (); Stopwatch sw = new Stopwatch (); int oldGcCount; txtOutput.Buffer.Text = ""; try { if (_parseTree == null) ParseSample (); if (_parseTree.ParserMessages.Count > 0) return; System.GC.Collect (); //to avoid disruption of perf times with occasional collections oldGcCount = System.GC.CollectionCount (0); System.Threading.Thread.Sleep (100); sw.Start (); var iRunner = _grammar as ICanRunSample; var args = new RunSampleArgs (_language, _teEditor.Text, _parseTree); string output = iRunner.RunSample (args); sw.Stop (); lblRunTime.Text = sw.ElapsedMilliseconds.ToString (); var gcCount = System.GC.CollectionCount (0) - oldGcCount; lblGCCount.Text = gcCount.ToString (); WriteOutput (output); tabBottom.CurrentPage = 4; //pageOutput; } catch (ScriptException ex) { ShowRuntimeError (ex); } finally { sw.Stop (); } } private void WriteOutput (string text) { if (string.IsNullOrEmpty (text)) return; txtOutput.Buffer.Text += text + Environment.NewLine; // txtOutput.Buffer.SelectRange( Select(txtOutput.Text.Length - 1, 0); } #endregion #region Show... methods private void ClearLanguageInfo () { try { _txtTerms.Text = string.Empty; _txtNonTerms.Text = string.Empty; _txtParserStates.Text = string.Empty; } catch { // Skip errors on initial form load } lblLanguage.Text = string.Empty; lblLanguageVersion.Text = string.Empty; lblLanguageDescr.Text = string.Empty; txtGrammarComments.Buffer.Text = string.Empty; } private void ClearParserOutput () { lblSrcLineCount.Text = string.Empty; lblSrcTokenCount.Text = ""; lblParseTime.Text = ""; lblParseErrorCount.Text = ""; (lstTokens.Model as ListStore).Clear (); DefineCompilerErrorsHeader (); DefineParseTraceHeader (); ClearTreeView (tvParseTree); ClearTreeView (tvAST); } private void ShowLanguageInfo () { if (_grammar != null) { var langAttr = LanguageAttribute.GetValue (_grammar.GetType ()); if (langAttr != null) { lblLanguage.Text = langAttr.LanguageName; lblLanguageVersion.Text = langAttr.Version; lblLanguageDescr.Text = langAttr.Description; txtGrammarComments.Buffer.Text = _grammar.GrammarComments; } } } private void DefineParseTraceHeader() { if (_gridParserTrace.Model != null) { (_gridParserTrace.Model as ListStore).Clear (); (_gridParserTrace.Model as ListStore).AppendValues ( "State", "Stack Top", "Input", "Action" ); _gridParserTrace.Orientation = Orientation.Vertical; _gridParserTrace.NRowHeaders = 0; _gridParserTrace.NColHeaders = 1; } } private void DefineCompilerErrorsHeader() { if (_gridCompileErrors.Model != null) { (_gridCompileErrors.Model as ListStore).Clear (); (_gridCompileErrors.Model as ListStore).AppendValues ( "L.C.", "Error Message", "Parser State" ); _gridCompileErrors.Orientation = Orientation.Vertical; _gridCompileErrors.NRowHeaders = 0; _gridCompileErrors.NColHeaders = 1; } } private void ShowCompilerErrors () { DefineCompilerErrorsHeader (); if (_parseTree == null || _parseTree.ParserMessages.Count == 0) return; foreach (var err in _parseTree.ParserMessages) { (_gridCompileErrors.Model as ListStore).AppendValues (err.Location.ToUiString (), err.Message, err.ParserState.ToString (), err); } var needPageSwitch = tabBottom.CurrentPage != 2 && // pageParserOutput !(tabBottom.CurrentPage == 3 && chkParserTrace.Active); if (needPageSwitch) tabBottom.CurrentPage = 2; // pageParserOutput; _gridCompileErrors.ShowAll (); } private void ShowParseTrace () { DefineParseTraceHeader (); String cellColor; foreach (ParserTraceEntry entry in _parser.Context.ParserTrace) { if (entry.IsError) { cellColor = "red"; } else { cellColor = "black"; } string cInput = ""; if (entry.Input != null) { cInput = _regexCleanWhiteSpace.Replace (entry.Input.ToString (), @" "); cInput = System.Text.RegularExpressions.Regex.Replace(cInput.ToString(),@"\s+"," "); } string cStackTop = _regexCleanWhiteSpace.Replace (entry.StackTop.ToString (), @" "); cStackTop = System.Text.RegularExpressions.Regex.Replace(cStackTop.ToString(),@"\s+"," "); ListStore listmodel = (_gridParserTrace.Model as ListStore); // "State", "Stack Top", "Input", "Action"} listmodel.AppendValues(entry.State.Name, cStackTop, cInput, entry.Message); } //Show tokens String foo; foreach (Token tkn in _parseTree.Tokens) { if (chkExcludeComments.Active && tkn.Category == TokenCategory.Comment) continue; foo = tkn.ToString (); string cleanedup = System.Text.RegularExpressions.Regex.Replace (foo, @"\s+", " "); (lstTokens.Model as ListStore).AppendValues ( cleanedup, tkn ); } _gridParserTrace.ShowAll (); } private void ShowCompileStats () { if (_parseTree != null) { lblSrcLineCount.Text = string.Empty; if (_parseTree.Tokens.Count > 0) lblSrcLineCount.Text = (_parseTree.Tokens [_parseTree.Tokens.Count - 1].Location.Line + 1).ToString (); lblSrcTokenCount.Text = _parseTree.Tokens.Count.ToString (); lblParseTime.Text = _parseTree.ParseTimeMilliseconds.ToString (); lblParseErrorCount.Text = _parseTree.ParserMessages.Count.ToString (); } //Note: this time is "pure" parse time; actual delay after cliking "Compile" includes time to fill ParseTree, AstTree controls } private void ClearTreeView (TreeView tv) { TreeStore ts = (tv.Model as TreeStore); if (ts.IterNChildren () > 0) { // HACK: Gtk delegate threading issue again even on Application.Invoke.... tv.Model = null; ts.Clear (); tv.Model = ts; } } private void ShowParseTree () { ClearTreeView (tvParseTree); if (_parseTree != null) { AddParseNodeRec (TreeIter.Zero, _parseTree.Root); } } private void AddParseNodeRec (TreeIter parent, ParseTreeNode node) { if (node != null) { string txt = _regexCleanWhiteSpace.Replace (node.ToString (), @" "); TreeIter ti; TreeStore ptree = tvParseTree.Model as TreeStore; if (!parent.Equals (TreeIter.Zero)) { ti = ptree.AppendValues (parent, txt, node); } else { ti = ptree.AppendValues (txt); } foreach (var child in node.ChildNodes) AddParseNodeRec (ti, child); } } private void ShowAstTree () { ClearTreeView (tvAST); if (_parseTree == null || _parseTree.Root == null || _parseTree.Root.AstNode == null) return; AddAstNodeRec (TreeIter.Zero, _parseTree.Root.AstNode); } private void AddAstNodeRec (TreeIter parent, object astNode) { if (astNode != null) { string txt = _regexCleanWhiteSpace.Replace (astNode.ToString (), @" "); TreeIter ti; TreeStore asttree = tvAST.Model as TreeStore; if (!parent.Equals (TreeIter.Zero)) { ti = asttree.AppendValues (parent, txt, astNode); } else { ti = asttree.AppendValues (txt); } var iBrowsable = astNode as IBrowsableAstNode; if (iBrowsable != null) { var childList = iBrowsable.GetChildNodes (); foreach (var child in childList) AddAstNodeRec (ti, child); } } } private void ShowParserConstructionResults () { lblParserStateCount.Text = _language.ParserData.States.Count.ToString (); lblParserConstrTime.Text = _language.ConstructionTime.ToString (); (gridGrammarErrors.Model as ListStore).Clear (); try { _txtTerms.Text = string.Empty; _txtNonTerms.Text = string.Empty; _txtParserStates.Text = string.Empty; } catch { // Due to form creation order, this editors might not be created } tabBottom.CurrentPage = 0; // pageLanguage; if (_parser != null) { _txtTerms.Text = ParserDataPrinter.PrintTerminals (_language); _txtTerms.Document.ReadOnly = true; _txtNonTerms.Text = ParserDataPrinter.PrintNonTerminals (_language); _txtNonTerms.Document.ReadOnly = true; _txtParserStates.Text = ParserDataPrinter.PrintStateList (_language); _txtNonTerms.Document.ReadOnly = true; ShowGrammarErrors (); } } private void ShowGrammarErrors () { (gridGrammarErrors.Model as ListStore).Clear (); var errors = _parser.Language.Errors; if (errors.Count == 0) return; foreach (var err in errors) (gridGrammarErrors.Model as ListStore).AppendValues (err.Level.ToString (), err.Message, err.State); if (tabBottom.CurrentPage != 1) // pageGrammarErrors tabBottom.CurrentPage = 0; } private void ShowSourcePosition (TextEditor te, Irony.Parsing.SourceSpan sSpan) { ShowSourcePosition (te, sSpan.Location.Line, sSpan.Location.Column, sSpan.Length); } private void ShowSourcePosition (TextEditor te, ScriptException scriptException) { ShowSourcePosition (te, scriptException.Location.Line, 0, 0); } private void ShowSourcePosition (TextEditor te, int line, int column, int length) { if (te.IsSomethingSelected) { te.ClearSelection (); } if (length == 0) { te.SetCaretTo (line + 1, 1); te.StartCaretPulseAnimation (); te.SetSelectLines (line + 1, line + 1); } else { te.SetCaretTo (line + 1, column + 1); te.StartCaretPulseAnimation (); te.SetSelection (line + 1, column + 1, line + 1, column + length + 1); } if (tabGrammar.CurrentPage != 3) tabGrammar.CurrentPage = 3; te.GrabFocus (); } private void ClearTraceTokenSelection () { (lstTokens.NodeSelection).UnselectAll (); } private void ShowTraceToken (int position, int length) { TreeIter ti; ListStore modelLstTokens = lstTokens.Model as ListStore; for (int i = 0; i < modelLstTokens.IterNChildren(); i++) { lstTokens.Model.GetIterFromString(out ti, i.ToString() ); Token token = modelLstTokens.GetValue (ti, 1) as Token; if (!token.Equals (null)) { if (token.Location.Position == position) { lstTokens.SetCursor (new TreePath (i.ToString ()), lstTokens.Columns [0], false); return; } } } } private void LocateParserState (ParserState state) { if (state == null) return; if (tabGrammar.CurrentPage != 2) tabGrammar.CurrentPage = 2; DoSearch(_txtParserStates, "State " + state.Name, 0); } private void ShowRuntimeError (ScriptException error) { _runtimeError = error; lnkShowErrLocation.Sensitive = _runtimeError != null; lnkShowErrStack.Sensitive = lnkShowErrLocation.Sensitive; if (_runtimeError != null) { //the exception was caught and processed by Interpreter WriteOutput ("Error: " + error.Message + " At " + _runtimeError.Location.ToUiString () + "."); // ShowSourcePosition(_runtimeError.Location.Position, 1); } else { //the exception was not caught by interpreter/AST node. Show full exception info WriteOutput ("Error: " + error.Message); dlgShowException showExceptionDialog = new dlgShowException (error.Message); showExceptionDialog.Destroy (); } tabBottom.CurrentPage = 4; // pageOutput; } private void SelectTreeNode (TreeView tree, TreeNode node) { // _treeClickDisabled = true; // tree.SelectedNode = node; // if (node != null) // node.EnsureVisible(); // _treeClickDisabled = false; } private void ClearRuntimeInfo () { lnkShowErrLocation.Sensitive = false; lnkShowErrStack.Sensitive = false; _runtimeError = null; txtOutput.Buffer.Text = string.Empty; } #endregion #region Grammar combo menu commands private void RemoveCurrentGrammar () { // if (MessageBox.Show("Are you sure you want to remove grammmar " + cboGrammars.SelectedItem + "?", // "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { // cboGrammars.Items.RemoveAt(cboGrammars.SelectedIndex); _parser = null; if ((cboGrammars.Model as ListStore).IterNChildren () > 0) { TreeIter ti; cboGrammars.GetActiveIter (out ti); // Temp removal of ListStore from combobox as removing items while active is not threadsafe in GTK ListStore tmpListStore = cboGrammars.Model as ListStore; cboGrammars.Model = null; tmpListStore.Remove (ref ti); tmpListStore.GetIterFirst (out ti); cboGrammars.Model = tmpListStore; cboGrammars.SetActiveIter (ti); btnRefresh.Sensitive = true; if (tmpListStore.IterNChildren () == 0) { ClearUIInfo (); } } else { btnRefresh.Sensitive = false; } } private void RemoveAllGrammarsInList () { // if (MessageBox.Show("Are you sure you want to remove all grammmars in the list?", // "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { _parser = null; ListStore tmpListStore = cboGrammars.Model as ListStore; cboGrammars.Model = null; tmpListStore.Clear (); cboGrammars.Model = tmpListStore; ClearUIInfo (); btnRefresh.Sensitive = false; // } } #endregion private void SelectGrammarAssembly () { Gtk.FileChooserDialog fc = new Gtk.FileChooserDialog ("Choose the Irony-based grammar to open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept); fc.Run (); string location = fc.Filename; if (!string.IsNullOrEmpty (location)) { var oldGrammars = new GrammarItemList (); fc.Destroy (); SelectGrammars (location, oldGrammars); } else { fc.Destroy (); } } protected void OnBtnRefreshClicked (object sender, EventArgs e) { LoadSelectedGrammar (); } protected void SelectGrammars (string filename, GrammarItemList grammerlist) { dlgSelectGrammars grammarListDialog = new dlgSelectGrammars (); grammarListDialog.ShowGrammars (filename, grammerlist, new dlgSelectGrammars.ProcessGrammars (foobar), this); } private void ClearUIInfo () { ClearLanguageInfo (); ClearParserOutput (); ClearRuntimeInfo (); } // public delegate void ProcessBookDelegate (GrammarItemList grammarlist); public void foobar (GrammarItemList grammarlist) { if (grammarlist != null) { // Store the Grammar items from the dll in the combobox ListStore model UpdateModelFromGrammarList (grammarlist, cboGrammars.Model as ListStore); btnRefresh.Sensitive = false; // auto-select the first grammar if no grammar currently selected TreeIter ti; cboGrammars.Model.GetIterFirst (out ti); cboGrammars.SetActiveIter (ti); } if (grammarlist.Count == 0) { ClearUIInfo (); } } #region miscellaneous: LoadSourceFile, Search, Source highlighting private void LoadSourceFile (string path) { _parseTree = null; StreamReader reader = null; try { reader = new StreamReader (path); _teEditor.Text = String.Empty; //to clear any old formatting // txtSource.ClearUndo(); // txtSource.ClearStylesBuffer(); _teEditor.Text = reader.ReadToEnd (); // txtSource.SetVisibleState(0, FastColoredTextBoxNS.VisibleState.Visible); // txtSource.Selection = txtSource.GetRange(0, 0); } catch (Exception error) { dlgShowException showExceptionDialog = new dlgShowException (error.Message); showExceptionDialog.Destroy (); } finally { if (reader != null) reader.Close (); } } private void StartParserStatesHighlighter () { _IronyParserStatesSyntaxMode = new IronyParserStatesSyntaxMode (null); Mono.TextEditor.Highlighting.SyntaxModeService.InstallSyntaxMode ("text/x-irony-parserstates", new SyntaxModeProvider (doc => _IronyParserStatesSyntaxMode )); _txtParserStates.Document.MimeType = "text/x-irony-parserstates"; } private void StopParserStatesHighlighter () { } private void StartTestSourceHighlighter () { _IronySyntaxMode = new IronySyntaxMode (null); Mono.TextEditor.Highlighting.SyntaxModeService.InstallSyntaxMode ("text/x-irony", new SyntaxModeProvider (doc => _IronySyntaxMode )); var termList = _language.GrammarData.Terminals.ToList(); var tStringList = new List<string>(); foreach (var t in termList) { if (t.GetType().GetProperty("Text") != null) { tStringList.Add ( t.ToString() ); } } _IronySyntaxMode.AddTerminals (tStringList); var ntList = _language.GrammarData.NonTerminals.ToList(); var ntStringList = new List<string>(); foreach (var nt in ntList) { if (nt.GetType().GetProperty("Text") != null) { ntStringList.Add ( nt.ToString() ); } } _IronySyntaxMode.AddNonTerminals (ntStringList); _teEditor.Document.MimeType = "text/x-irony"; var tmp = _teEditor.Document.Text; _teEditor.Document.Text = String.Empty; _teEditor.Document.Text = tmp; } private void StopTestSourceHighlighter () { _teEditor.Document.MimeType = "text/stophighlighting"; var tmp = _teEditor.Document.Text; _teEditor.Document.Text = String.Empty; _teEditor.Document.Text = tmp; } private void EnableHighlighter (bool enable) { if (enable) StartTestSourceHighlighter (); else StopTestSourceHighlighter(); } private void DoSearch () { _teEditor.ClearSelection (); _teEditor.HighlightSearchPattern = true; _teEditor.SearchPattern = txtSearch.Text; Mono.TextEditor.SearchResult foo = _teEditor.SearchForward (0); lblSearchError.Visible = (foo == null); if (foo != null) { _teEditor.AnimateSearchResult (foo); } } private bool DoSearch(TextEditor te, string fragment, int start) { te.ClearSelection (); te.HighlightSearchPattern = true; te.SearchPattern = fragment; Mono.TextEditor.SearchResult found = te.SearchForward (0); lblSearchError.Visible = (found == null); if (found != null) { te.StopSearchResultAnimation (); te.Caret.Location = te.OffsetToLocation (found.EndOffset); te.SetSelection (found.Offset, found.EndOffset); te.CenterToCaret (); te.AnimateSearchResult (found); return true; } else { return false; } } bool _changingGrammar; private void LoadSelectedGrammar () { try { ClearLanguageInfo (); ClearParserOutput (); ClearRuntimeInfo (); _changingGrammar = true; CreateGrammar (); ShowLanguageInfo (); CreateParser (); } finally { _changingGrammar = false; //in case of exception } btnRefresh.Sensitive = true; } #endregion #region Controls event handlers protected void OnBtnParseClicked (object sender, EventArgs e) { ParseSample (); } protected void OnBtnRunClicked (object sender, EventArgs e) { RunSample (); } protected void OnCboGrammarsChanged (object sender, EventArgs e) { TreeIter ti; cboGrammars.GetActiveIter (out ti); _grammarLoader.SelectedGrammar = cboGrammars.Model.GetValue (ti, 0) as GrammarItem; LoadSelectedGrammar (); } private void GrammarAssemblyUpdated (object sender, EventArgs args) { if (chkAutoRefresh.Active) { Gtk.Application.Invoke (delegate { LoadSelectedGrammar (); txtGrammarComments.Buffer.Text += String.Format ("{0}Grammar assembly reloaded: {1:HH:mm:ss}", Environment.NewLine, DateTime.Now); }); } } protected void OnFcbtnFileOpenSelectionChanged (object sender, EventArgs e) { FileChooserButton file = sender as FileChooserButton; string location = file.Filename; if (!string.IsNullOrEmpty (location)) { ClearParserOutput (); LoadSourceFile (location); } } private void cboParseMethod_SelectedIndexChanged (object sender, EventArgs e) { //changing grammar causes setting of parse method combo, so to prevent double-call to ConstructParser // we don't do it here if _changingGrammar is set if (!_changingGrammar) CreateParser (); } protected void OnDefaultActivated (object sender, EventArgs e) { (sender as Gtk.Window).Present (); } protected void OnRealized (object sender, EventArgs e) { (sender as Gtk.Window).Present (); } protected void OnOpenGrammarAssemblyActionActivated (object sender, EventArgs e) { SelectGrammarAssembly (); } protected void OnEnterFullScreenActionActivated (object sender, EventArgs e) { if (!_fullScreen) { this.Fullscreen (); EnterFullScreenAction.Label = "Exit Full Screen"; } else { this.Unfullscreen (); EnterFullScreenAction.Label = "Enter Full Screen"; } _fullScreen = !_fullScreen; } protected void OnStateChanged (object sender, EventArgs e) { _fullScreen = !_fullScreen; } protected void OnQuitActionActivated (object sender, EventArgs e) { fmExploreGrammarWindowClosing (); Application.Quit (); } protected void OnMinimizeActionActivated (object sender, EventArgs e) { this.Iconify (); } protected void OnCloseGrammarAssemblyActionActivated (object sender, EventArgs e) { RemoveAllGrammarsInList (); } protected void OnAboutIrontGrammarExplorerActionActivated (object sender, EventArgs e) { AboutDialog about = new AboutDialog (); about.Parent = this; about.SetPosition (WindowPosition.CenterOnParent); Assembly currentAssem = typeof(MainWindow).Assembly; object[] attribs = currentAssem.GetCustomAttributes (typeof(AssemblyCompanyAttribute), true); attribs = currentAssem.GetCustomAttributes (typeof(AssemblyDescriptionAttribute), true); if (attribs.Length > 0) about.ProgramName = ((AssemblyDescriptionAttribute)attribs [0]).Description; attribs = currentAssem.GetCustomAttributes (typeof(AssemblyFileVersionAttribute), true); if (attribs.Length > 0) about.Version = ((AssemblyFileVersionAttribute)attribs [0]).Version; string[] authors = { "GtkSharp version by Robert Nees", "Original Windows.Forms Version by Roman Ivantsov" }; attribs = currentAssem.GetCustomAttributes (typeof(AssemblyCopyrightAttribute), true); if (attribs.Length > 0) about.Copyright = ((AssemblyCopyrightAttribute)attribs [0]).Copyright; about.Authors = authors; // Note: Link will only work when run from within App bundle on OS-X about.Website = "http://irony.codeplex.com"; about.Response += (object o, ResponseArgs args) => about.Destroy (); about.Show (); } protected void OnBtnSearchClicked (object sender, EventArgs e) { DoSearch (); } protected void OnTxtSearchEditingDone (object sender, EventArgs e) { DoSearch (); } protected void OnTxtSearchChanged (object sender, EventArgs e) { btnSearch.Sensitive = (txtSearch.Text != String.Empty); DoSearch (); } bool _InManageGrammarSelectiion = false; // HACK: no context menu like winform, using a combobox instead. // and need to ignore 'second' change event when clearing the selection after processing user's selection protected void OnBtnManageGrammarsChanged (object sender, EventArgs e) { if (!_InManageGrammarSelectiion) { _InManageGrammarSelectiion = true; try { TreeIter ti; btnManageGrammars.GetActiveIter (out ti); ListStore listStore = btnManageGrammars.Model as ListStore; (listStore.GetValue (ti, 1) as System.Action) (); } finally { btnManageGrammars.SetActiveIter (TreeIter.Zero); _InManageGrammarSelectiion = false; } } } void LocateTreeNodes (TextSegment segment) { if (segment != null) { if (!_TreeSelectionChanging) { LocateTreeNode (tvParseTree, segment.Offset, segment.Length); tvParseTree.CollapseAll (); tvParseTree.ExpandToPath (_currentPath); var treeselect = tvParseTree.Selection; tvParseTree.SetCursor (_currentPath, tvParseTree.Columns [0], false); LocateTreeNode (tvAST, segment.Offset, segment.Length); tvAST.CollapseAll (); tvAST.ExpandToPath (_currentPath); treeselect = tvParseTree.Selection; tvAST.SetCursor (_currentPath, tvAST.Columns [0], false); } } } protected void OnBtnLocateClicked (object sender, EventArgs e) { if (!_TreeSelectionChanging) { if (_parser != null) { if (_teEditor.IsSomethingSelected) { if (_parseTree == null) { ParseSample (); } LocateTreeNodes (_teEditor.SelectionRange); } } } } protected void OnLnkShowErrStackClicked (object sender, EventArgs e) { if (_runtimeError != null) { if (_runtimeError.InnerException != null) { dlgShowException showExceptionDialog = new dlgShowException (_runtimeError.InnerException.ToString ()); showExceptionDialog.Response += (object o, ResponseArgs args) => showExceptionDialog.Destroy (); } else { dlgShowException showExceptionDialog = new dlgShowException (_runtimeError.ToString ()); showExceptionDialog.Response += (object o, ResponseArgs args) => showExceptionDialog.Destroy (); } } } protected void OnLnkShowErrLocationClicked (object sender, EventArgs e) { if (_runtimeError != null) ShowSourcePosition (_teEditor, _runtimeError); } bool _TreeSelectionChanging = false; protected void OnTvParseTreeRowActivated (object o, RowActivatedArgs args) { try { _TreeSelectionChanging = true; TreeIter ti; (tvParseTree.Model as TreeStore).GetIter (out ti, args.Path); ParseTreeNode parseNode = (tvParseTree.Model as TreeStore).GetValue (ti, 1) as ParseTreeNode; if (parseNode != null) { ShowSourcePosition (_teEditor, parseNode.Span); } } finally { _TreeSelectionChanging = false; } } protected void OnTvASTRowActivated (object o, RowActivatedArgs args) { try { _TreeSelectionChanging = true; TreeIter ti; (tvAST.Model as TreeStore).GetIter (out ti, args.Path); Irony.Interpreter.Ast.AstNode astNode = (tvAST.Model as TreeStore).GetValue (ti, 1) as Irony.Interpreter.Ast.AstNode; if (astNode != null) { ShowSourcePosition (_teEditor, astNode.Span); } } finally { _TreeSelectionChanging = false; } } #endregion TreeIter _currentNode; TreePath _currentPath; int _start; int _end; private bool ForEachTreeNode (Gtk.TreeModel model, Gtk.TreePath path, Gtk.TreeIter iter) { ParseTreeNode foo = model.GetValue (iter, 1) as ParseTreeNode; if (foo == null) return false; Irony.Parsing.SourceSpan sSpan = foo.Span; if (sSpan.Location.Position >= _start) { if (_end == sSpan.Length) { _currentNode = iter; _currentPath = path.Copy (); return true; } } return false; } private TreeIter LocateTreeNode (TreeView tv, int start, int end) { _currentNode = TreeIter.Zero; _start = start; _end = end; tv.Model.Foreach (new TreeModelForeachFunc (ForEachTreeNode)); return _currentNode; } private void OnParseStateCellClicked (object sender, CellPressEventArgs args) { int _row = args.Row; if (_row >= _parser.Context.ParserTrace.Count) { _row = 0; } var entry = _parser.Context.ParserTrace[_row]; switch (args.Column) { case 0: //state case 3: //action LocateParserState(entry.State); break; case 1: //stack top if (entry.StackTop != null) { ShowSourcePosition (_teEditor, entry.StackTop.Span); LocateTreeNodes (_teEditor.SelectionRange); if (entry.Input != null) { ShowTraceToken (entry.Input.Span.Location.Position, entry.Input.Span.Length); } else { ClearTraceTokenSelection (); } } break; case 2: //input if (entry.Input != null) { ShowSourcePosition (_teEditor, entry.StackTop.Span); LocateTreeNodes (_teEditor.SelectionRange); if (entry.Input != null) { ShowTraceToken (entry.Input.Span.Location.Position, entry.Input.Span.Length); } else { ClearTraceTokenSelection (); } } break; } } protected void OnLstTokensRowActivated (object o, RowActivatedArgs args) { TreeIter ti; ListStore modelLstTokens = (o as NodeView).Model as ListStore; modelLstTokens.GetIter (out ti, args.Path); if (!ti.Equals (null)) { Token token = modelLstTokens.GetValue (ti, 1) as Token; if (!token.Equals(null)) { ShowSourcePosition (_teEditor, token.Location.Line, token.Location.Column, token.Length); } } } protected void OnChkDisableHiliToggled (object sender, EventArgs e) { if (_loaded) { EnableHighlighter (!chkDisableHili.Active); } } private void OnGridCompileErrorsClick(object sender, CellPressEventArgs args) { TreeIter ti; var treemodel = _gridCompileErrors.Model as ListStore; treemodel.GetIter (out ti, args.Path ); if (!ti.Equals (null)) { var err = treemodel.GetValue (ti, 3) as LogMessage; if (!err.Equals(null)) { switch (args.Column) { case 0: //state case 1: //stack top ShowSourcePosition(_teEditor, err.Location.Line, err.Location.Column, 1); break; case 2: //input if (err.ParserState != null) LocateParserState(err.ParserState); break; } } } } } }
/* * Copyright (c) Brock Allen. All rights reserved. * see license.txt * * Code borrowed from: https://github.com/brockallen/BrockAllen.MembershipReboot/tree/master/src/BrockAllen.MembershipReboot/Crypto */ namespace IdentityBase.Crypto { using System; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; public class DefaultCryptoService : ICryptoService { public const char PasswordHashingIterationCountSeparator = '.'; public string HashPassword(string password, int iterations) { if (iterations <= 0) { iterations = GetIterationsFromYear(GetCurrentYear()); } string result = HashPasswordInternal(password, iterations); return EncodeIterations(iterations) + PasswordHashingIterationCountSeparator + result; } public bool VerifyPasswordHash( string hashedPassword, string password, int iterations) { if (!hashedPassword.Contains( DefaultCryptoService.PasswordHashingIterationCountSeparator)) { return this.VerifyPasswordHashInternal( hashedPassword, password, PBKDF2IterCount ); } string[] parts = hashedPassword .Split(PasswordHashingIterationCountSeparator); if (parts.Length != 2) { return false; } int count = DecodeIterations(parts[0]); if (count <= 0) { return false; } hashedPassword = parts[1]; return this.VerifyPasswordHashInternal( hashedPassword, password, count ); } // From OWASP : https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet public const int StartYear = 2016; public const int StartCount = 1000; public int GetIterationsFromYear(int year) { if (year <= StartYear) { return StartCount; } int diff = (year - StartYear) / 2; int mul = (int)Math.Pow(2, diff); int count = StartCount * mul; // if we go negative, then we wrapped (expected in year ~2044). // Int32.Max is best we can do at this point if (count < 0) { count = Int32.MaxValue; } return count; } public virtual int GetCurrentYear() { return DateTime.Now.Year; } public string EncodeIterations(int count) { return count.ToString("X"); } public const int PBKDF2IterCount = 1000; // default for Rfc2898DeriveBytes public const int PBKDF2SubkeyLength = 256 / 8; // 256 bits public const int SaltSize = 128 / 8; // 128 bits public string HashPasswordInternal(string password, int iterations) { if (password == null) { throw new ArgumentNullException(nameof(password)); } // Produce a version 0 (see comment above) password hash. byte[] salt; byte[] subkey; using (var deriveBytes = new Rfc2898DeriveBytes( password, SaltSize, iterations)) { salt = deriveBytes.Salt; subkey = deriveBytes.GetBytes(PBKDF2SubkeyLength); } byte[] outputBytes = new byte[1 + SaltSize + PBKDF2SubkeyLength]; Buffer.BlockCopy(salt, 0, outputBytes, 1, SaltSize); Buffer.BlockCopy(subkey, 0, outputBytes, 1 + SaltSize, PBKDF2SubkeyLength); return Convert.ToBase64String(outputBytes); } public bool VerifyPasswordHashInternal( string passwordHash, string password, int iterationCount) { if (passwordHash == null) { throw new ArgumentNullException("hashedPassword"); } if (password == null) { throw new ArgumentNullException("password"); } byte[] hashedPasswordBytes = Convert.FromBase64String(passwordHash); // Verify a version 0 (see comment above) password hash. if (hashedPasswordBytes.Length != (1 + SaltSize + PBKDF2SubkeyLength) || hashedPasswordBytes[0] != 0x00) { // Wrong length or version header. return false; } byte[] salt = new byte[SaltSize]; Buffer.BlockCopy(hashedPasswordBytes, 1, salt, 0, SaltSize); byte[] storedSubkey = new byte[PBKDF2SubkeyLength]; Buffer.BlockCopy( hashedPasswordBytes, 1 + SaltSize, storedSubkey, 0, PBKDF2SubkeyLength ); byte[] generatedSubkey; using (Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes( password, salt, iterationCount) ) { generatedSubkey = deriveBytes.GetBytes(PBKDF2SubkeyLength); } return ByteArraysEqual(storedSubkey, generatedSubkey); } public int DecodeIterations(string prefix) { int val; if (Int32.TryParse( prefix, System.Globalization.NumberStyles.HexNumber, null, out val) ) { return val; } return -1; } /// <summary> /// Compares two byte arrays for equality. The method is specifically /// written so that the loop is not optimized. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> [MethodImpl(MethodImplOptions.NoOptimization)] public bool ByteArraysEqual(byte[] a, byte[] b) { if (ReferenceEquals(a, b)) { return true; } if (a == null || b == null || a.Length != b.Length) { return false; } bool areSame = true; for (int i = 0; i < a.Length; i++) { areSame &= (a[i] == b[i]); } return areSame; } public string GenerateSalt() { var buf = new byte[SaltSize]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(buf); } return Convert.ToBase64String(buf); } public string Hash(string input) { if (input == null) { throw new ArgumentNullException(nameof(input)); } return Hash(Encoding.UTF8.GetBytes(input)); } public string Hash(byte[] input) { if (input == null) { throw new ArgumentNullException(nameof(input)); } using (HashAlgorithm alg = SHA256.Create()) { if (alg == null) { //String.Format(CultureInfo.InvariantCulture, HelpersResources.Crypto_NotSupportedHashAlg, algorithm)); throw new InvalidOperationException(); } byte[] hashData = alg.ComputeHash(input); return this.BinaryToHex(hashData); } } internal string BinaryToHex(byte[] data) { char[] hex = new char[data.Length * 2]; for (int iter = 0; iter < data.Length; iter++) { byte hexChar = ((byte)(data[iter] >> 4)); hex[iter * 2] = (char)(hexChar > 9 ? hexChar + 0x37 : hexChar + 0x30); hexChar = ((byte)(data[iter] & 0xF)); hex[(iter * 2) + 1] = (char)(hexChar > 9 ? hexChar + 0x37 : hexChar + 0x30); } return new string(hex); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Pathfinding; public class HumanoidHandler : MonoBehaviour { public static List<HumanoidHandler> ListOfHumans = new List<HumanoidHandler>(); public static List<HumanoidHandler> ListOfZombies = new List<HumanoidHandler>(); /// <summary> /// Character attack using state--User defined, type of attack being used /// </summary> public enum StateCharacterAtkUsing { WeakAttack, MediumAttack, StrongAttack } /// <summary> /// Character attack behave state--User defined, stand until attacked or attack nearest /// </summary> public enum StateCharacterBehave { StandAndRun, Stand, AtkNearest } /// <summary> /// Character state--Zombie or Human. /// </summary> public enum StateCharacterType { Zombie, Human } /// <summary> /// Zombie type--The type the character is or will turn into if infected. /// </summary> public enum StateZombieType { Sneeky, Strong, Fast } /// <summary> /// Animation Atate->animation: Standing->standing, Walking->walking or shambling, /// Running->running, Attacking-> hitting or shooting /// /// NOTE: Standing, Walking, Running, and Attacking add HoldGun to respective animation /// </summary> public enum StateAnim { Standing, Walking, Running, Attacking } public static Texture2D FastTex; public static Texture2D SneakyTex; //public static Texture2D ToughTex; public static Texture2D HumanTex; //public static Texture2D MilitaryTex; /// State enum variables--The enum variables representing current states. public StateCharacterAtkUsing CurrUsingAttack; public StateCharacterBehave CurrBehavior; public StateCharacterType CurrCharacterType; public StateZombieType CurrZombType; public StateAnim CurrAnimation; public bool isSelected; //By the player, needed in AIPather.cs so all zombies aren't moved at once. /// <summary> /// isTargeting -> either targeting a walkToPoint or an enemy. /// If not targeting, the user is controling the zombie. /// </summary> public bool isTargeting; public bool isArmed; public int maxHealth; public int currHealth; public int maxResistance;// for infecting humans public int currResistance; public int baseAttackDamage; public float timeSinceLastAttack; public float speedPerSec; // the following are used in pathfinding private Seeker seeker; private Path path; private CharacterController controller; //<summary>Once this dist is reached, go to the next Path point</summary> private float distToIncrementPathPoint = .5f; //<summary>The current Path point</summary> private int currPathPointIndex = 0; //<summary>Initial position where a new Path was obtained</summary> private Vector3 initTargetPos { set; get; } //<summary>The Transform of the Target. Used to track target's movement</summary> public Transform TransOfTarget { set; get; } //<summary>Self Pos</summary> public Vector3 Position { get { return transform.position; } } // Use this for initialization public void Start() { // Get components for pathfinding seeker = GetComponent<Seeker>(); controller = GetComponent<CharacterController>(); FastTex = (Texture2D)Resources.Load ("ZombieFastTex"); SneakyTex = (Texture2D)Resources.Load ("ZombieSneakyTex"); //ToughTex = (Texture2D)Resources.Load ("ZombieToughTex"); HumanTex = (Texture2D)Resources.Load ("HumanTex"); //MilitaryTex = (Texture2D)Resources.Load ("MilitaryTex"); CurrUsingAttack = StateCharacterAtkUsing.WeakAttack; CurrBehavior = StateCharacterBehave.AtkNearest; //CurrCharacterType = StateCharacterType.Human; CurrZombType = StateZombieType.Fast; CurrAnimation = StateAnim.Standing; //isTargeting = false; isArmed = false; maxHealth = 8; // was 75; currHealth = maxHealth; maxResistance = 75; currResistance = maxResistance; baseAttackDamage = 2; timeSinceLastAttack = 0; speedPerSec = 2000.0f; if( CurrCharacterType == StateCharacterType.Human ) { HumanoidHandler.ListOfHumans.Add (this); } else { HumanoidHandler.ListOfZombies.Add(this); } } //TODO: remove test() void TestingFun() { }// TestingFun() // Update is called once per frame void FixedUpdate () { if( CurrCharacterType == StateCharacterType.Zombie) { if( isTargeting ) { AnimateZombie(); } else { // TODO: add function for handling AI according to UI } } else { AnimateHuman(); } if( currHealth < 1 ) {// remove self from the game if( CurrCharacterType == StateCharacterType.Human ) { int thisID = transform.GetInstanceID(); for( int i = 0; i < HumanoidHandler.ListOfHumans.Count; i++ ) { if( thisID == HumanoidHandler.ListOfHumans[i].transform.GetInstanceID () ) { HumanoidHandler.ListOfHumans.RemoveAt (i); } } // TODO: add random placement upon game over // if dead place self below ground if( transform.position.y > 0.0f ) { transform.Translate ( new Vector3(0.0f, -16.0f - transform.position.y , 0.0f) , Space.World ); } } else {// remove zombie self from zombie list int thisID = transform.GetInstanceID(); for( int i = 0; i < HumanoidHandler.ListOfZombies.Count; i++ ) { if( thisID == HumanoidHandler.ListOfZombies[i].transform.GetInstanceID () ) { HumanoidHandler.ListOfZombies.RemoveAt (i); } } } } }// Update() void AnimateZombie() { switch( CurrAnimation ) { case StateAnim.Running: {//TODO: Check if target moved // --> get path to new target position (switch to standing) //Check if target reached // --> switch to Attacking state if( !animation.IsPlaying ("Run") ) { animation.Play ("Run"); } TranslateAndRotate ( 2 * speedPerSec);// set running speed & move if( TransOfTarget != null && Vector3.Magnitude ( TransOfTarget.position - transform.position ) < 7.50f ) { CurrAnimation = StateAnim.Attacking; } break; } case StateAnim.Walking: {//TODO: Check if target moved // --> get path to new target position (switch to standing) //Check if target reached // --> switch to Attacking state if( !animation.IsPlaying ("Walk") ) { animation.Play ("Walk"); } TranslateAndRotate (speedPerSec);// set to walking speed & move if( TransOfTarget != null && Vector3.Magnitude ( TransOfTarget.position - transform.position ) < 7.50f ) { CurrAnimation = StateAnim.Attacking; } break; } case StateAnim.Attacking: {//TODO: Check if target moved // --> get path to new target position (switch to standing) //else attack //Debug.Log ("Entered Attacking"); HumanoidHandler CurrTarg = null; if( !isArmed ) { if( !animation.IsPlaying ("Hit") ) {Debug.Log ("Entered Hit"); animation.Play ("Hit"); } CurrTarg = Attack(); }// attack not armed else { }// attack armed if( CurrTarg != null && CurrTarg.currHealth <= 0 ) { CurrAnimation = StateAnim.Standing; } break; } case StateAnim.Standing: // Character is Standing // Standing is where all aquisition of new targets // or pathfinding to old, moved targets takes place {//TODO: if (hunting) // find nearest // if (found) // -->running/walking // else play() if( CurrBehavior == StateCharacterBehave.AtkNearest && HumanoidHandler.ListOfHumans.Count > 0 ) {// find nearest FindTarget (); // TODO: handle get/and wait for path to target seeker.StartPath( transform.position, TransOfTarget.position, SeekerSetPathToTargetCallBack ); CurrAnimation = StateAnim.Walking; } else {//Debug.Log ("Play Standing"); animation.Play ("Standing"); isTargeting = false; } break; } }// body animation blocks //if ( isArmed ) //{ // animation.Play ("HoldGun"); //} }// AnimateZombie() void AnimateHuman() { }// AnimateHuman() /// <summary> /// Attacks and returns current target or null if attack fails. /// </summary> HumanoidHandler Attack() { HumanoidHandler TargetHumanoid = null; if( HumanoidHandler.ListOfHumans.Count > 0 ) { // Find the current target as a HumanoidHandler for( int i = 0; i < HumanoidHandler.ListOfHumans.Count; i++) { if( HumanoidHandler.ListOfHumans[i].transform.GetInstanceID () == TransOfTarget.GetInstanceID () ) { TargetHumanoid = HumanoidHandler.ListOfHumans[i]; } } // increment time since last attack to prevent doing damage every frame timeSinceLastAttack += Time.deltaTime; // If the target was still in the list (still alive) // and it's time to attack, then do damage if( TargetHumanoid != null && timeSinceLastAttack > .5f ) { TargetHumanoid.currHealth -= baseAttackDamage; timeSinceLastAttack = 0f; //Debug.Log ("Entered Atk" + " health " + TargetHumanoid.currHealth); } } return TargetHumanoid; } /// <summary> /// Finds the nearest human. /// </summary> /// <returns> /// The nearest human. /// </returns> Transform FindNearestHuman() { if( HumanoidHandler.ListOfHumans.Count == 0 ) { Debug.LogWarning ("Finding target when human list is empty"); return null; } float minDist = 10000f; int index = -1; for(int i = 0; i < HumanoidHandler.ListOfHumans.Count; i++ ) { if( Vector3.Magnitude ( HumanoidHandler.ListOfHumans[i].transform.position - transform.position ) < minDist ) { minDist = Vector3.Magnitude ( HumanoidHandler.ListOfHumans[i].transform.position - transform.position ); index = i; } } return HumanoidHandler.ListOfHumans[index].transform; }// FindNearestHuman() /// <summary> /// Finds the target, the closest human. /// </summary>/ void FindTarget() {// TODO: (Maybe, depending on pathfinder functionality) record initial target Pos, in place of using the unneeded local NewTarget variable Transform NewTarget = FindNearestHuman(); TransOfTarget = NewTarget; }// FindTarget() /// <summary> /// A call back function called by the A* library once a path to the target is found. /// Sets the initial position of the target, the path to be followed, and /// the current path index. /// </summary> /// <param name='p'> /// P. passed in by the pathfinding library and is set as the path for this humanoid to walk. /// </param> void SeekerSetPathToTargetCallBack( Path p ) { Debug.Log ( "Returned from Seeker" ); if( !p.error ) { initTargetPos = TransOfTarget.position; path = p; currPathPointIndex = 0; } else { Debug.Log( "Seeker Error: " + p.error ); } }// Seeker CallBack() /// <summary> /// Translates and rotates the humanoid. /// </summary> /// <param name='speed'> /// Speed.the speed by which to translate. /// </param> void TranslateAndRotate(float speed ) { if( null == path ) {//Debug.Log( "path == null-->no path yet" ); return; } if( currPathPointIndex >= path.vectorPath.Count ) { // end of path reached //TODO: handle reaching target when reaching end of path but not the target return; } // get direction to next Path point // use the XZ component to rotate then use this 3D point to translate Vector3 tmpDir = (path.vectorPath[currPathPointIndex] - transform.position ).normalized; tmpDir *= speed * Time.deltaTime; // For rotating toward walkpoint, get angle between forward and target position // Get XZ forward dir of this Humanoid Vector2 tmpFwdXZ = new Vector2( transform.forward.x, transform.forward.z ).normalized; // Get 2D dir to target Vector2 tmpTargetXZ = new Vector2( tmpDir.x, tmpDir.z ).normalized; // Get angle between forward and target vectors to use in rotation float angle = Vector2.Angle (tmpTargetXZ,tmpFwdXZ); if( angle < 1.0f ) {// add 180 to correct the angle angle += 180.0f; } // if x of the next walk point is negative turn left else turn right if( transform.InverseTransformPoint (path.vectorPath[currPathPointIndex]).x < 0.0f ) { transform.Rotate( new Vector3(0f, 1f, 0f ), -angle * Time.deltaTime, Space.Self ); } else { transform.Rotate( new Vector3(0f, 1f, 0f ), angle * Time.deltaTime, Space.Self ); } controller.SimpleMove( tmpDir ); // if close enough to next Path point // increment to the next Path point if( Vector3.Magnitude ( path.vectorPath[currPathPointIndex] - transform.position ) < 15.0f && currPathPointIndex < path.vectorPath.Count - 1 )//distToIncrementPathPoint ) {Debug.Log ("incremented path index UBound: " + path.vectorPath.Count + " Curr Ind: " + currPathPointIndex ); currPathPointIndex++; } //Debug.Log ( "Dir: " + tmpDir //+ "Dist to next: " +Vector3.Magnitude ( path.vectorPath[currPathPointIndex] - transform.position ) ); }// TranslateAndRotate() }// class HumanoidHandler
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Reflection; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using ResGen = Microsoft.Build.Tasks.GenerateResource.ResGen; using Xunit; namespace Microsoft.Build.UnitTests { public class ResGen_Tests { /// <summary> /// Verify InputFiles: /// - Defaults to null, in which case the task just returns true and continues /// - If there are InputFiles, verify that they all show up on the command line /// - Verify that OutputFiles defaults appropriately /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void InputFiles() { ResGen t = new ResGen(); ITaskItem[] singleTestFile = { new TaskItem("foo.resx") }; ITaskItem[] singleOutput = { new TaskItem("foo.resources") }; ITaskItem[] multipleTestFiles = { new TaskItem("hello.resx"), new TaskItem("world.resx"), new TaskItem("!.resx") }; ITaskItem[] multipleOutputs = { new TaskItem("hello.resources"), new TaskItem("world.resources"), new TaskItem("!.resources") }; // Default: InputFiles is null Assert.Null(t.InputFiles); // "InputFiles is null by default" Assert.Null(t.OutputFiles); // "OutputFiles is null by default" ExecuteTaskAndVerifyLogContainsResource(t, true /* task passes */, "ResGen.NoInputFiles"); // One input file -- compile t.InputFiles = singleTestFile; t.StronglyTypedLanguage = null; t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.Version45)); Assert.Equal(singleTestFile, t.InputFiles); // "New InputFiles value should be set" Assert.Null(t.OutputFiles); // "OutputFiles is null until default name generation is triggered" string commandLineParameter = String.Join(",", new string[] { singleTestFile[0].ItemSpec, singleOutput[0].ItemSpec }); CommandLine.ValidateHasParameter(t, commandLineParameter, true /* resgen 4.0 supports response files */); CommandLine.ValidateHasParameter(t, @"/compile", true /* resgen 4.0 supports response files */); // One input file -- STR t.InputFiles = singleTestFile; t.StronglyTypedLanguage = "c#"; CommandLine.ValidateHasParameter(t, singleTestFile[0].ItemSpec, false /* resgen 4.0 does not appear to support response files for STR */); CommandLine.ValidateHasParameter(t, singleOutput[0].ItemSpec, false /* resgen 4.0 does not appear to support response files for STR */); CommandLine.ValidateHasParameter(t, "/str:c#,,,", false /* resgen 4.0 does not appear to support response files for STR */); // Multiple input files -- compile t.InputFiles = multipleTestFiles; t.OutputFiles = null; // want it to reset to default t.StronglyTypedLanguage = null; Assert.Equal(multipleTestFiles, t.InputFiles); // "New InputFiles value should be set" CommandLine.ValidateHasParameter(t, @"/compile", true /* resgen 4.0 supports response files */); for (int i = 0; i < multipleTestFiles.Length; i++) { commandLineParameter = String.Join(",", new string[] { multipleTestFiles[i].ItemSpec, multipleOutputs[i].ItemSpec }); CommandLine.ValidateHasParameter(t, commandLineParameter, true /* resgen 4.0 supports response files */); } // Multiple input files -- STR (should error) t.InputFiles = multipleTestFiles; t.StronglyTypedLanguage = "vb"; ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.STRLanguageButNotExactlyOneSourceFile"); } /// <summary> /// Verify OutputFiles: /// - Default values were tested by InputFiles() /// - Verify that if InputFiles and OutputFiles are different lengths (and both exist), an error is logged /// - Verify that if OutputFiles are set explicitly, they map and show up on the command line as expected /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void OutputFiles() { ResGen t = new ResGen(); ITaskItem[] differentLengthInput = { new TaskItem("hello.resx") }; ITaskItem[] differentLengthOutput = { new TaskItem("world.resources"), new TaskItem("!.resources") }; ITaskItem[] differentLengthDefaultOutput = { new TaskItem("hello.resources") }; // Different length inputs -- should error t.InputFiles = differentLengthInput; t.OutputFiles = differentLengthOutput; t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.Version45)); Assert.Equal(differentLengthInput, t.InputFiles); // "New InputFiles value should be set" Assert.Equal(differentLengthOutput, t.OutputFiles); // "New OutputFiles value should be set" ExecuteTaskAndVerifyLogContainsErrorFromResource ( t, "General.TwoVectorsMustHaveSameLength", differentLengthInput.Length, differentLengthOutput.Length, "InputFiles", "OutputFiles" ); // If only OutputFiles is set, then the task should return -- as far as // it's concerned, no work needs to be done. t = new ResGen(); // zero out the log t.InputFiles = null; t.OutputFiles = differentLengthOutput; t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.Version45)); Assert.Null(t.InputFiles); // "New InputFiles value should be set" Assert.Equal(differentLengthOutput, t.OutputFiles); // "New OutputFiles value should be set" ExecuteTaskAndVerifyLogContainsResource(t, true /* task passes */, "ResGen.NoInputFiles"); // However, if OutputFiles is set to null, it should revert back to default t.InputFiles = differentLengthInput; t.OutputFiles = null; Assert.Equal(differentLengthInput, t.InputFiles); // "New InputFiles value should be set" Assert.Null(t.OutputFiles); // "OutputFiles is null until default name generation is triggered" string commandLineParameter = String.Join(",", new string[] { differentLengthInput[0].ItemSpec, differentLengthDefaultOutput[0].ItemSpec }); CommandLine.ValidateHasParameter(t, commandLineParameter, true /* resgen 4.0 supports response files */); CommandLine.ValidateHasParameter(t, @"/compile", true /* resgen 4.0 supports response files */); // Explicitly setting output ITaskItem[] inputFiles = { new TaskItem("foo.resx") }; ITaskItem[] defaultOutput = { new TaskItem("foo.resources") }; ITaskItem[] explicitOutput = { new TaskItem("bar.txt") }; t.InputFiles = inputFiles; t.OutputFiles = null; Assert.Equal(inputFiles, t.InputFiles); // "New InputFiles value should be set" Assert.Null(t.OutputFiles); // "OutputFiles is null until default name generation is triggered" commandLineParameter = String.Join(",", new string[] { inputFiles[0].ItemSpec, defaultOutput[0].ItemSpec }); CommandLine.ValidateHasParameter(t, commandLineParameter, true /* resgen 4.0 supports response files */); CommandLine.ValidateHasParameter(t, @"/compile", true /* resgen 4.0 supports response files */); t.OutputFiles = explicitOutput; Assert.Equal(inputFiles, t.InputFiles); // "New InputFiles value should be set" Assert.Equal(explicitOutput, t.OutputFiles); // "New OutputFiles value should be set" commandLineParameter = String.Join(",", new string[] { inputFiles[0].ItemSpec, explicitOutput[0].ItemSpec }); CommandLine.ValidateHasParameter(t, commandLineParameter, true /* resgen 4.0 supports response files */); CommandLine.ValidateHasParameter(t, @"/compile", true /* resgen 4.0 supports response files */); } /// <summary> /// Tests ResGen's /publicClass switch /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void PublicClass() { ResGen t = new ResGen(); ITaskItem[] throwawayInput = { new TaskItem("hello.resx") }; t.InputFiles = throwawayInput; t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.Latest)); Assert.False(t.PublicClass); // "PublicClass should be false by default" CommandLine.ValidateNoParameterStartsWith(t, @"/publicClass", true /* resgen 4.0 supports response files */); t.PublicClass = true; Assert.True(t.PublicClass); // "PublicClass should be true" CommandLine.ValidateHasParameter(t, @"/publicClass", true /* resgen 4.0 supports response files */); } /// <summary> /// Tests the /r: parameter (passing in reference assemblies) /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void References() { ResGen t = new ResGen(); ITaskItem[] throwawayInput = { new TaskItem("hello.resx") }; ITaskItem a = new TaskItem(); ITaskItem b = new TaskItem(); t.InputFiles = throwawayInput; t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.Latest)); a.ItemSpec = "foo.dll"; b.ItemSpec = "bar.dll"; ITaskItem[] singleReference = { a }; ITaskItem[] multipleReferences = { a, b }; Assert.Null(t.References); // "References should be null by default" CommandLine.ValidateNoParameterStartsWith(t, "/r:", true /* resgen 4.0 supports response files */); // Single reference t.References = singleReference; Assert.Equal(singleReference, t.References); // "New References value should be set" CommandLine.ValidateHasParameter(t, "/r:" + singleReference[0].ItemSpec, true /* resgen 4.0 supports response files */); // MultipleReferences t.References = multipleReferences; Assert.Equal(multipleReferences, t.References); // "New References value should be set" foreach (ITaskItem reference in multipleReferences) { CommandLine.ValidateHasParameter(t, "/r:" + reference.ItemSpec, true /* resgen 4.0 supports response files */); } // test cases where command line length is equal to the maximum allowed length and just above the maximum allowed length // we do some calculation here to do ensure that the resulting command lines match these cases (see Case 1 and 2 below) // reference switch adds space + "/r:", (4 characters) int referenceSwitchDelta = 4; //subtract one because leading space is added to command line arguments int maxCommandLineLength = 28000 - 1; int referencePathLength = 200; //min reference argument is " /r:a.dll" int minReferenceArgumentLength = referenceSwitchDelta + "a.dll".Length; // reference name is of the form aaa...aaa###.dll (repeated a characters followed by 3 // digit identifier for uniqueness followed by the .dll file extension StringBuilder referencePathBuilder = new StringBuilder(); referencePathBuilder.Append('a', referencePathLength - (3 /* 3 digit identifier */ + 4 /* file extension */)); string longReferenceNameBase = referencePathBuilder.ToString(); // reference switch length plus the length of the reference path int referenceArgumentLength = referencePathLength + referenceSwitchDelta; t = CreateCommandLineResGen(); // compute command line with only one reference switch so remaining added reference // arguments will have the same length, since the first reference argument added may not have a // leading space List<ITaskItem> references = new List<ITaskItem>(); references.Add(new TaskItem() { ItemSpec = "a.dll" }); t.References = references.ToArray(); int baseCommandLineLength = CommandLine.GetCommandLine(t, false).Length; Assert.True(baseCommandLineLength < maxCommandLineLength); // "Cannot create command line less than the maximum allowed command line" // calculate how many reference arguments will need to be added and what the length of the last argument // should be so that the command line length is equal to the maximum allowed length int remainder; int quotient = Math.DivRem(maxCommandLineLength - baseCommandLineLength, referenceArgumentLength, out remainder); if (remainder < minReferenceArgumentLength) { remainder += referenceArgumentLength; quotient--; } // compute the length of the last reference argument int lastReferencePathLength = remainder - (4 /* switch length */ + 4 /* file extension */); for (int i = 0; i < quotient; i++) { string refIndex = i.ToString().PadLeft(3, '0'); references.Add(new TaskItem() { ItemSpec = (longReferenceNameBase + refIndex + ".dll") }); } // // Case 1: Command line length is equal to the maximum allowed value // // create last reference argument referencePathBuilder.Clear(); referencePathBuilder.Append('b', lastReferencePathLength).Append(".dll"); ITaskItem lastReference = new TaskItem() { ItemSpec = referencePathBuilder.ToString() }; references.Add(lastReference); // set references t.References = references.ToArray(); int commandLineLength = CommandLine.GetCommandLine(t, false).Length; Assert.Equal(commandLineLength, maxCommandLineLength); ExecuteTaskAndVerifyLogDoesNotContainResource ( t, false, "ResGen.CommandTooLong", CommandLine.GetCommandLine(t, false).Length ); VerifyLogDoesNotContainResource((MockEngine)t.BuildEngine, GetPrivateLog(t), "ToolTask.CommandTooLong", typeof(ResGen).Name); // // Case 2: Command line length is one more than the maximum allowed value // // make last reference name longer by one character so that command line should become too long referencePathBuilder.Insert(0, 'b'); lastReference.ItemSpec = referencePathBuilder.ToString(); // reset ResGen task, since execution can change the command line t = CreateCommandLineResGen(); t.References = references.ToArray(); commandLineLength = CommandLine.GetCommandLine(t, false).Length; Assert.Equal(commandLineLength, maxCommandLineLength + 1); ExecuteTaskAndVerifyLogContainsErrorFromResource ( t, "ResGen.CommandTooLong", CommandLine.GetCommandLine(t, false).Length ); VerifyLogDoesNotContainResource((MockEngine)t.BuildEngine, GetPrivateLog(t), "ToolTask.CommandTooLong", typeof(ResGen).Name); } private ResGen CreateCommandLineResGen() { ResGen t = new ResGen(); ITaskItem[] throwawayInput = { new TaskItem("hello.resx") }; // setting these values should ensure that no response file is used t.UseCommandProcessor = false; t.StronglyTypedLanguage = "CSharp"; t.InputFiles = throwawayInput; t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.Latest)); return t; } /// <summary> /// Tests the SdkToolsPath property: Should log an error if it's null or a bad path. /// </summary> [Fact] public void SdkToolsPath() { ResGen t = new ResGen(); string badParameterValue = @"C:\Program Files\Microsoft Visual Studio 10.0\My Fake SDK Path"; string goodParameterValue = Path.GetTempPath(); ITaskItem[] throwawayInput = { new TaskItem("hello.resx") }; // Without any inputs, the task just passes t.InputFiles = throwawayInput; Assert.Null(t.SdkToolsPath); // "SdkToolsPath should be null by default" ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.SdkOrToolPathNotSpecifiedOrInvalid", t.SdkToolsPath, t.ToolPath); t.SdkToolsPath = badParameterValue; Assert.Equal(badParameterValue, t.SdkToolsPath); // "New SdkToolsPath value should be set" ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.SdkOrToolPathNotSpecifiedOrInvalid", t.SdkToolsPath, t.ToolPath); MockEngine e = new MockEngine(); t.BuildEngine = e; t.SdkToolsPath = goodParameterValue; Assert.Equal(goodParameterValue, t.SdkToolsPath); // "New SdkToolsPath value should be set" bool taskPassed = t.Execute(); Assert.False(taskPassed); // "Task should still fail -- there are other things wrong with it." // but that particular error shouldn't be there anymore. string sdkToolsPathMessage = t.Log.FormatResourceString("ResGen.SdkOrToolPathNotSpecifiedOrInvalid", t.SdkToolsPath, t.ToolPath); string messageWithNoCode; string sdkToolsPathCode = t.Log.ExtractMessageCode(sdkToolsPathMessage, out messageWithNoCode); e.AssertLogDoesntContain(sdkToolsPathCode); } /// <summary> /// Verifies the parameters that for resgen.exe's /str: switch /// </summary> [Fact] public void StronglyTypedParameters() { ResGen t = new ResGen(); ITaskItem[] throwawayInput = { new TaskItem("hello.resx") }; string strLanguage = "c#"; string strNamespace = "Microsoft.Build.Foo"; string strClass = "MyFoo"; string strFile = "MyFoo.cs"; // Without any inputs, the task just passes t.InputFiles = throwawayInput; t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.Latest)); // Language is null by default Assert.Null(t.StronglyTypedLanguage); // "StronglyTypedLanguage should be null by default" CommandLine.ValidateNoParameterStartsWith(t, "/str:", false /* resgen 4.0 does not appear to support response files for STR */); // If other STR parameters are passed, we error, suggesting they might want a language as well. t.StronglyTypedNamespace = strNamespace; CommandLine.ValidateNoParameterStartsWith(t, "/str:", false /* resgen 4.0 does not appear to support response files for STR */); ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.STRClassNamespaceOrFilenameWithoutLanguage"); t.StronglyTypedNamespace = ""; t.StronglyTypedClassName = strClass; CommandLine.ValidateNoParameterStartsWith(t, "/str:", false /* resgen 4.0 does not appear to support response files for STR */); ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.STRClassNamespaceOrFilenameWithoutLanguage"); t.StronglyTypedClassName = ""; t.StronglyTypedFileName = strFile; CommandLine.ValidateNoParameterStartsWith(t, "/str:", false /* resgen 4.0 does not appear to support response files for STR */); ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.STRClassNamespaceOrFilenameWithoutLanguage"); // However, if it is passed, the /str: switch gets added t.StronglyTypedLanguage = strLanguage; t.StronglyTypedNamespace = ""; t.StronglyTypedClassName = ""; t.StronglyTypedFileName = ""; CommandLine.ValidateHasParameter(t, "/str:" + strLanguage + ",,,", false /* resgen 4.0 does not appear to support response files for STR */); t.StronglyTypedNamespace = strNamespace; CommandLine.ValidateHasParameter(t, "/str:" + strLanguage + "," + strNamespace + ",,", false /* resgen 4.0 does not appear to support response files for STR */); t.StronglyTypedClassName = strClass; CommandLine.ValidateHasParameter(t, "/str:" + strLanguage + "," + strNamespace + "," + strClass + ",", false /* resgen 4.0 does not appear to support response files for STR */); t.StronglyTypedFileName = strFile; CommandLine.ValidateHasParameter(t, "/str:" + strLanguage + "," + strNamespace + "," + strClass + "," + strFile, false /* resgen 4.0 does not appear to support response files for STR */); } /// <summary> /// Tests the ToolPath property: Should log an error if it's null or a bad path. /// </summary> [Fact] public void ToolPath() { ResGen t = new ResGen(); string badParameterValue = @"C:\Program Files\Microsoft Visual Studio 10.0\My Fake SDK Path"; string goodParameterValue = Path.GetTempPath(); ITaskItem[] throwawayInput = { new TaskItem("hello.resx") }; // Without any inputs, the task just passes t.InputFiles = throwawayInput; Assert.Null(t.ToolPath); // "ToolPath should be null by default" ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.SdkOrToolPathNotSpecifiedOrInvalid", t.SdkToolsPath, t.ToolPath); t.ToolPath = badParameterValue; Assert.Equal(badParameterValue, t.ToolPath); // "New ToolPath value should be set" ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.SdkOrToolPathNotSpecifiedOrInvalid", t.SdkToolsPath, t.ToolPath); MockEngine e = new MockEngine(); t.BuildEngine = e; t.ToolPath = goodParameterValue; Assert.Equal(goodParameterValue, t.ToolPath); // "New ToolPath value should be set" bool taskPassed = t.Execute(); Assert.False(taskPassed); // "Task should still fail -- there are other things wrong with it." // but that particular error shouldn't be there anymore. string toolPathMessage = t.Log.FormatResourceString("ResGen.SdkOrToolPathNotSpecifiedOrInvalid", t.SdkToolsPath, t.ToolPath); string messageWithNoCode; string toolPathCode = t.Log.ExtractMessageCode(toolPathMessage, out messageWithNoCode); e.AssertLogDoesntContain(toolPathCode); } /// <summary> /// Tests ResGen's /useSourcePath switch /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void UseSourcePath() { ResGen t = new ResGen(); ITaskItem[] throwawayInput = { new TaskItem("hello.resx") }; t.InputFiles = throwawayInput; t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.Latest)); Assert.False(t.UseSourcePath); // "UseSourcePath should be false by default" CommandLine.ValidateNoParameterStartsWith(t, @"/useSourcePath", true /* resgen 4.0 supports response files */); t.UseSourcePath = true; Assert.True(t.UseSourcePath); // "UseSourcePath should be true" CommandLine.ValidateHasParameter(t, @"/useSourcePath", true /* resgen 4.0 supports response files */); } #region Helper Functions /// <summary> /// Given an instance of a ResGen task, executes that task (assuming all necessary parameters /// have been set ahead of time) and verifies that the execution log contains the error /// corresponding to the resource name passed in. /// </summary> /// <param name="t">The task to execute and check</param> /// <param name="errorResource">The name of the resource string to check the log for</param> /// <param name="args">Arguments needed to format the resource string properly</param> private void ExecuteTaskAndVerifyLogContainsErrorFromResource(ResGen t, string errorResource, params object[] args) { ExecuteTaskAndVerifyLogContainsResource(t, false, errorResource, args); } /// <summary> /// Given an instance of a ResGen task, executes that task (assuming all necessary parameters /// have been set ahead of time), verifies that the task had the expected result, and checks /// the log for the string corresponding to the resource name passed in /// </summary> /// <param name="t">The task to execute and check</param> /// <param name="expectedResult">true if the task is expected to pass, false otherwise</param> /// <param name="resourceString">The name of the resource string to check the log for</param> /// <param name="args">Arguments needed to format the resource string properly</param> private void ExecuteTaskAndVerifyLogContainsResource(ResGen t, bool expectedResult, string resourceString, params object[] args) { MockEngine e = new MockEngine(); t.BuildEngine = e; bool taskPassed = t.Execute(); Assert.Equal(taskPassed, expectedResult); // "Unexpected task result" VerifyLogContainsResource(e, t.Log, resourceString, args); } /// <summary> /// Given a log and a resource string, acquires the text of that resource string and /// compares it to the log. Asserts if the log does not contain the desired string. /// </summary> /// <param name="e">The MockEngine that contains the log we're checking</param> /// <param name="log">The TaskLoggingHelper that we use to load the string resource</param> /// <param name="errorResource">The name of the resource string to check the log for</param> /// <param name="args">Arguments needed to format the resource string properly</param> private void VerifyLogContainsResource(MockEngine e, TaskLoggingHelper log, string messageResource, params object[] args) { string message = log.FormatResourceString(messageResource, args); e.AssertLogContains(message); } /// <summary> /// Given an instance of a ResGen task, executes that task (assuming all necessary parameters /// have been set ahead of time), verifies that the task had the expected result, and ensures /// the log does not contain the string corresponding to the resource name passed in /// </summary> /// <param name="t">The task to execute and check</param> /// <param name="expectedResult">true if the task is expected to pass, false otherwise</param> /// <param name="resourceString">The name of the resource string to check the log for</param> /// <param name="args">Arguments needed to format the resource string properly</param> private void ExecuteTaskAndVerifyLogDoesNotContainResource(ResGen t, bool expectedResult, string resourceString, params object[] args) { MockEngine e = new MockEngine(); t.BuildEngine = e; bool taskPassed = t.Execute(); Assert.Equal(taskPassed, expectedResult); // "Unexpected task result" VerifyLogDoesNotContainResource(e, t.Log, resourceString, args); } /// <summary> /// Given a log and a resource string, acquires the text of that resource string and /// compares it to the log. Assert fails if the log contain the desired string. /// </summary> /// <param name="e">The MockEngine that contains the log we're checking</param> /// <param name="log">The TaskLoggingHelper that we use to load the string resource</param> /// <param name="errorResource">The name of the resource string to check the log for</param> /// <param name="args">Arguments needed to format the resource string properly</param> private void VerifyLogDoesNotContainResource(MockEngine e, TaskLoggingHelper log, string messageResource, params object[] args) { string message = log.FormatResourceString(messageResource, args); e.AssertLogDoesntContain(message); } /// <summary> /// Gets the LogPrivate on the given ToolTask instance. We need to use reflection since /// LogPrivate is a private property. /// </summary> /// <returns></returns> static private TaskLoggingHelper GetPrivateLog(ToolTask task) { PropertyInfo logPrivateProperty = typeof(ToolTask).GetProperty("LogPrivate", BindingFlags.Instance | BindingFlags.NonPublic); return (TaskLoggingHelper)logPrivateProperty.GetValue(task, null); } #endregion // Helper Functions } }
// 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. #nullable enable using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Text; namespace System.IO { /// <summary>Contains internal path helpers that are shared between many projects.</summary> internal static partial class PathInternal { // All paths in Win32 ultimately end up becoming a path to a File object in the Windows object manager. Passed in paths get mapped through // DosDevice symbolic links in the object tree to actual File objects under \Devices. To illustrate, this is what happens with a typical // path "Foo" passed as a filename to any Win32 API: // // 1. "Foo" is recognized as a relative path and is appended to the current directory (say, "C:\" in our example) // 2. "C:\Foo" is prepended with the DosDevice namespace "\??\" // 3. CreateFile tries to create an object handle to the requested file "\??\C:\Foo" // 4. The Object Manager recognizes the DosDevices prefix and looks // a. First in the current session DosDevices ("\Sessions\1\DosDevices\" for example, mapped network drives go here) // b. If not found in the session, it looks in the Global DosDevices ("\GLOBAL??\") // 5. "C:" is found in DosDevices (in our case "\GLOBAL??\C:", which is a symbolic link to "\Device\HarddiskVolume6") // 6. The full path is now "\Device\HarddiskVolume6\Foo", "\Device\HarddiskVolume6" is a File object and parsing is handed off // to the registered parsing method for Files // 7. The registered open method for File objects is invoked to create the file handle which is then returned // // There are multiple ways to directly specify a DosDevices path. The final format of "\??\" is one way. It can also be specified // as "\\.\" (the most commonly documented way) and "\\?\". If the question mark syntax is used the path will skip normalization // (essentially GetFullPathName()) and path length checks. // Windows Kernel-Mode Object Manager // https://msdn.microsoft.com/en-us/library/windows/hardware/ff565763.aspx // https://channel9.msdn.com/Shows/Going+Deep/Windows-NT-Object-Manager // // Introduction to MS-DOS Device Names // https://msdn.microsoft.com/en-us/library/windows/hardware/ff548088.aspx // // Local and Global MS-DOS Device Names // https://msdn.microsoft.com/en-us/library/windows/hardware/ff554302.aspx internal const char DirectorySeparatorChar = '\\'; internal const char AltDirectorySeparatorChar = '/'; internal const char VolumeSeparatorChar = ':'; internal const char PathSeparator = ';'; internal const string DirectorySeparatorCharAsString = "\\"; internal const string ExtendedPathPrefix = @"\\?\"; internal const string UncPathPrefix = @"\\"; internal const string UncExtendedPrefixToInsert = @"?\UNC\"; internal const string UncExtendedPathPrefix = @"\\?\UNC\"; internal const string DevicePathPrefix = @"\\.\"; internal const string ParentDirectoryPrefix = @"..\"; internal const int MaxShortPath = 260; internal const int MaxShortDirectoryPath = 248; // \\?\, \\.\, \??\ internal const int DevicePrefixLength = 4; // \\ internal const int UncPrefixLength = 2; // \\?\UNC\, \\.\UNC\ internal const int UncExtendedPrefixLength = 8; /// <summary> /// Returns true if the given character is a valid drive letter /// </summary> internal static bool IsValidDriveChar(char value) { return (value >= 'A' && value <= 'Z') || (value >= 'a' && value <= 'z'); } internal static bool EndsWithPeriodOrSpace(string? path) { if (string.IsNullOrEmpty(path)) return false; char c = path[path.Length - 1]; return c == ' ' || c == '.'; } /// <summary> /// Adds the extended path prefix (\\?\) if not already a device path, IF the path is not relative, /// AND the path is more than 259 characters. (> MAX_PATH + null). This will also insert the extended /// prefix if the path ends with a period or a space. Trailing periods and spaces are normally eaten /// away from paths during normalization, but if we see such a path at this point it should be /// normalized and has retained the final characters. (Typically from one of the *Info classes) /// </summary> [return: NotNullIfNotNull("path")] internal static string? EnsureExtendedPrefixIfNeeded(string? path) { if (path != null && (path.Length >= MaxShortPath || EndsWithPeriodOrSpace(path))) { return EnsureExtendedPrefix(path); } else { return path; } } /// <summary> /// Adds the extended path prefix (\\?\) if not relative or already a device path. /// </summary> internal static string EnsureExtendedPrefix(string path) { // Putting the extended prefix on the path changes the processing of the path. It won't get normalized, which // means adding to relative paths will prevent them from getting the appropriate current directory inserted. // If it already has some variant of a device path (\??\, \\?\, \\.\, //./, etc.) we don't need to change it // as it is either correct or we will be changing the behavior. When/if Windows supports long paths implicitly // in the future we wouldn't want normalization to come back and break existing code. // In any case, all internal usages should be hitting normalize path (Path.GetFullPath) before they hit this // shimming method. (Or making a change that doesn't impact normalization, such as adding a filename to a // normalized base path.) if (IsPartiallyQualified(path.AsSpan()) || IsDevice(path.AsSpan())) return path; // Given \\server\share in longpath becomes \\?\UNC\server\share if (path.StartsWith(UncPathPrefix, StringComparison.OrdinalIgnoreCase)) return path.Insert(2, UncExtendedPrefixToInsert); return ExtendedPathPrefix + path; } /// <summary> /// Returns true if the path uses any of the DOS device path syntaxes. ("\\.\", "\\?\", or "\??\") /// </summary> internal static bool IsDevice(ReadOnlySpan<char> path) { // If the path begins with any two separators is will be recognized and normalized and prepped with // "\??\" for internal usage correctly. "\??\" is recognized and handled, "/??/" is not. return IsExtended(path) || ( path.Length >= DevicePrefixLength && IsDirectorySeparator(path[0]) && IsDirectorySeparator(path[1]) && (path[2] == '.' || path[2] == '?') && IsDirectorySeparator(path[3]) ); } /// <summary> /// Returns true if the path is a device UNC (\\?\UNC\, \\.\UNC\) /// </summary> internal static bool IsDeviceUNC(ReadOnlySpan<char> path) { return path.Length >= UncExtendedPrefixLength && IsDevice(path) && IsDirectorySeparator(path[7]) && path[4] == 'U' && path[5] == 'N' && path[6] == 'C'; } /// <summary> /// Returns true if the path uses the canonical form of extended syntax ("\\?\" or "\??\"). If the /// path matches exactly (cannot use alternate directory separators) Windows will skip normalization /// and path length checks. /// </summary> internal static bool IsExtended(ReadOnlySpan<char> path) { // While paths like "//?/C:/" will work, they're treated the same as "\\.\" paths. // Skipping of normalization will *only* occur if back slashes ('\') are used. return path.Length >= DevicePrefixLength && path[0] == '\\' && (path[1] == '\\' || path[1] == '?') && path[2] == '?' && path[3] == '\\'; } /// <summary> /// Check for known wildcard characters. '*' and '?' are the most common ones. /// </summary> internal static bool HasWildCardCharacters(ReadOnlySpan<char> path) { // Question mark is part of dos device syntax so we have to skip if we are int startIndex = IsDevice(path) ? ExtendedPathPrefix.Length : 0; // [MS - FSA] 2.1.4.4 Algorithm for Determining if a FileName Is in an Expression // https://msdn.microsoft.com/en-us/library/ff469270.aspx for (int i = startIndex; i < path.Length; i++) { char c = path[i]; if (c <= '?') // fast path for common case - '?' is highest wildcard character { if (c == '\"' || c == '<' || c == '>' || c == '*' || c == '?') return true; } } return false; } /// <summary> /// Gets the length of the root of the path (drive, share, etc.). /// </summary> internal static int GetRootLength(ReadOnlySpan<char> path) { int pathLength = path.Length; int i = 0; bool deviceSyntax = IsDevice(path); bool deviceUnc = deviceSyntax && IsDeviceUNC(path); if ((!deviceSyntax || deviceUnc) && pathLength > 0 && IsDirectorySeparator(path[0])) { // UNC or simple rooted path (e.g. "\foo", NOT "\\?\C:\foo") if (deviceUnc || (pathLength > 1 && IsDirectorySeparator(path[1]))) { // UNC (\\?\UNC\ or \\), scan past server\share // Start past the prefix ("\\" or "\\?\UNC\") i = deviceUnc ? UncExtendedPrefixLength : UncPrefixLength; // Skip two separators at most int n = 2; while (i < pathLength && (!IsDirectorySeparator(path[i]) || --n > 0)) i++; } else { // Current drive rooted (e.g. "\foo") i = 1; } } else if (deviceSyntax) { // Device path (e.g. "\\?\.", "\\.\") // Skip any characters following the prefix that aren't a separator i = DevicePrefixLength; while (i < pathLength && !IsDirectorySeparator(path[i])) i++; // If there is another separator take it, as long as we have had at least one // non-separator after the prefix (e.g. don't take "\\?\\", but take "\\?\a\") if (i < pathLength && i > DevicePrefixLength && IsDirectorySeparator(path[i])) i++; } else if (pathLength >= 2 && path[1] == VolumeSeparatorChar && IsValidDriveChar(path[0])) { // Valid drive specified path ("C:", "D:", etc.) i = 2; // If the colon is followed by a directory separator, move past it (e.g "C:\") if (pathLength > 2 && IsDirectorySeparator(path[2])) i++; } return i; } /// <summary> /// Returns true if the path specified is relative to the current drive or working directory. /// Returns false if the path is fixed to a specific drive or UNC path. This method does no /// validation of the path (URIs will be returned as relative as a result). /// </summary> /// <remarks> /// Handles paths that use the alternate directory separator. It is a frequent mistake to /// assume that rooted paths (Path.IsPathRooted) are not relative. This isn't the case. /// "C:a" is drive relative- meaning that it will be resolved against the current directory /// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory /// will not be used to modify the path). /// </remarks> internal static bool IsPartiallyQualified(ReadOnlySpan<char> path) { if (path.Length < 2) { // It isn't fixed, it must be relative. There is no way to specify a fixed // path with one character (or less). return true; } if (IsDirectorySeparator(path[0])) { // There is no valid way to specify a relative path with two initial slashes or // \? as ? isn't valid for drive relative paths and \??\ is equivalent to \\?\ return !(path[1] == '?' || IsDirectorySeparator(path[1])); } // The only way to specify a fixed path that doesn't begin with two slashes // is the drive, colon, slash format- i.e. C:\ return !((path.Length >= 3) && (path[1] == VolumeSeparatorChar) && IsDirectorySeparator(path[2]) // To match old behavior we'll check the drive character for validity as the path is technically // not qualified if you don't have a valid drive. "=:\" is the "=" file's default data stream. && IsValidDriveChar(path[0])); } /// <summary> /// True if the given character is a directory separator. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsDirectorySeparator(char c) { return c == DirectorySeparatorChar || c == AltDirectorySeparatorChar; } /// <summary> /// Normalize separators in the given path. Converts forward slashes into back slashes and compresses slash runs, keeping initial 2 if present. /// Also trims initial whitespace in front of "rooted" paths (see PathStartSkip). /// /// This effectively replicates the behavior of the legacy NormalizePath when it was called with fullCheck=false and expandShortpaths=false. /// The current NormalizePath gets directory separator normalization from Win32's GetFullPathName(), which will resolve relative paths and as /// such can't be used here (and is overkill for our uses). /// /// Like the current NormalizePath this will not try and analyze periods/spaces within directory segments. /// </summary> /// <remarks> /// The only callers that used to use Path.Normalize(fullCheck=false) were Path.GetDirectoryName() and Path.GetPathRoot(). Both usages do /// not need trimming of trailing whitespace here. /// /// GetPathRoot() could technically skip normalizing separators after the second segment- consider as a future optimization. /// /// For legacy desktop behavior with ExpandShortPaths: /// - It has no impact on GetPathRoot() so doesn't need consideration. /// - It could impact GetDirectoryName(), but only if the path isn't relative (C:\ or \\Server\Share). /// /// In the case of GetDirectoryName() the ExpandShortPaths behavior was undocumented and provided inconsistent results if the path was /// fixed/relative. For example: "C:\PROGRA~1\A.TXT" would return "C:\Program Files" while ".\PROGRA~1\A.TXT" would return ".\PROGRA~1". If you /// ultimately call GetFullPath() this doesn't matter, but if you don't or have any intermediate string handling could easily be tripped up by /// this undocumented behavior. /// /// We won't match this old behavior because: /// /// 1. It was undocumented /// 2. It was costly (extremely so if it actually contained '~') /// 3. Doesn't play nice with string logic /// 4. Isn't a cross-plat friendly concept/behavior /// </remarks> internal static string NormalizeDirectorySeparators(string path) { if (string.IsNullOrEmpty(path)) return path; char current; // Make a pass to see if we need to normalize so we can potentially skip allocating bool normalized = true; for (int i = 0; i < path.Length; i++) { current = path[i]; if (IsDirectorySeparator(current) && (current != DirectorySeparatorChar // Check for sequential separators past the first position (we need to keep initial two for UNC/extended) || (i > 0 && i + 1 < path.Length && IsDirectorySeparator(path[i + 1])))) { normalized = false; break; } } if (normalized) return path; var builder = new ValueStringBuilder(stackalloc char[MaxShortPath]); int start = 0; if (IsDirectorySeparator(path[start])) { start++; builder.Append(DirectorySeparatorChar); } for (int i = start; i < path.Length; i++) { current = path[i]; // If we have a separator if (IsDirectorySeparator(current)) { // If the next is a separator, skip adding this if (i + 1 < path.Length && IsDirectorySeparator(path[i + 1])) { continue; } // Ensure it is the primary separator current = DirectorySeparatorChar; } builder.Append(current); } return builder.ToString(); } /// <summary> /// Returns true if the path is effectively empty for the current OS. /// For unix, this is empty or null. For Windows, this is empty, null, or /// just spaces ((char)32). /// </summary> internal static bool IsEffectivelyEmpty(ReadOnlySpan<char> path) { if (path.IsEmpty) return true; foreach (char c in path) { if (c != ' ') return false; } return true; } } }
using System; using System.Collections.Generic; using System.Linq; namespace BTCPayServer.Client { public class Policies { public const string CanCreateLightningInvoiceInternalNode = "btcpay.server.cancreatelightninginvoiceinternalnode"; public const string CanCreateLightningInvoiceInStore = "btcpay.store.cancreatelightninginvoice"; public const string CanUseInternalLightningNode = "btcpay.server.canuseinternallightningnode"; public const string CanUseLightningNodeInStore = "btcpay.store.canuselightningnode"; public const string CanModifyServerSettings = "btcpay.server.canmodifyserversettings"; public const string CanModifyStoreSettings = "btcpay.store.canmodifystoresettings"; public const string CanModifyStoreWebhooks = "btcpay.store.webhooks.canmodifywebhooks"; public const string CanModifyStoreSettingsUnscoped = "btcpay.store.canmodifystoresettings:"; public const string CanViewStoreSettings = "btcpay.store.canviewstoresettings"; public const string CanViewInvoices = "btcpay.store.canviewinvoices"; public const string CanCreateInvoice = "btcpay.store.cancreateinvoice"; public const string CanModifyInvoices = "btcpay.store.canmodifyinvoices"; public const string CanViewPaymentRequests = "btcpay.store.canviewpaymentrequests"; public const string CanModifyPaymentRequests = "btcpay.store.canmodifypaymentrequests"; public const string CanModifyProfile = "btcpay.user.canmodifyprofile"; public const string CanViewProfile = "btcpay.user.canviewprofile"; public const string CanManageNotificationsForUser = "btcpay.user.canmanagenotificationsforuser"; public const string CanViewNotificationsForUser = "btcpay.user.canviewnotificationsforuser"; public const string CanViewUsers = "btcpay.server.canviewusers"; public const string CanCreateUser = "btcpay.server.cancreateuser"; public const string CanDeleteUser = "btcpay.user.candeleteuser"; public const string CanManagePullPayments = "btcpay.store.canmanagepullpayments"; public const string Unrestricted = "unrestricted"; public static IEnumerable<string> AllPolicies { get { yield return CanViewInvoices; yield return CanCreateInvoice; yield return CanModifyInvoices; yield return CanModifyStoreWebhooks; yield return CanModifyServerSettings; yield return CanModifyStoreSettings; yield return CanViewStoreSettings; yield return CanViewPaymentRequests; yield return CanModifyPaymentRequests; yield return CanModifyProfile; yield return CanViewProfile; yield return CanViewUsers; yield return CanCreateUser; yield return CanDeleteUser; yield return CanManageNotificationsForUser; yield return CanViewNotificationsForUser; yield return Unrestricted; yield return CanUseInternalLightningNode; yield return CanCreateLightningInvoiceInternalNode; yield return CanUseLightningNodeInStore; yield return CanCreateLightningInvoiceInStore; yield return CanManagePullPayments; } } public static bool IsValidPolicy(string policy) { return AllPolicies.Any(p => p.Equals(policy, StringComparison.OrdinalIgnoreCase)); } public static bool IsStorePolicy(string policy) { return policy.StartsWith("btcpay.store", StringComparison.OrdinalIgnoreCase); } public static bool IsStoreModifyPolicy(string policy) { return policy.StartsWith("btcpay.store.canmodify", StringComparison.OrdinalIgnoreCase); } public static bool IsServerPolicy(string policy) { return policy.StartsWith("btcpay.server", StringComparison.OrdinalIgnoreCase); } } public class Permission { public static Permission Create(string policy, string scope = null) { if (TryCreatePermission(policy, scope, out var r)) return r; throw new ArgumentException("Invalid Permission"); } public static bool TryCreatePermission(string policy, string scope, out Permission permission) { permission = null; if (policy == null) throw new ArgumentNullException(nameof(policy)); policy = policy.Trim().ToLowerInvariant(); if (!Policies.IsValidPolicy(policy)) return false; if (scope != null && !Policies.IsStorePolicy(policy)) return false; permission = new Permission(policy, scope); return true; } public static bool TryParse(string str, out Permission permission) { permission = null; if (str == null) throw new ArgumentNullException(nameof(str)); str = str.Trim(); var separator = str.IndexOf(':'); if (separator == -1) { str = str.ToLowerInvariant(); if (!Policies.IsValidPolicy(str)) return false; permission = new Permission(str, null); return true; } else { var policy = str.Substring(0, separator).ToLowerInvariant(); if (!Policies.IsValidPolicy(policy)) return false; if (!Policies.IsStorePolicy(policy)) return false; var storeId = str.Substring(separator + 1); if (storeId.Length == 0) return false; permission = new Permission(policy, storeId); return true; } } internal Permission(string policy, string scope) { Policy = policy; Scope = scope; } public bool Contains(Permission subpermission) { if (subpermission is null) throw new ArgumentNullException(nameof(subpermission)); if (!ContainsPolicy(subpermission.Policy)) { return false; } if (!Policies.IsStorePolicy(subpermission.Policy)) return true; return Scope == null || subpermission.Scope == this.Scope; } public static IEnumerable<Permission> ToPermissions(string[] permissions) { if (permissions == null) throw new ArgumentNullException(nameof(permissions)); foreach (var p in permissions) { if (TryParse(p, out var pp)) yield return pp; } } private bool ContainsPolicy(string subpolicy) { if (this.Policy == Policies.Unrestricted) return true; if (this.Policy == subpolicy) return true; switch (subpolicy) { case Policies.CanViewInvoices when this.Policy == Policies.CanModifyStoreSettings: case Policies.CanViewInvoices when this.Policy == Policies.CanModifyInvoices: case Policies.CanModifyStoreWebhooks when this.Policy == Policies.CanModifyStoreSettings: case Policies.CanViewInvoices when this.Policy == Policies.CanViewStoreSettings: case Policies.CanViewStoreSettings when this.Policy == Policies.CanModifyStoreSettings: case Policies.CanCreateInvoice when this.Policy == Policies.CanModifyStoreSettings: case Policies.CanModifyInvoices when this.Policy == Policies.CanModifyStoreSettings: case Policies.CanViewProfile when this.Policy == Policies.CanModifyProfile: case Policies.CanModifyPaymentRequests when this.Policy == Policies.CanModifyStoreSettings: case Policies.CanViewPaymentRequests when this.Policy == Policies.CanModifyStoreSettings: case Policies.CanViewPaymentRequests when this.Policy == Policies.CanViewStoreSettings: case Policies.CanCreateLightningInvoiceInternalNode when this.Policy == Policies.CanUseInternalLightningNode: case Policies.CanCreateLightningInvoiceInStore when this.Policy == Policies.CanUseLightningNodeInStore: case Policies.CanViewNotificationsForUser when this.Policy == Policies.CanManageNotificationsForUser: case Policies.CanUseInternalLightningNode when this.Policy == Policies.CanModifyServerSettings: return true; default: return false; } } public string Scope { get; } public string Policy { get; } public override string ToString() { if (Scope != null) { return $"{Policy}:{Scope}"; } return Policy; } public override bool Equals(object obj) { Permission item = obj as Permission; if (item == null) return false; return ToString().Equals(item.ToString()); } public static bool operator ==(Permission a, Permission b) { if (System.Object.ReferenceEquals(a, b)) return true; if (((object)a == null) || ((object)b == null)) return false; return a.ToString() == b.ToString(); } public static bool operator !=(Permission a, Permission b) { return !(a == b); } public override int GetHashCode() { return ToString().GetHashCode(); } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Runtime.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Security; using System.Threading; using System.Xml; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; #if USE_REFEMIT public sealed class ClassDataContract : DataContract #else internal sealed class ClassDataContract : DataContract #endif { [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - XmlDictionaryString(s) representing the XML namespaces for class members." + "statically cached and used from IL generated code. should ideally be Critical." + "marked SecurityNode to be callable from transparent IL generated code." + "not changed to property to avoid regressing performance; any changes to initalization should be reviewed.")] public XmlDictionaryString[] ContractNamespaces; [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - XmlDictionaryString(s) representing the XML element names for class members." + "statically cached and used from IL generated code. should ideally be Critical." + "marked SecurityNode to be callable from transparent IL generated code." + "not changed to property to avoid regressing performance; any changes to initalization should be reviewed.")] public XmlDictionaryString[] MemberNames; [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - XmlDictionaryString(s) representing the XML namespaces for class members." + "statically cached and used from IL generated code. should ideally be Critical." + "marked SecurityNode to be callable from transparent IL generated code." + "not changed to property to avoid regressing performance; any changes to initalization should be reviewed.")] public XmlDictionaryString[] MemberNamespaces; [Fx.Tag.SecurityNote(Critical = "XmlDictionaryString representing the XML namespaces for members of class." + "Statically cached and used from IL generated code.")] [SecurityCritical] XmlDictionaryString[] childElementNamespaces; [Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization. " + "Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")] [SecurityCritical] ClassDataContractCriticalHelper helper; [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'", Safe = "Doesn't leak anything.")] [SecuritySafeCritical] internal ClassDataContract() : base(new ClassDataContractCriticalHelper()) { InitClassDataContract(); } [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'", Safe = "Doesn't leak anything.")] [SecuritySafeCritical] internal ClassDataContract(Type type) : base(new ClassDataContractCriticalHelper(type)) { InitClassDataContract(); } [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'", Safe = "Doesn't leak anything.")] [SecuritySafeCritical] ClassDataContract(Type type, XmlDictionaryString ns, string[] memberNames) : base(new ClassDataContractCriticalHelper(type, ns, memberNames)) { InitClassDataContract(); } [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical fields; called from all constructors.")] [SecurityCritical] void InitClassDataContract() { this.helper = base.Helper as ClassDataContractCriticalHelper; this.ContractNamespaces = helper.ContractNamespaces; this.MemberNames = helper.MemberNames; this.MemberNamespaces = helper.MemberNamespaces; } internal ClassDataContract BaseContract { [Fx.Tag.SecurityNote(Critical = "Fetches the critical baseContract property.", Safe = "baseContract only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.BaseContract; } [Fx.Tag.SecurityNote(Critical = "Sets the critical baseContract property.")] [SecurityCritical] set { helper.BaseContract = value; } } internal List<DataMember> Members { [Fx.Tag.SecurityNote(Critical = "Fetches the critical members property.", Safe = "members only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.Members; } [Fx.Tag.SecurityNote(Critical = "Sets the critical members property.", Safe = "Protected for write if contract has underlyingType.")] [SecurityCritical] set { helper.Members = value; } } public XmlDictionaryString[] ChildElementNamespaces { [Fx.Tag.SecurityNote(Critical = "Sets the critical childElementNamespaces property.", Safe = "childElementNamespaces only needs to be protected for write; initialized in getter if null.")] [SecuritySafeCritical] get { if (this.childElementNamespaces == null) { lock (this) { if (this.childElementNamespaces == null) { if (helper.ChildElementNamespaces == null) { XmlDictionaryString[] tempChildElementamespaces = CreateChildElementNamespaces(); Thread.MemoryBarrier(); helper.ChildElementNamespaces = tempChildElementamespaces; } this.childElementNamespaces = helper.ChildElementNamespaces; } } } return this.childElementNamespaces; } } internal MethodInfo OnSerializing { [Fx.Tag.SecurityNote(Critical = "Fetches the critical onSerializing property.", Safe = "onSerializing only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.OnSerializing; } } internal MethodInfo OnSerialized { [Fx.Tag.SecurityNote(Critical = "Fetches the critical onSerialized property.", Safe = "onSerialized only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.OnSerialized; } } internal MethodInfo OnDeserializing { [Fx.Tag.SecurityNote(Critical = "Fetches the critical onDeserializing property.", Safe = "onDeserializing only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.OnDeserializing; } } internal MethodInfo OnDeserialized { [Fx.Tag.SecurityNote(Critical = "Fetches the critical onDeserialized property.", Safe = "onDeserialized only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.OnDeserialized; } } internal MethodInfo ExtensionDataSetMethod { [Fx.Tag.SecurityNote(Critical = "Fetches the critical extensionDataSetMethod property.", Safe = "extensionDataSetMethod only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.ExtensionDataSetMethod; } } internal override DataContractDictionary KnownDataContracts { [Fx.Tag.SecurityNote(Critical = "Fetches the critical knownDataContracts property.", Safe = "knownDataContracts only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.KnownDataContracts; } [Fx.Tag.SecurityNote(Critical = "Sets the critical knownDataContracts property.", Safe = "Protected for write if contract has underlyingType.")] [SecurityCritical] set { helper.KnownDataContracts = value; } } internal override bool IsISerializable { [Fx.Tag.SecurityNote(Critical = "Fetches the critical isISerializable property.", Safe = "isISerializable only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.IsISerializable; } [Fx.Tag.SecurityNote(Critical = "Sets the critical isISerializable property.", Safe = "Protected for write if contract has underlyingType.")] [SecurityCritical] set { helper.IsISerializable = value; } } internal bool IsNonAttributedType { [Fx.Tag.SecurityNote(Critical = "Fetches the critical IsNonAttributedType property.", Safe = "IsNonAttributedType only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.IsNonAttributedType; } } internal bool HasDataContract { [Fx.Tag.SecurityNote(Critical = "Fetches the critical hasDataContract property.", Safe = "hasDataContract only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.HasDataContract; } } internal bool HasExtensionData { [Fx.Tag.SecurityNote(Critical = "Fetches the critical hasExtensionData property.", Safe = "hasExtensionData only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.HasExtensionData; } } internal string SerializationExceptionMessage { [Fx.Tag.SecurityNote(Critical = "Fetches the critical serializationExceptionMessage property.", Safe = "serializationExceptionMessage only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.SerializationExceptionMessage; } } internal string DeserializationExceptionMessage { [Fx.Tag.SecurityNote(Critical = "Fetches the critical deserializationExceptionMessage property.", Safe = "deserializationExceptionMessage only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.DeserializationExceptionMessage; } } internal bool IsReadOnlyContract { get { return this.DeserializationExceptionMessage != null; } } [Fx.Tag.SecurityNote(Critical = "Fetches information about which constructor should be used to initialize ISerializable types.", Safe = "only needs to be protected for write.")] [SecuritySafeCritical] internal ConstructorInfo GetISerializableConstructor() { return helper.GetISerializableConstructor(); } [Fx.Tag.SecurityNote(Critical = "Fetches information about which constructor should be used to initialize non-attributed types that are valid for serialization.", Safe = "only needs to be protected for write.")] [SecuritySafeCritical] internal ConstructorInfo GetNonAttributedTypeConstructor() { return helper.GetNonAttributedTypeConstructor(); } internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate { [Fx.Tag.SecurityNote(Critical = "Fetches the critical xmlFormatWriterDelegate property.", Safe = "xmlFormatWriterDelegate only needs to be protected for write; initialized in getter if null.")] [SecuritySafeCritical] get { if (helper.XmlFormatWriterDelegate == null) { lock (this) { if (helper.XmlFormatWriterDelegate == null) { XmlFormatClassWriterDelegate tempDelegate = new XmlFormatWriterGenerator().GenerateClassWriter(this); Thread.MemoryBarrier(); helper.XmlFormatWriterDelegate = tempDelegate; } } } return helper.XmlFormatWriterDelegate; } } internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate { [Fx.Tag.SecurityNote(Critical = "Fetches the critical xmlFormatReaderDelegate property.", Safe = "xmlFormatReaderDelegate only needs to be protected for write; initialized in getter if null.")] [SecuritySafeCritical] get { if (helper.XmlFormatReaderDelegate == null) { lock (this) { if (helper.XmlFormatReaderDelegate == null) { if (this.IsReadOnlyContract) { ThrowInvalidDataContractException(helper.DeserializationExceptionMessage, null /*type*/); } XmlFormatClassReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateClassReader(this); Thread.MemoryBarrier(); helper.XmlFormatReaderDelegate = tempDelegate; } } } return helper.XmlFormatReaderDelegate; } } internal static ClassDataContract CreateClassDataContractForKeyValue(Type type, XmlDictionaryString ns, string[] memberNames) { return new ClassDataContract(type, ns, memberNames); } internal static void CheckAndAddMember(List<DataMember> members, DataMember memberContract, Dictionary<string, DataMember> memberNamesTable) { DataMember existingMemberContract; if (memberNamesTable.TryGetValue(memberContract.Name, out existingMemberContract)) { Type declaringType = memberContract.MemberInfo.DeclaringType; DataContract.ThrowInvalidDataContractException( SR.GetString((declaringType.IsEnum ? SR.DupEnumMemberValue : SR.DupMemberName), existingMemberContract.MemberInfo.Name, memberContract.MemberInfo.Name, DataContract.GetClrTypeFullName(declaringType), memberContract.Name), declaringType); } memberNamesTable.Add(memberContract.Name, memberContract); members.Add(memberContract); } internal static XmlDictionaryString GetChildNamespaceToDeclare(DataContract dataContract, Type childType, XmlDictionary dictionary) { childType = DataContract.UnwrapNullableType(childType); if (!childType.IsEnum && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(childType) && DataContract.GetBuiltInDataContract(childType) == null && childType != Globals.TypeOfDBNull) { string ns = DataContract.GetStableName(childType).Namespace; if (ns.Length > 0 && ns != dataContract.Namespace.Value) return dictionary.Add(ns); } return null; } [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - callers may need to depend on isNonAttributedType for a security decision." + "isNonAttributedType must be calculated correctly." + "IsNonAttributedTypeValidForSerialization is used as part of the isNonAttributedType calculation and is therefore marked with SecurityNote.", Safe = "Does not let caller influence isNonAttributedType calculation; no harm in leaking value.")] // check whether a corresponding update is required in DataContractCriticalHelper.CreateDataContract static internal bool IsNonAttributedTypeValidForSerialization(Type type) { if (type.IsArray) return false; if (type.IsEnum) return false; if (type.IsGenericParameter) return false; if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) return false; if (type.IsPointer) return false; if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) return false; Type[] interfaceTypes = type.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { if (CollectionDataContract.IsCollectionInterface(interfaceType)) return false; } if (type.IsSerializable) return false; if (Globals.TypeOfISerializable.IsAssignableFrom(type)) return false; if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) return false; if (type == Globals.TypeOfExtensionDataObject) return false; if (type.IsValueType) { return type.IsVisible; } else { return (type.IsVisible && type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, Globals.EmptyTypeArray, null) != null); } } XmlDictionaryString[] CreateChildElementNamespaces() { if (Members == null) return null; XmlDictionaryString[] baseChildElementNamespaces = null; if (this.BaseContract != null) baseChildElementNamespaces = this.BaseContract.ChildElementNamespaces; int baseChildElementNamespaceCount = (baseChildElementNamespaces != null) ? baseChildElementNamespaces.Length : 0; XmlDictionaryString[] childElementNamespaces = new XmlDictionaryString[Members.Count + baseChildElementNamespaceCount]; if (baseChildElementNamespaceCount > 0) Array.Copy(baseChildElementNamespaces, 0, childElementNamespaces, 0, baseChildElementNamespaces.Length); XmlDictionary dictionary = new XmlDictionary(); for (int i = 0; i < this.Members.Count; i++) { childElementNamespaces[i + baseChildElementNamespaceCount] = GetChildNamespaceToDeclare(this, this.Members[i].MemberType, dictionary); } return childElementNamespaces; } [Fx.Tag.SecurityNote(Critical = "Calls critical method on helper.", Safe = "Doesn't leak anything.")] [SecuritySafeCritical] void EnsureMethodsImported() { helper.EnsureMethodsImported(); } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { XmlFormatWriterDelegate(xmlWriter, obj, context, this); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { xmlReader.Read(); object o = XmlFormatReaderDelegate(xmlReader, context, MemberNames, MemberNamespaces); xmlReader.ReadEndElement(); return o; } [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - calculates whether this class requires MemberAccessPermission for deserialization." + "Since this information is used to determine whether to give the generated code access " + "permissions to private members, any changes to the logic should be reviewed.")] internal bool RequiresMemberAccessForRead(SecurityException securityException) { EnsureMethodsImported(); if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustDataContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForRead(securityException)) return true; if (ConstructorRequiresMemberAccess(GetISerializableConstructor())) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustISerializableNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (ConstructorRequiresMemberAccess(GetNonAttributedTypeConstructor())) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustNonAttributedSerializableTypeNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnDeserializing)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustDataContractOnDeserializingNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnDeserializing.Name), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnDeserialized)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustDataContractOnDeserializedNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnDeserialized.Name), securityException)); } return true; } if (this.Members != null) { for (int i = 0; i < this.Members.Count; i++) { if (this.Members[i].RequiresMemberAccessForSet()) { if (securityException != null) { if (this.Members[i].MemberInfo is FieldInfo) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustDataContractFieldSetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustDataContractPropertySetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } } return true; } } } return false; } [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - calculates whether this class requires MemberAccessPermission for serialization." + " Since this information is used to determine whether to give the generated code access" + " permissions to private members, any changes to the logic should be reviewed.")] internal bool RequiresMemberAccessForWrite(SecurityException securityException) { EnsureMethodsImported(); if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustDataContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForWrite(securityException)) return true; if (MethodRequiresMemberAccess(this.OnSerializing)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustDataContractOnSerializingNotPublic, DataContract.GetClrTypeFullName(this.UnderlyingType), this.OnSerializing.Name), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnSerialized)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustDataContractOnSerializedNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnSerialized.Name), securityException)); } return true; } if (this.Members != null) { for (int i = 0; i < this.Members.Count; i++) { if (this.Members[i].RequiresMemberAccessForGet()) { if (securityException != null) { if (this.Members[i].MemberInfo is FieldInfo) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustDataContractFieldGetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustDataContractPropertyGetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } } return true; } } } return false; } [Fx.Tag.SecurityNote(Critical = "Holds all state used for (de)serializing classes." + " Since the data is cached statically, we lock down access to it.")] [SecurityCritical(SecurityCriticalScope.Everything)] class ClassDataContractCriticalHelper : DataContract.DataContractCriticalHelper { ClassDataContract baseContract; List<DataMember> members; MethodInfo onSerializing, onSerialized; MethodInfo onDeserializing, onDeserialized; MethodInfo extensionDataSetMethod; DataContractDictionary knownDataContracts; string serializationExceptionMessage; bool isISerializable; bool isKnownTypeAttributeChecked; bool isMethodChecked; bool hasExtensionData; [Fx.Tag.SecurityNote(Miscellaneous = "in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and hasDataContract.")] bool isNonAttributedType; [Fx.Tag.SecurityNote(Miscellaneous = "in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and isNonAttributedType.")] bool hasDataContract; XmlDictionaryString[] childElementNamespaces; XmlFormatClassReaderDelegate xmlFormatReaderDelegate; XmlFormatClassWriterDelegate xmlFormatWriterDelegate; public XmlDictionaryString[] ContractNamespaces; public XmlDictionaryString[] MemberNames; public XmlDictionaryString[] MemberNamespaces; internal ClassDataContractCriticalHelper() : base() { } internal ClassDataContractCriticalHelper(Type type) : base(type) { XmlQualifiedName stableName = GetStableNameAndSetHasDataContract(type); if (type == Globals.TypeOfDBNull) { this.StableName = stableName; this.members = new List<DataMember>(); XmlDictionary dictionary = new XmlDictionary(2); this.Name = dictionary.Add(StableName.Name); this.Namespace = dictionary.Add(StableName.Namespace); this.ContractNamespaces = this.MemberNames = this.MemberNamespaces = new XmlDictionaryString[] { }; EnsureMethodsImported(); return; } Type baseType = type.BaseType; this.isISerializable = (Globals.TypeOfISerializable.IsAssignableFrom(type)); SetIsNonAttributedType(type); if (this.isISerializable) { if (HasDataContract) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.ISerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type)))); if (baseType != null && !(baseType.IsSerializable && Globals.TypeOfISerializable.IsAssignableFrom(baseType))) baseType = null; } this.IsValueType = type.IsValueType; if (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) { DataContract baseContract = DataContract.GetDataContract(baseType); if (baseContract is CollectionDataContract) this.BaseContract = ((CollectionDataContract)baseContract).SharedTypeContract as ClassDataContract; else this.BaseContract = baseContract as ClassDataContract; if (this.BaseContract != null && this.BaseContract.IsNonAttributedType && !this.isNonAttributedType) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError (new InvalidDataContractException(SR.GetString(SR.AttributedTypesCannotInheritFromNonAttributedSerializableTypes, DataContract.GetClrTypeFullName(type), DataContract.GetClrTypeFullName(baseType)))); } } else this.BaseContract = null; hasExtensionData = (Globals.TypeOfIExtensibleDataObject.IsAssignableFrom(type)); if (hasExtensionData && !HasDataContract && !IsNonAttributedType) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.OnlyDataContractTypesCanHaveExtensionData, DataContract.GetClrTypeFullName(type)))); if (this.isISerializable) SetDataContractName(stableName); else { this.StableName = stableName; ImportDataMembers(); XmlDictionary dictionary = new XmlDictionary(2 + Members.Count); Name = dictionary.Add(StableName.Name); Namespace = dictionary.Add(StableName.Namespace); int baseMemberCount = 0; int baseContractCount = 0; if (BaseContract == null) { MemberNames = new XmlDictionaryString[Members.Count]; MemberNamespaces = new XmlDictionaryString[Members.Count]; ContractNamespaces = new XmlDictionaryString[1]; } else { if (BaseContract.IsReadOnlyContract) { this.serializationExceptionMessage = BaseContract.SerializationExceptionMessage; } baseMemberCount = BaseContract.MemberNames.Length; MemberNames = new XmlDictionaryString[Members.Count + baseMemberCount]; Array.Copy(BaseContract.MemberNames, MemberNames, baseMemberCount); MemberNamespaces = new XmlDictionaryString[Members.Count + baseMemberCount]; Array.Copy(BaseContract.MemberNamespaces, MemberNamespaces, baseMemberCount); baseContractCount = BaseContract.ContractNamespaces.Length; ContractNamespaces = new XmlDictionaryString[1 + baseContractCount]; Array.Copy(BaseContract.ContractNamespaces, ContractNamespaces, baseContractCount); } ContractNamespaces[baseContractCount] = Namespace; for (int i = 0; i < Members.Count; i++) { MemberNames[i + baseMemberCount] = dictionary.Add(Members[i].Name); MemberNamespaces[i + baseMemberCount] = Namespace; } } EnsureMethodsImported(); } internal ClassDataContractCriticalHelper(Type type, XmlDictionaryString ns, string[] memberNames) : base(type) { this.StableName = new XmlQualifiedName(GetStableNameAndSetHasDataContract(type).Name, ns.Value); ImportDataMembers(); XmlDictionary dictionary = new XmlDictionary(1 + Members.Count); Name = dictionary.Add(StableName.Name); Namespace = ns; ContractNamespaces = new XmlDictionaryString[] { Namespace }; MemberNames = new XmlDictionaryString[Members.Count]; MemberNamespaces = new XmlDictionaryString[Members.Count]; for (int i = 0; i < Members.Count; i++) { Members[i].Name = memberNames[i]; MemberNames[i] = dictionary.Add(Members[i].Name); MemberNamespaces[i] = Namespace; } EnsureMethodsImported(); } void EnsureIsReferenceImported(Type type) { DataContractAttribute dataContractAttribute; bool isReference = false; bool hasDataContractAttribute = TryGetDCAttribute(type, out dataContractAttribute); if (BaseContract != null) { if (hasDataContractAttribute && dataContractAttribute.IsReferenceSetExplicitly) { bool baseIsReference = this.BaseContract.IsReference; if ((baseIsReference && !dataContractAttribute.IsReference) || (!baseIsReference && dataContractAttribute.IsReference)) { DataContract.ThrowInvalidDataContractException( SR.GetString(SR.InconsistentIsReference, DataContract.GetClrTypeFullName(type), dataContractAttribute.IsReference, DataContract.GetClrTypeFullName(this.BaseContract.UnderlyingType), this.BaseContract.IsReference), type); } else { isReference = dataContractAttribute.IsReference; } } else { isReference = this.BaseContract.IsReference; } } else if (hasDataContractAttribute) { if (dataContractAttribute.IsReference) isReference = dataContractAttribute.IsReference; } if (isReference && type.IsValueType) { DataContract.ThrowInvalidDataContractException( SR.GetString(SR.ValueTypeCannotHaveIsReference, DataContract.GetClrTypeFullName(type), true, false), type); return; } this.IsReference = isReference; } void ImportDataMembers() { Type type = this.UnderlyingType; EnsureIsReferenceImported(type); List<DataMember> tempMembers = new List<DataMember>(); Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>(); MemberInfo[] memberInfos; if (this.isNonAttributedType) { memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); } else { memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } for (int i = 0; i < memberInfos.Length; i++) { MemberInfo member = memberInfos[i]; if (HasDataContract) { object[] memberAttributes = member.GetCustomAttributes(typeof(DataMemberAttribute), false); if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.GetString(SR.TooManyDataMembers, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name)); DataMember memberContract = new DataMember(member); if (member.MemberType == MemberTypes.Property) { PropertyInfo property = (PropertyInfo)member; MethodInfo getMethod = property.GetGetMethod(true); if (getMethod != null && IsMethodOverriding(getMethod)) continue; MethodInfo setMethod = property.GetSetMethod(true); if (setMethod != null && IsMethodOverriding(setMethod)) continue; if (getMethod == null) ThrowInvalidDataContractException(SR.GetString(SR.NoGetMethodForProperty, property.DeclaringType, property.Name)); if (setMethod == null) { if (!SetIfGetOnlyCollection(memberContract, skipIfReadOnlyContract: false)) { this.serializationExceptionMessage = SR.GetString(SR.NoSetMethodForProperty, property.DeclaringType, property.Name); } } if (getMethod.GetParameters().Length > 0) ThrowInvalidDataContractException(SR.GetString(SR.IndexedPropertyCannotBeSerialized, property.DeclaringType, property.Name)); } else if (member.MemberType != MemberTypes.Field) ThrowInvalidDataContractException(SR.GetString(SR.InvalidMember, DataContract.GetClrTypeFullName(type), member.Name)); DataMemberAttribute memberAttribute = (DataMemberAttribute)memberAttributes[0]; if (memberAttribute.IsNameSetExplicitly) { if (memberAttribute.Name == null || memberAttribute.Name.Length == 0) ThrowInvalidDataContractException(SR.GetString(SR.InvalidDataMemberName, member.Name, DataContract.GetClrTypeFullName(type))); memberContract.Name = memberAttribute.Name; } else memberContract.Name = member.Name; memberContract.Name = DataContract.EncodeLocalName(memberContract.Name); memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); memberContract.IsRequired = memberAttribute.IsRequired; if (memberAttribute.IsRequired && this.IsReference) { ThrowInvalidDataContractException( SR.GetString(SR.IsRequiredDataMemberOnIsReferenceDataContractType, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name, true), type); } memberContract.EmitDefaultValue = memberAttribute.EmitDefaultValue; memberContract.Order = memberAttribute.Order; CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } } else if (this.isNonAttributedType) { FieldInfo field = member as FieldInfo; PropertyInfo property = member as PropertyInfo; if ((field == null && property == null) || (field != null && field.IsInitOnly)) continue; object[] memberAttributes = member.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), false); if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.GetString(SR.TooManyIgnoreDataMemberAttributes, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name)); else continue; } DataMember memberContract = new DataMember(member); if (property != null) { MethodInfo getMethod = property.GetGetMethod(); if (getMethod == null || IsMethodOverriding(getMethod) || getMethod.GetParameters().Length > 0) continue; MethodInfo setMethod = property.GetSetMethod(true); if (setMethod == null) { // if the collection doesn't have the 'Add' method, we will skip it, for compatibility with 4.0 if (!SetIfGetOnlyCollection(memberContract, skipIfReadOnlyContract: true)) continue; } else { if (!setMethod.IsPublic || IsMethodOverriding(setMethod)) continue; } //skip ExtensionData member of type ExtensionDataObject if IExtensibleDataObject is implemented in non-attributed type if (this.hasExtensionData && memberContract.MemberType == Globals.TypeOfExtensionDataObject && member.Name == Globals.ExtensionDataObjectPropertyName) continue; } memberContract.Name = DataContract.EncodeLocalName(member.Name); memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } else { FieldInfo field = member as FieldInfo; if (field != null && !field.IsNotSerialized) { DataMember memberContract = new DataMember(member); memberContract.Name = DataContract.EncodeLocalName(member.Name); object[] optionalFields = field.GetCustomAttributes(Globals.TypeOfOptionalFieldAttribute, false); if (optionalFields == null || optionalFields.Length == 0) { if (this.IsReference) { ThrowInvalidDataContractException( SR.GetString(SR.NonOptionalFieldMemberOnIsReferenceSerializableType, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name, true), type); } memberContract.IsRequired = true; } memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } } } if (tempMembers.Count > 1) tempMembers.Sort(DataMemberComparer.Singleton); SetIfMembersHaveConflict(tempMembers); Thread.MemoryBarrier(); members = tempMembers; } bool SetIfGetOnlyCollection(DataMember memberContract, bool skipIfReadOnlyContract) { //OK to call IsCollection here since the use of surrogated collection types is not supported in get-only scenarios if (CollectionDataContract.IsCollection(memberContract.MemberType, false /*isConstructorRequired*/, skipIfReadOnlyContract) && !memberContract.MemberType.IsValueType) { memberContract.IsGetOnlyCollection = true; return true; } return false; } void SetIfMembersHaveConflict(List<DataMember> members) { if (BaseContract == null) return; int baseTypeIndex = 0; List<Member> membersInHierarchy = new List<Member>(); foreach (DataMember member in members) { membersInHierarchy.Add(new Member(member, this.StableName.Namespace, baseTypeIndex)); } ClassDataContract currContract = BaseContract; while (currContract != null) { baseTypeIndex++; foreach (DataMember member in currContract.Members) { membersInHierarchy.Add(new Member(member, currContract.StableName.Namespace, baseTypeIndex)); } currContract = currContract.BaseContract; } IComparer<Member> comparer = DataMemberConflictComparer.Singleton; membersInHierarchy.Sort(comparer); for (int i = 0; i < membersInHierarchy.Count - 1; i++) { int startIndex = i; int endIndex = i; bool hasConflictingType = false; while (endIndex < membersInHierarchy.Count - 1 && String.CompareOrdinal(membersInHierarchy[endIndex].member.Name, membersInHierarchy[endIndex + 1].member.Name) == 0 && String.CompareOrdinal(membersInHierarchy[endIndex].ns, membersInHierarchy[endIndex + 1].ns) == 0) { membersInHierarchy[endIndex].member.ConflictingMember = membersInHierarchy[endIndex + 1].member; if (!hasConflictingType) { if (membersInHierarchy[endIndex + 1].member.HasConflictingNameAndType) { hasConflictingType = true; } else { hasConflictingType = (membersInHierarchy[endIndex].member.MemberType != membersInHierarchy[endIndex + 1].member.MemberType); } } endIndex++; } if (hasConflictingType) { for (int j = startIndex; j <= endIndex; j++) { membersInHierarchy[j].member.HasConflictingNameAndType = true; } } i = endIndex + 1; } } [Fx.Tag.SecurityNote(Critical = "Sets the critical hasDataContract field.", Safe = "Uses a trusted critical API (DataContract.GetStableName) to calculate the value, does not accept the value from the caller.")] [SecuritySafeCritical] XmlQualifiedName GetStableNameAndSetHasDataContract(Type type) { return DataContract.GetStableName(type, out this.hasDataContract); } [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - callers may need to depend on isNonAttributedType for a security decision." + "isNonAttributedType must be calculated correctly." + "SetIsNonAttributedType should not be called before GetStableNameAndSetHasDataContract since it is dependent on the correct calculation of hasDataContract.", Safe = "Does not let caller influence isNonAttributedType calculation; no harm in leaking value.")] void SetIsNonAttributedType(Type type) { this.isNonAttributedType = !type.IsSerializable && !this.hasDataContract && IsNonAttributedTypeValidForSerialization(type); } static bool IsMethodOverriding(MethodInfo method) { return method.IsVirtual && ((method.Attributes & MethodAttributes.NewSlot) == 0); } internal void EnsureMethodsImported() { if (!isMethodChecked && UnderlyingType != null) { lock (this) { if (!isMethodChecked) { Type type = this.UnderlyingType; MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < methods.Length; i++) { MethodInfo method = methods[i]; Type prevAttributeType = null; ParameterInfo[] parameters = method.GetParameters(); if (HasExtensionData && IsValidExtensionDataSetMethod(method, parameters)) { if (method.Name == Globals.ExtensionDataSetExplicitMethod || !method.IsPublic) extensionDataSetMethod = XmlFormatGeneratorStatics.ExtensionDataSetExplicitMethodInfo; else extensionDataSetMethod = method; } if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializingAttribute, onSerializing, ref prevAttributeType)) onSerializing = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializedAttribute, onSerialized, ref prevAttributeType)) onSerialized = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializingAttribute, onDeserializing, ref prevAttributeType)) onDeserializing = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializedAttribute, onDeserialized, ref prevAttributeType)) onDeserialized = method; } Thread.MemoryBarrier(); isMethodChecked = true; } } } } bool IsValidExtensionDataSetMethod(MethodInfo method, ParameterInfo[] parameters) { if (method.Name == Globals.ExtensionDataSetExplicitMethod || method.Name == Globals.ExtensionDataSetMethod) { if (extensionDataSetMethod != null) ThrowInvalidDataContractException(SR.GetString(SR.DuplicateExtensionDataSetMethod, method, extensionDataSetMethod, DataContract.GetClrTypeFullName(method.DeclaringType))); if (method.ReturnType != Globals.TypeOfVoid) DataContract.ThrowInvalidDataContractException(SR.GetString(SR.ExtensionDataSetMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfExtensionDataObject) DataContract.ThrowInvalidDataContractException(SR.GetString(SR.ExtensionDataSetParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfExtensionDataObject), method.DeclaringType); return true; } return false; } static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType) { if (method.IsDefined(attributeType, false)) { if (currentCallback != null) DataContract.ThrowInvalidDataContractException(SR.GetString(SR.DuplicateCallback, method, currentCallback, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); else if (prevAttributeType != null) DataContract.ThrowInvalidDataContractException(SR.GetString(SR.DuplicateAttribute, prevAttributeType, attributeType, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); else if (method.IsVirtual) DataContract.ThrowInvalidDataContractException(SR.GetString(SR.CallbacksCannotBeVirtualMethods, method, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); else { if (method.ReturnType != Globals.TypeOfVoid) DataContract.ThrowInvalidDataContractException(SR.GetString(SR.CallbackMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfStreamingContext) DataContract.ThrowInvalidDataContractException(SR.GetString(SR.CallbackParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfStreamingContext), method.DeclaringType); prevAttributeType = attributeType; } return true; } return false; } internal ClassDataContract BaseContract { get { return baseContract; } set { baseContract = value; if (baseContract != null && IsValueType) ThrowInvalidDataContractException(SR.GetString(SR.ValueTypeCannotHaveBaseType, StableName.Name, StableName.Namespace, baseContract.StableName.Name, baseContract.StableName.Namespace)); } } internal List<DataMember> Members { get { return members; } set { members = value; } } internal MethodInfo OnSerializing { get { EnsureMethodsImported(); return onSerializing; } } internal MethodInfo OnSerialized { get { EnsureMethodsImported(); return onSerialized; } } internal MethodInfo OnDeserializing { get { EnsureMethodsImported(); return onDeserializing; } } internal MethodInfo OnDeserialized { get { EnsureMethodsImported(); return onDeserialized; } } internal MethodInfo ExtensionDataSetMethod { get { EnsureMethodsImported(); return extensionDataSetMethod; } } internal override DataContractDictionary KnownDataContracts { get { if (!isKnownTypeAttributeChecked && UnderlyingType != null) { lock (this) { if (!isKnownTypeAttributeChecked) { knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType); Thread.MemoryBarrier(); isKnownTypeAttributeChecked = true; } } } return knownDataContracts; } set { knownDataContracts = value; } } internal string SerializationExceptionMessage { get { return serializationExceptionMessage; } } internal string DeserializationExceptionMessage { get { if (serializationExceptionMessage == null) { return null; } else { return SR.GetString(SR.ReadOnlyClassDeserialization, this.serializationExceptionMessage); } } } internal override bool IsISerializable { get { return isISerializable; } set { isISerializable = value; } } internal bool HasDataContract { get { return hasDataContract; } } internal bool HasExtensionData { get { return hasExtensionData; } } internal bool IsNonAttributedType { get { return isNonAttributedType; } } internal ConstructorInfo GetISerializableConstructor() { if (!IsISerializable) return null; ConstructorInfo ctor = UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, SerInfoCtorArgs, null); if (ctor == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(UnderlyingType)))); return ctor; } internal ConstructorInfo GetNonAttributedTypeConstructor() { if (!this.IsNonAttributedType) return null; Type type = UnderlyingType; if (type.IsValueType) return null; ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, Globals.EmptyTypeArray, null); if (ctor == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.NonAttributedSerializableTypesMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type)))); return ctor; } internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate { get { return xmlFormatWriterDelegate; } set { xmlFormatWriterDelegate = value; } } internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate { get { return xmlFormatReaderDelegate; } set { xmlFormatReaderDelegate = value; } } public XmlDictionaryString[] ChildElementNamespaces { get { return childElementNamespaces; } set { childElementNamespaces = value; } } static Type[] serInfoCtorArgs; static Type[] SerInfoCtorArgs { get { if (serInfoCtorArgs == null) serInfoCtorArgs = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; return serInfoCtorArgs; } } internal struct Member { internal Member(DataMember member, string ns, int baseTypeIndex) { this.member = member; this.ns = ns; this.baseTypeIndex = baseTypeIndex; } internal DataMember member; internal string ns; internal int baseTypeIndex; } internal class DataMemberConflictComparer : IComparer<Member> { public int Compare(Member x, Member y) { int nsCompare = String.CompareOrdinal(x.ns, y.ns); if (nsCompare != 0) return nsCompare; int nameCompare = String.CompareOrdinal(x.member.Name, y.member.Name); if (nameCompare != 0) return nameCompare; return x.baseTypeIndex - y.baseTypeIndex; } internal static DataMemberConflictComparer Singleton = new DataMemberConflictComparer(); } } [Fx.Tag.SecurityNote(Critical = "Sets critical properties on ClassDataContract .", Safe = "Called during schema import/code generation.")] [SecuritySafeCritical] internal override DataContract BindGenericParameters(DataContract[] paramContracts, Dictionary<DataContract, DataContract> boundContracts) { Type type = UnderlyingType; if (!type.IsGenericType || !type.ContainsGenericParameters) return this; lock (this) { DataContract boundContract; if (boundContracts.TryGetValue(this, out boundContract)) return boundContract; ClassDataContract boundClassContract = new ClassDataContract(); boundContracts.Add(this, boundClassContract); XmlQualifiedName stableName; object[] genericParams; if (type.IsGenericTypeDefinition) { stableName = this.StableName; genericParams = paramContracts; } else { //partial Generic: Construct stable name from its open generic type definition stableName = DataContract.GetStableName(type.GetGenericTypeDefinition()); Type[] paramTypes = type.GetGenericArguments(); genericParams = new object[paramTypes.Length]; for (int i = 0; i < paramTypes.Length; i++) { Type paramType = paramTypes[i]; if (paramType.IsGenericParameter) genericParams[i] = paramContracts[paramType.GenericParameterPosition]; else genericParams[i] = paramType; } } boundClassContract.StableName = CreateQualifiedName(DataContract.ExpandGenericParameters(XmlConvert.DecodeName(stableName.Name), new GenericNameProvider(DataContract.GetClrTypeFullName(this.UnderlyingType), genericParams)), stableName.Namespace); if (BaseContract != null) boundClassContract.BaseContract = (ClassDataContract)BaseContract.BindGenericParameters(paramContracts, boundContracts); boundClassContract.IsISerializable = this.IsISerializable; boundClassContract.IsValueType = this.IsValueType; boundClassContract.IsReference = this.IsReference; if (Members != null) { boundClassContract.Members = new List<DataMember>(Members.Count); foreach (DataMember member in Members) boundClassContract.Members.Add(member.BindGenericParameters(paramContracts, boundContracts)); } return boundClassContract; } } internal override bool Equals(object other, Dictionary<DataContractPairKey, object> checkedContracts) { if (IsEqualOrChecked(other, checkedContracts)) return true; if (base.Equals(other, checkedContracts)) { ClassDataContract dataContract = other as ClassDataContract; if (dataContract != null) { if (IsISerializable) { if (!dataContract.IsISerializable) return false; } else { if (dataContract.IsISerializable) return false; if (Members == null) { if (dataContract.Members != null) { // check that all the datamembers in dataContract.Members are optional if (!IsEveryDataMemberOptional(dataContract.Members)) return false; } } else if (dataContract.Members == null) { // check that all the datamembers in Members are optional if (!IsEveryDataMemberOptional(Members)) return false; } else { Dictionary<string, DataMember> membersDictionary = new Dictionary<string, DataMember>(Members.Count); List<DataMember> dataContractMembersList = new List<DataMember>(); for (int i = 0; i < Members.Count; i++) { membersDictionary.Add(Members[i].Name, Members[i]); } for (int i = 0; i < dataContract.Members.Count; i++) { // check that all datamembers common to both datacontracts match DataMember dataMember; if (membersDictionary.TryGetValue(dataContract.Members[i].Name, out dataMember)) { if (dataMember.Equals(dataContract.Members[i], checkedContracts)) { membersDictionary.Remove(dataMember.Name); } else { return false; } } // otherwise save the non-matching datamembers for later verification else { dataContractMembersList.Add(dataContract.Members[i]); } } // check that datamembers left over from either datacontract are optional if (!IsEveryDataMemberOptional(membersDictionary.Values)) return false; if (!IsEveryDataMemberOptional(dataContractMembersList)) return false; } } if (BaseContract == null) return (dataContract.BaseContract == null); else if (dataContract.BaseContract == null) return false; else return BaseContract.Equals(dataContract.BaseContract, checkedContracts); } } return false; } bool IsEveryDataMemberOptional(IEnumerable<DataMember> dataMembers) { foreach (DataMember dataMember in dataMembers) { if (dataMember.IsRequired) return false; } return true; } public override int GetHashCode() { return base.GetHashCode(); } internal class DataMemberComparer : IComparer<DataMember> { public int Compare(DataMember x, DataMember y) { int orderCompare = x.Order - y.Order; if (orderCompare != 0) return orderCompare; return String.CompareOrdinal(x.Name, y.Name); } internal static DataMemberComparer Singleton = new DataMemberComparer(); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System.IO; using System.Xml.Linq; using System.Collections; using System.Resources; using Microsoft.Cci; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace Microsoft.Build.Net.CoreRuntimeTask { public sealed class ResourceHandlingTask : Task { [Serializable()] public sealed class PortableLibraryResourceStateInfo { public DateTime PLibTimeUtc; public DateTime ResWTimeUtc; public string ResWPath; } [Serializable()] public sealed class ResourceHandlingState { [NonSerialized] private TaskLoggingHelper _logger; public Dictionary<string, PortableLibraryResourceStateInfo> PortableLibraryStatesLookup = new Dictionary<string, PortableLibraryResourceStateInfo>(); public void SetLogger(TaskLoggingHelper logger) { _logger = logger; } public bool IsUpToDate(string assemblyPath, out string reswFilePath) { reswFilePath = null; if (PortableLibraryStatesLookup == null) { PortableLibraryStatesLookup = new Dictionary<string, PortableLibraryResourceStateInfo>(); return false; } if (PortableLibraryStatesLookup.Count == 0) { return false; } try { if (assemblyPath == null || !File.Exists(assemblyPath)) { return false; } PortableLibraryResourceStateInfo info; if (!PortableLibraryStatesLookup.TryGetValue(assemblyPath, out info)) { return false; } FileInfo fiPlib = new FileInfo(assemblyPath); if (!fiPlib.LastWriteTimeUtc.Equals(info.PLibTimeUtc)) { _logger.LogMessage(MessageImportance.Low, Resources.Message_CachedReswNotUpToDateAssemblyNewer, assemblyPath); return false; } if (info.ResWPath == null || !File.Exists(info.ResWPath)) { _logger.LogMessage(MessageImportance.Low, Resources.Message_CachedReswNotExists, assemblyPath, info.ResWPath); return false; } FileInfo fiResW = new FileInfo(info.ResWPath); if (!fiResW.LastWriteTimeUtc.Equals(info.ResWTimeUtc)) { _logger.LogMessage(MessageImportance.Low, Resources.Message_CachedReswNotUpToDate, info.ResWPath); return false; } _logger.LogMessage(MessageImportance.Low, Resources.Message_UsingCachedResw, info.ResWPath, assemblyPath); reswFilePath = info.ResWPath; return true; } catch (Exception e) { _logger.LogMessage(MessageImportance.Low, Resources.Error_UnspecifiedCheckUpToDate, assemblyPath, e.Message); return false; } } public void Save(string assemblyPath, string reswPath, DateTime plibTimeUtc, DateTime reswTimeUtc) { try { PortableLibraryStatesLookup[assemblyPath] = new PortableLibraryResourceStateInfo() { PLibTimeUtc = plibTimeUtc, ResWTimeUtc = reswTimeUtc, ResWPath = reswPath}; } catch (Exception e) { _logger.LogMessage(MessageImportance.Low, Resources.Error_UnspecifiedSaveState, assemblyPath, e.Message); } } } [Required] public ITaskItem[] AssemblyList { get; set; } [Required] public string OutResWPath { get; set; } [Required] public string StateFile { get; set; } public bool SkipFrameworkResources { get; set; } [Output] public ITaskItem[] ReswFileList { get; set; } [Output] public ITaskItem[] UnprocessedAssemblyList { get; set; } private MetadataReaderHost _host; private ResourceHandlingState _state = null; public override bool Execute() { ReswFileList = null; UnprocessedAssemblyList = null; List<ITaskItem> unprocessedAssemblyList = new List<ITaskItem>(); List<ITaskItem> reswList = new List<ITaskItem>(); _state = ReadStateFile(StateFile); if (_state == null) { _state = new ResourceHandlingState(); } _state.SetLogger(Log); using (_host = new PeReader.DefaultHost()) { try { ITaskItem firstNonFrameworkAssembly = null; foreach (ITaskItem assemblyFilePath in AssemblyList) { string reswPath = null; bool containsResources = false; if (!_state.IsUpToDate(assemblyFilePath.ItemSpec, out reswPath) || !IsAtOutputFolder(reswPath) ) { reswPath = ExtractFrameworkAssemblyResW(assemblyFilePath.ItemSpec, out containsResources); if (reswPath != null) { FileInfo fiAssembly = new FileInfo(assemblyFilePath.ItemSpec); FileInfo fiResW = new FileInfo(reswPath); _state.Save(assemblyFilePath.ItemSpec, reswPath, fiAssembly.LastWriteTimeUtc, fiResW.LastWriteTimeUtc); } } if (reswPath == null) { if (containsResources) unprocessedAssemblyList.Add(assemblyFilePath); if (unprocessedAssemblyList.Count == 0) firstNonFrameworkAssembly = assemblyFilePath; } else { TaskItem newTaskItem = new TaskItem(reswPath); newTaskItem.SetMetadata("NeutralResourceLanguage","en-US"); newTaskItem.SetMetadata("ResourceIndexName",Path.GetFileNameWithoutExtension(reswPath)); reswList.Add(newTaskItem); } } UnprocessedAssemblyList = unprocessedAssemblyList.ToArray(); if (!SkipFrameworkResources) { ReswFileList = reswList.ToArray(); } // we make sure unprocessedAssemblyList has at least one item if ReswFileList is empty to avoid having _GeneratePrisForPortableLibraries // repopulate the assembly list and reprocess them if ((ReswFileList == null || ReswFileList.Length == 0) && UnprocessedAssemblyList.Length == 0 && firstNonFrameworkAssembly != null) { UnprocessedAssemblyList = new ITaskItem[1] { firstNonFrameworkAssembly }; } WriteStateFile(StateFile, _state); } catch (Exception e) { Log.LogError(Resources.Error_ResourceExtractionFailed, e.Message); return false; } } return true; } private ResourceHandlingState ReadStateFile(string stateFile) { try { if (!String.IsNullOrEmpty(stateFile) && File.Exists(stateFile)) { using (FileStream fs = new FileStream(stateFile, FileMode.Open)) { BinaryFormatter formatter = new BinaryFormatter(); object deserializedObject = formatter.Deserialize(fs); ResourceHandlingState state = deserializedObject as ResourceHandlingState; if (state == null && deserializedObject != null) { Log.LogMessage(MessageImportance.Normal, Resources.Message_UnspecifiedStateFileCorrupted, stateFile); } return state; } } else return null; } catch (Exception e) { Log.LogMessage(MessageImportance.Low, Resources.Message_UnspecifiedReadStateFile, e.Message); return null; } } private bool IsAtOutputFolder(string path) { try { return (Path.GetDirectoryName(path).Equals(OutResWPath.TrimEnd(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}), StringComparison.OrdinalIgnoreCase)); } catch { return false; } } private void WriteStateFile(string stateFile, ResourceHandlingState state) { try { if (stateFile != null && stateFile.Length > 0 ) { using (FileStream fs = new FileStream(stateFile, FileMode.Create)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, state); } } } catch (Exception e) { Log.LogMessage(MessageImportance.Low, Resources.Message_UnspecifiedSaveStateFile, e.Message); } } private string ExtractFrameworkAssemblyResW(string assemblyFilePath, out bool containsResources) { string assemblyName; using (Stream stream = ExtractFromAssembly(assemblyFilePath, out assemblyName, out containsResources)) { if (stream == null) return null; string reswFilePath = OutResWPath + Path.AltDirectorySeparatorChar + "FxResources." + assemblyName + ".SR.resw"; WriteResW(stream, reswFilePath); return reswFilePath; } } private void WriteResW(Stream stream, string reswFilePath) { using (ResourceReader rr = new ResourceReader(stream)) { using (ResXResourceWriter rw = new ResXResourceWriter(reswFilePath)) { foreach (DictionaryEntry dict in rr) { rw.AddResource((string)dict.Key, (string)dict.Value); } } } } private Stream ExtractFromAssembly(string assemblyFilePath, out string assemblyName, out bool containsResources) { assemblyName = null; containsResources = true; IAssembly assembly = _host.LoadUnitFrom(assemblyFilePath) as IAssembly; if (assembly == null || assembly == Dummy.Assembly) { containsResources = false; return null; } if (assembly.Resources == null) { containsResources = false; return null; } assemblyName = assembly.Name.Value; string resourcesName = "FxResources." + assemblyName + ".SR.resources"; int resourceCount = 0; foreach (IResourceReference resourceReference in assembly.Resources) { resourceCount++; if (!resourceReference.Resource.IsInExternalFile && resourceReference.Name.Value.Equals(resourcesName, StringComparison.OrdinalIgnoreCase)) { const int BUFFERSIZE = 4096; byte[] buffer = new byte[BUFFERSIZE]; int index = 0; MemoryStream ms = new MemoryStream(BUFFERSIZE); foreach (byte b in resourceReference.Resource.Data) { if (index == BUFFERSIZE) { ms.Write(buffer, 0, BUFFERSIZE); index = 0; } buffer[index++] = b; } ms.Write(buffer, 0, index); ms.Seek(0, SeekOrigin.Begin); return ms; } } if (resourceCount == 0) // no resources { containsResources = false; } return null; } } }
// The MIT License (MIT) // Copyright 2015 Siney/Pangweiwei siney@yeah.net // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace SLua { using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System; using System.Reflection; using UnityEditor; using LuaInterface; using System.Text; using System.Text.RegularExpressions; public class ConnectDebugger : EditorWindow { string addr = "localhost:10240"; static ConnectDebugger wnd; [MenuItem("SLua/Console")] static void Init() { if (wnd == null) wnd = (ConnectDebugger)EditorWindow.GetWindow(typeof(ConnectDebugger), true, "Connect debugger"); wnd.position = new Rect(Screen.width / 2, Screen.height / 2, 500, 50); wnd.Show(); } void OnGUI() { addr = EditorGUILayout.TextField("Debugger IP:", addr); if (GUILayout.Button("Connect", GUILayout.ExpandHeight(true))) { try { string ip = "localhost"; int port = 10240; string[] comp = addr.Split(':'); ip = comp[0]; if (comp.Length > 0) port = Convert.ToInt32(comp[1]); #if UNITY_EDITOR_WIN System.Diagnostics.Process.Start("debugger\\win\\ldb.exe", string.Format("-host {0} -port {1}", ip, port)); #else System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo(); proc.FileName = "ldb"; proc.WorkingDirectory = "debugger/mac"; // I don't know why can't start process with arguments on MacOSX // I just keep arguments empty???? proc.Arguments = "";//string.Format("-host {0} -port {1}", ip, port); proc.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal; proc.CreateNoWindow = true; System.Diagnostics.Process.Start(proc); #endif } catch (Exception e) { Debug.LogError(e); } } } } public class LuaCodeGen : MonoBehaviour { public const string Path = "Assets/Slua/LuaObject/"; public delegate void ExportGenericDelegate(Type t, string ns); static bool autoRefresh = true; static bool IsCompiling { get { if (EditorApplication.isCompiling) { Debug.Log("Unity Editor is compiling, please wait."); } return EditorApplication.isCompiling; } } [InitializeOnLoad] public class Startup { static Startup() { bool ok = System.IO.Directory.Exists(Path); if (!ok && EditorUtility.DisplayDialog("Slua", "Not found lua interface for Unity, generate it now?", "Generate", "No")) { GenerateAll(); } } } [MenuItem("SLua/All/Make")] static public void GenerateAll() { autoRefresh = false; Generate(); GenerateUI(); Custom(); Generate3rdDll(); autoRefresh = true; AssetDatabase.Refresh(); } [MenuItem("SLua/Unity/Make UnityEngine")] static public void Generate() { if (IsCompiling) { return; } Assembly assembly = Assembly.Load("UnityEngine"); Type[] types = assembly.GetExportedTypes(); List<string> uselist; List<string> noUseList; CustomExport.OnGetNoUseList(out noUseList); CustomExport.OnGetUseList(out uselist); List<Type> exports = new List<Type>(); string path = Path + "Unity/"; foreach (Type t in types) { if (filterType(t, noUseList, uselist) && Generate(t, path)) exports.Add(t); } GenerateBind(exports, "BindUnity", 0, path); if(autoRefresh) AssetDatabase.Refresh(); Debug.Log("Generate engine interface finished"); } static bool filterType(Type t, List<string> noUseList, List<string> uselist) { // check type in uselist string fullName = t.FullName; if (uselist != null && uselist.Count > 0) { return uselist.Contains(fullName); } else { // check type not in nouselist foreach (string str in noUseList) { if (fullName.Contains(str)) { return false; } } return true; } } [MenuItem("SLua/Unity/Make UI (for Unity4.6+)")] static public void GenerateUI() { if (IsCompiling) { return; } List<string> uselist; List<string> noUseList; CustomExport.OnGetNoUseList(out noUseList); CustomExport.OnGetUseList(out uselist); Assembly assembly = Assembly.Load("UnityEngine.UI"); Type[] types = assembly.GetExportedTypes(); List<Type> exports = new List<Type>(); string path = Path + "Unity/"; foreach (Type t in types) { if (filterType(t,noUseList,uselist) && Generate(t,path)) { exports.Add(t); } } GenerateBind(exports, "BindUnityUI", 1, path); if(autoRefresh) AssetDatabase.Refresh(); Debug.Log("Generate UI interface finished"); } [MenuItem("SLua/Unity/Clear Uinty UI")] static public void ClearUnity() { clear(new string[] { Path + "Unity" }); Debug.Log("Clear Unity & UI complete."); } [MenuItem("SLua/Custom/Make")] static public void Custom() { if (IsCompiling) { return; } List<Type> exports = new List<Type>(); string path = Path + "Custom/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } ExportGenericDelegate fun = (Type t, string ns) => { if (Generate(t, ns, path)) exports.Add(t); }; HashSet<string> namespaces = CustomExport.OnAddCustomNamespace(); Assembly assembly; Type[] types; try { // export plugin-dll assembly = Assembly.Load("Assembly-CSharp-firstpass"); types = assembly.GetExportedTypes(); foreach (Type t in types) { if (t.GetCustomAttributes(typeof(CustomLuaClassAttribute), false).Length > 0 || namespaces.Contains(t.Namespace)) { fun(t, null); } } } catch(Exception){} // export self-dll assembly = Assembly.Load("Assembly-CSharp"); types = assembly.GetExportedTypes(); foreach (Type t in types) { if (t.GetCustomAttributes(typeof(CustomLuaClassAttribute), false).Length > 0 || namespaces.Contains(t.Namespace)) { fun(t, null); } } CustomExport.OnAddCustomClass(fun); GenerateBind(exports, "BindCustom", 3, path); if(autoRefresh) AssetDatabase.Refresh(); Debug.Log("Generate custom interface finished"); } [MenuItem("SLua/3rdDll/Make")] static public void Generate3rdDll() { if (IsCompiling) { return; } List<Type> cust = new List<Type>(); List<string> assemblyList = new List<string>(); CustomExport.OnAddCustomAssembly(ref assemblyList); foreach (string assemblyItem in assemblyList) { Assembly assembly = Assembly.Load(assemblyItem); Type[] types = assembly.GetExportedTypes(); foreach (Type t in types) { cust.Add(t); } } if (cust.Count > 0) { List<Type> exports = new List<Type>(); string path = Path + "Dll/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } foreach (Type t in cust) { if (Generate(t,path)) exports.Add(t); } GenerateBind(exports, "BindDll", 2, path); if(autoRefresh) AssetDatabase.Refresh(); Debug.Log("Generate 3rdDll interface finished"); } } [MenuItem("SLua/3rdDll/Clear")] static public void Clear3rdDll() { clear(new string[] { Path + "Dll" }); Debug.Log("Clear AssemblyDll complete."); } [MenuItem("SLua/Custom/Clear")] static public void ClearCustom() { clear(new string[] { Path + "Custom" }); Debug.Log("Clear custom complete."); } [MenuItem("SLua/All/Clear")] static public void ClearALL() { clear(new string[] { Path.Substring(0, Path.Length - 1) }); Debug.Log("Clear all complete."); } static void clear(string[] paths) { try { foreach (string path in paths) { System.IO.Directory.Delete(path, true); } } catch { } AssetDatabase.Refresh(); } static bool Generate(Type t, string path) { return Generate(t, null, path); } static bool Generate(Type t, string ns, string path) { if (t.IsInterface) return false; CodeGenerator cg = new CodeGenerator(); cg.givenNamespace = ns; cg.path = path; return cg.Generate(t); } static void GenerateBind(List<Type> list, string name, int order,string path) { CodeGenerator cg = new CodeGenerator(); cg.path = path; cg.GenerateBind(list, name, order); } } class CodeGenerator { static List<string> memberFilter = new List<string> { "AnimationClip.averageDuration", "AnimationClip.averageAngularSpeed", "AnimationClip.averageSpeed", "AnimationClip.apparentSpeed", "AnimationClip.isLooping", "AnimationClip.isAnimatorMotion", "AnimationClip.isHumanMotion", "AnimatorOverrideController.PerformOverrideClipListCleanup", "Caching.SetNoBackupFlag", "Caching.ResetNoBackupFlag", "Light.areaSize", "Security.GetChainOfTrustValue", "Texture2D.alphaIsTransparency", "WWW.movie", "WebCamTexture.MarkNonReadable", "WebCamTexture.isReadable", // i don't why below 2 functions missed in iOS platform "Graphic.OnRebuildRequested", "Text.OnRebuildRequested", // il2cpp not exixts "Application.ExternalEval", "GameObject.networkView", "Component.networkView", // unity5 "AnimatorControllerParameter.name", "Input.IsJoystickPreconfigured", "Resources.LoadAssetAtPath", #if UNITY_4_6 "Motion.ValidateIfRetargetable", "Motion.averageDuration", "Motion.averageAngularSpeed", "Motion.averageSpeed", "Motion.apparentSpeed", "Motion.isLooping", "Motion.isAnimatorMotion", "Motion.isHumanMotion", #endif }; HashSet<string> funcname = new HashSet<string>(); Dictionary<string, bool> directfunc = new Dictionary<string, bool>(); public string givenNamespace; public string path; class PropPair { public string get = "null"; public string set = "null"; public bool isInstance = true; } Dictionary<string, PropPair> propname = new Dictionary<string, PropPair>(); int indent = 0; public void GenerateBind(List<Type> list, string name, int order) { HashSet<Type> exported = new HashSet<Type>(); string f = path + name + ".cs"; StreamWriter file = new StreamWriter(f, false, Encoding.UTF8); Write(file, "using System;"); Write(file, "using System.Collections.Generic;"); Write(file, "namespace SLua {"); Write(file, "[LuaBinder({0})]", order); Write(file, "public class {0} {{", name); Write(file, "public static Action<IntPtr>[] GetBindList() {"); Write(file, "Action<IntPtr>[] list= {"); foreach (Type t in list) { WriteBindType(file, t, list, exported); } Write(file, "};"); Write(file, "return list;"); Write(file, "}"); Write(file, "}"); Write(file, "}"); file.Close(); } void WriteBindType(StreamWriter file, Type t, List<Type> exported, HashSet<Type> binded) { if (t == null || binded.Contains(t) || !exported.Contains(t)) return; WriteBindType(file, t.BaseType, exported, binded); Write(file, "{0}.reg,", ExportName(t), binded); binded.Add(t); } public bool Generate(Type t) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (!t.IsGenericTypeDefinition && (!IsObsolete(t) && t != typeof(YieldInstruction) && t != typeof(Coroutine)) || (t.BaseType != null && t.BaseType == typeof(System.MulticastDelegate))) { if (t.IsEnum) { StreamWriter file = Begin(t); WriteHead(t, file); RegEnumFunction(t, file); End(file); } else if (t.BaseType == typeof(System.MulticastDelegate)) { string f; if (t.IsGenericType) { if (t.ContainsGenericParameters) return false; f = path + string.Format("Lua{0}_{1}.cs", _Name(GenericBaseName(t)), _Name(GenericName(t))); } else { f = path + "LuaDelegate_" + _Name(t.FullName) + ".cs"; } StreamWriter file = new StreamWriter(f, false, Encoding.UTF8); WriteDelegate(t, file); file.Close(); return false; } else { funcname.Clear(); propname.Clear(); directfunc.Clear(); StreamWriter file = Begin(t); WriteHead(t, file); WriteConstructor(t, file); WriteFunction(t, file); WriteFunction(t, file, true); WriteField(t, file); RegFunction(t, file); End(file); if (t.BaseType != null && t.BaseType.Name == "UnityEvent`1") { string f = path + "LuaUnityEvent_" + _Name(GenericName(t.BaseType)) + ".cs"; file = new StreamWriter(f, false, Encoding.UTF8); WriteEvent(t, file); file.Close(); } } return true; } return false; } void WriteDelegate(Type t, StreamWriter file) { string temp = @" using System; using System.Collections.Generic; using LuaInterface; using UnityEngine; namespace SLua { public partial class LuaDelegation : LuaObject { static internal int checkDelegate(IntPtr l,int p,out $FN ua) { int op = extractFunction(l,p); if(LuaDLL.lua_isnil(l,p)) { ua=null; return op; } else if (LuaDLL.lua_isuserdata(l, p)==1) { ua = ($FN)checkObj(l, p); return op; } LuaDelegate ld; checkType(l, -1, out ld); if(ld.d!=null) { ua = ($FN)ld.d; return op; } LuaDLL.lua_pop(l,1); l = LuaState.get(l).L; ua = ($ARGS) => { int error = pushTry(l); "; temp = temp.Replace("$TN", t.Name); temp = temp.Replace("$FN", SimpleType(t)); MethodInfo mi = t.GetMethod("Invoke"); List<int> outindex = new List<int>(); List<int> refindex = new List<int>(); temp = temp.Replace("$ARGS", ArgsList(mi, ref outindex, ref refindex)); Write(file, temp); this.indent = 4; for (int n = 0; n < mi.GetParameters().Length; n++) { if (!outindex.Contains(n)) Write(file, "pushValue(l,a{0});", n + 1); } Write(file, "ld.pcall({0}, error);", mi.GetParameters().Length - outindex.Count); int offset = 0; if (mi.ReturnType != typeof(void)) { offset = 1; WriteValueCheck(file, mi.ReturnType, offset, "ret", "error+"); } foreach (int i in outindex) { string a = string.Format("a{0}", i + 1); WriteCheckType(file, mi.GetParameters()[i].ParameterType, i + offset, a, "error+"); } foreach (int i in refindex) { string a = string.Format("a{0}", i + 1); WriteCheckType(file, mi.GetParameters()[i].ParameterType, i + offset, a, "error+"); } Write(file, "LuaDLL.lua_settop(l, error-1);"); if (mi.ReturnType != typeof(void)) Write(file, "return ret;"); Write(file, "};"); Write(file, "ld.d=ua;"); Write(file, "return op;"); Write(file, "}"); Write(file, "}"); Write(file, "}"); } string ArgsList(MethodInfo m, ref List<int> outindex, ref List<int> refindex) { string str = ""; ParameterInfo[] pars = m.GetParameters(); for (int n = 0; n < pars.Length; n++) { string t = SimpleType(pars[n].ParameterType); ParameterInfo p = pars[n]; if (p.ParameterType.IsByRef && p.IsOut) { str += string.Format("out {0} a{1}", t, n + 1); outindex.Add(n); } else if (p.ParameterType.IsByRef) { str += string.Format("ref {0} a{1}", t, n + 1); refindex.Add(n); } else str += string.Format("{0} a{1}", t, n + 1); if (n < pars.Length - 1) str += ","; } return str; } void tryMake(Type t) { if (t.BaseType == typeof(System.MulticastDelegate)) { CodeGenerator cg = new CodeGenerator(); cg.path = this.path; cg.Generate(t); } } void WriteEvent(Type t, StreamWriter file) { string temp = @" using System; using System.Collections.Generic; using LuaInterface; using UnityEngine; using UnityEngine.EventSystems; namespace SLua { public class LuaUnityEvent_$CLS : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int AddListener(IntPtr l) { try { UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l); UnityEngine.Events.UnityAction<$GN> a1; checkType(l, 2, out a1); self.AddListener(a1); pushValue(l,true); return 1; } catch (Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int RemoveListener(IntPtr l) { try { UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l); UnityEngine.Events.UnityAction<$GN> a1; checkType(l, 2, out a1); self.RemoveListener(a1); pushValue(l,true); return 1; } catch (Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Invoke(IntPtr l) { try { UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l); $GN o; checkType(l,2,out o); self.Invoke(o); pushValue(l,true); return 1; } catch (Exception e) { return error(l,e); } } static public void reg(IntPtr l) { getTypeTable(l, typeof(LuaUnityEvent_$CLS).FullName); addMember(l, AddListener); addMember(l, RemoveListener); addMember(l, Invoke); createTypeMetatable(l, null, typeof(LuaUnityEvent_$CLS), typeof(UnityEngine.Events.UnityEventBase)); } static bool checkType(IntPtr l,int p,out UnityEngine.Events.UnityAction<$GN> ua) { LuaDLL.luaL_checktype(l, p, LuaTypes.LUA_TFUNCTION); LuaDelegate ld; checkType(l, p, out ld); if (ld.d != null) { ua = (UnityEngine.Events.UnityAction<$GN>)ld.d; return true; } l = LuaState.get(l).L; ua = ($GN v) => { int error = pushTry(l); pushValue(l, v); ld.pcall(1, error); LuaDLL.lua_settop(l,error - 1); }; ld.d = ua; return true; } } }"; temp = temp.Replace("$CLS", _Name(GenericName(t.BaseType))); temp = temp.Replace("$FNAME", FullName(t)); temp = temp.Replace("$GN", GenericName(t.BaseType)); Write(file, temp); } void RegEnumFunction(Type t, StreamWriter file) { // Write export function Write(file, "static public void reg(IntPtr l) {"); Write(file, "getEnumTable(l,\"{0}\");", string.IsNullOrEmpty(givenNamespace) ? FullName(t) : givenNamespace); foreach (object value in Enum.GetValues (t)) { Write(file, "addMember(l,{0},\"{1}\");", (int)value, value.ToString()); } Write(file, "LuaDLL.lua_pop(l, 1);"); Write(file, "}"); } StreamWriter Begin(Type t) { string clsname = ExportName(t); string f = path + clsname + ".cs"; StreamWriter file = new StreamWriter(f, false, Encoding.UTF8); return file; } private void End(StreamWriter file) { Write(file, "}"); file.Flush(); file.Close(); } private void WriteHead(Type t, StreamWriter file) { Write(file, "using UnityEngine;"); Write(file, "using System;"); Write(file, "using LuaInterface;"); Write(file, "using SLua;"); Write(file, "using System.Collections.Generic;"); Write(file, "public class {0} : LuaObject {{", ExportName(t)); } private void WriteFunction(Type t, StreamWriter file, bool writeStatic = false) { BindingFlags bf = BindingFlags.Public | BindingFlags.DeclaredOnly; if (writeStatic) bf |= BindingFlags.Static; else bf |= BindingFlags.Instance; MethodInfo[] members = t.GetMethods(bf); foreach (MethodInfo mi in members) { bool instanceFunc; if (writeStatic && isPInvoke(mi, out instanceFunc)) { directfunc.Add(t.FullName + "." + mi.Name, instanceFunc); continue; } string fn = writeStatic ? staticName(mi.Name) : mi.Name; if (mi.MemberType == MemberTypes.Method && !IsObsolete(mi) && !DontExport(mi) && !funcname.Contains(fn) && isUsefullMethod(mi) && !MemberInFilter(t, mi)) { WriteFunctionDec(file, fn); WriteFunctionImpl(file, mi, t, bf); funcname.Add(fn); } } } bool isPInvoke(MethodInfo mi, out bool instanceFunc) { object[] attrs = mi.GetCustomAttributes(typeof(MonoPInvokeCallbackAttribute), false); if (attrs.Length > 0) { instanceFunc = mi.GetCustomAttributes(typeof(StaticExportAttribute), false).Length == 0; return true; } instanceFunc = true; return false; } string staticName(string name) { if (name.StartsWith("op_")) return name; return name + "_s"; } bool MemberInFilter(Type t, MemberInfo mi) { return memberFilter.Contains(t.Name + "." + mi.Name); } bool IsObsolete(MemberInfo t) { return t.GetCustomAttributes(typeof(ObsoleteAttribute), false).Length > 0; } void RegFunction(Type t, StreamWriter file) { // Write export function Write(file, "static public void reg(IntPtr l) {"); if (t.BaseType != null && t.BaseType.Name.Contains("UnityEvent`")) { Write(file, "LuaUnityEvent_{1}.reg(l);", FullName(t), _Name((GenericName(t.BaseType)))); } Write(file, "getTypeTable(l,\"{0}\");", string.IsNullOrEmpty(givenNamespace) ? FullName(t) : givenNamespace); foreach (string f in funcname) { Write(file, "addMember(l,{0});", f); } foreach (string f in directfunc.Keys) { bool instance = directfunc[f]; Write(file, "addMember(l,{0},{1});", f, instance ? "true" : "false"); } foreach (string f in propname.Keys) { PropPair pp = propname[f]; Write(file, "addMember(l,\"{0}\",{1},{2},{3});", f, pp.get, pp.set, pp.isInstance ? "true" : "false"); } if (t.BaseType != null && !CutBase(t.BaseType)) { if (t.BaseType.Name.Contains("UnityEvent`1")) Write(file, "createTypeMetatable(l,{2}, typeof({0}),typeof(LuaUnityEvent_{1}));", TypeDecl(t), _Name(GenericName(t.BaseType)), constructorOrNot(t)); else Write(file, "createTypeMetatable(l,{2}, typeof({0}),typeof({1}));", TypeDecl(t), TypeDecl(t.BaseType), constructorOrNot(t)); } else Write(file, "createTypeMetatable(l,{1}, typeof({0}));", TypeDecl(t), constructorOrNot(t)); Write(file, "}"); } string constructorOrNot(Type t) { ConstructorInfo[] cons = GetValidConstructor(t); if (cons.Length > 0 || t.IsValueType) return "constructor"; return "null"; } bool CutBase(Type t) { if (t.FullName.StartsWith("System.Object")) return true; return false; } void WriteSet(StreamWriter file, Type t, string cls, string fn, bool isstatic = false) { if (t.BaseType == typeof(MulticastDelegate)) { if (isstatic) { Write(file, "if(op==0) {0}.{1}=v;", cls, fn); Write(file, "else if(op==1) {0}.{1}+=v;", cls, fn); Write(file, "else if(op==2) {0}.{1}-=v;", cls, fn); } else { Write(file, "if(op==0) self.{0}=v;", fn); Write(file, "else if(op==1) self.{0}+=v;", fn); Write(file, "else if(op==2) self.{0}-=v;", fn); } } else { if (isstatic) { Write(file, "{0}.{1}=v;", cls, fn); } else { Write(file, "self.{0}=v;", fn); } } } readonly static string[] keywords = { "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while" }; static string NormalName(string name) { if (Array.BinarySearch<string>(keywords, name) >= 0) { return "@" + name; } return name; } private void WriteField(Type t, StreamWriter file) { // Write field set/get FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (FieldInfo fi in fields) { if (DontExport(fi) || IsObsolete(fi)) continue; PropPair pp = new PropPair(); pp.isInstance = !fi.IsStatic; if (fi.FieldType.BaseType != typeof(MulticastDelegate)) { WriteFunctionAttr(file); Write(file, "static public int get_{0}(IntPtr l) {{", fi.Name); WriteTry(file); if (fi.IsStatic) { WriteOk(file); WritePushValue(fi.FieldType, file, string.Format("{0}.{1}", TypeDecl(t), NormalName(fi.Name))); } else { WriteCheckSelf(file, t); WriteOk(file); WritePushValue(fi.FieldType, file, string.Format("self.{0}", NormalName(fi.Name))); } Write(file, "return 2;"); WriteCatchExecption(file); Write(file, "}"); pp.get = "get_" + fi.Name; } if (!fi.IsLiteral && !fi.IsInitOnly) { WriteFunctionAttr(file); Write(file, "static public int set_{0}(IntPtr l) {{", fi.Name); WriteTry(file); if (fi.IsStatic) { Write(file, "{0} v;", TypeDecl(fi.FieldType)); WriteCheckType(file, fi.FieldType, 2); WriteSet(file, fi.FieldType, TypeDecl(t), NormalName(fi.Name), true); } else { WriteCheckSelf(file, t); Write(file, "{0} v;", TypeDecl(fi.FieldType)); WriteCheckType(file, fi.FieldType, 2); WriteSet(file, fi.FieldType, t.FullName, NormalName(fi.Name)); } if (t.IsValueType && !fi.IsStatic) Write(file, "setBack(l,self);"); WriteOk(file); Write(file, "return 1;"); WriteCatchExecption(file); Write(file, "}"); pp.set = "set_" + fi.Name; } propname.Add(fi.Name, pp); tryMake(fi.FieldType); } //for this[] List<PropertyInfo> getter = new List<PropertyInfo>(); List<PropertyInfo> setter = new List<PropertyInfo>(); // Write property set/get PropertyInfo[] props = t.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (PropertyInfo fi in props) { //if (fi.Name == "Item" || IsObsolete(fi) || MemberInFilter(t,fi) || DontExport(fi)) if (IsObsolete(fi) || MemberInFilter(t, fi) || DontExport(fi)) continue; if (fi.Name == "Item" || (t.Name == "String" && fi.Name == "Chars")) // for string[] { //for this[] if (!fi.GetGetMethod().IsStatic && fi.GetIndexParameters().Length == 1) { if (fi.CanRead && !IsNotSupport(fi.PropertyType)) getter.Add(fi); if (fi.CanWrite && fi.GetSetMethod() != null) setter.Add(fi); } continue; } PropPair pp = new PropPair(); bool isInstance = true; if (fi.CanRead && fi.GetGetMethod() != null) { if (!IsNotSupport(fi.PropertyType)) { WriteFunctionAttr(file); Write(file, "static public int get_{0}(IntPtr l) {{", fi.Name); WriteTry(file); if (fi.GetGetMethod().IsStatic) { isInstance = false; WriteOk(file); WritePushValue(fi.PropertyType, file, string.Format("{0}.{1}", TypeDecl(t), NormalName(fi.Name))); } else { WriteCheckSelf(file, t); WriteOk(file); WritePushValue(fi.PropertyType, file, string.Format("self.{0}", NormalName(fi.Name))); } Write(file, "return 2;"); WriteCatchExecption(file); Write(file, "}"); pp.get = "get_" + fi.Name; } } if (fi.CanWrite && fi.GetSetMethod() != null) { WriteFunctionAttr(file); Write(file, "static public int set_{0}(IntPtr l) {{", fi.Name); WriteTry(file); if (fi.GetSetMethod().IsStatic) { WriteValueCheck(file, fi.PropertyType, 2); WriteSet(file, fi.PropertyType, TypeDecl(t), NormalName(fi.Name), true); isInstance = false; } else { WriteCheckSelf(file, t); WriteValueCheck(file, fi.PropertyType, 2); WriteSet(file, fi.PropertyType, TypeDecl(t), NormalName(fi.Name)); } if (t.IsValueType) Write(file, "setBack(l,self);"); WriteOk(file); Write(file, "return 1;"); WriteCatchExecption(file); Write(file, "}"); pp.set = "set_" + fi.Name; } pp.isInstance = isInstance; propname.Add(fi.Name, pp); tryMake(fi.PropertyType); } //for this[] WriteItemFunc(t, file, getter, setter); } void WriteItemFunc(Type t, StreamWriter file, List<PropertyInfo> getter, List<PropertyInfo> setter) { //Write property this[] set/get if (getter.Count > 0) { //get bool first_get = true; WriteFunctionAttr(file); Write(file, "static public int getItem(IntPtr l) {"); WriteTry(file); WriteCheckSelf(file, t); if (getter.Count == 1) { PropertyInfo _get = getter[0]; ParameterInfo[] infos = _get.GetIndexParameters(); WriteValueCheck(file, infos[0].ParameterType, 2, "v"); Write(file, "var ret = self[v];"); WriteOk(file); WritePushValue(_get.PropertyType, file, "ret"); Write(file, "return 2;"); } else { Write(file, "LuaTypes t = LuaDLL.lua_type(l, 2);"); for (int i = 0; i < getter.Count; i++) { PropertyInfo fii = getter[i]; ParameterInfo[] infos = fii.GetIndexParameters(); Write(file, "{0}(matchType(l,2,t,typeof({1}))){{", first_get ? "if" : "else if", infos[0].ParameterType); WriteValueCheck(file, infos[0].ParameterType, 2, "v"); Write(file, "var ret = self[v];"); WriteOk(file); WritePushValue(fii.PropertyType, file, "ret"); Write(file, "return 2;"); Write(file, "}"); first_get = false; } WriteError(file, "No matched override function to call"); } WriteCatchExecption(file); Write(file, "}"); funcname.Add("getItem"); } if (setter.Count > 0) { bool first_set = true; WriteFunctionAttr(file); Write(file, "static public int setItem(IntPtr l) {"); WriteTry(file); WriteCheckSelf(file, t); if (setter.Count == 1) { PropertyInfo _set = setter[0]; ParameterInfo[] infos = _set.GetIndexParameters(); WriteValueCheck(file, infos[0].ParameterType, 2); WriteValueCheck(file, _set.PropertyType, 3, "c"); Write(file, "self[v]=c;"); WriteOk(file); } else { Write(file, "LuaTypes t = LuaDLL.lua_type(l, 2);"); for (int i = 0; i < setter.Count; i++) { PropertyInfo fii = setter[i]; if (t.BaseType != typeof(MulticastDelegate)) { ParameterInfo[] infos = fii.GetIndexParameters(); Write(file, "{0}(matchType(l,2,t,typeof({1}))){{", first_set ? "if" : "else if", infos[0].ParameterType); WriteValueCheck(file, infos[0].ParameterType, 2, "v"); WriteValueCheck(file, fii.PropertyType, 3, "c"); Write(file, "self[v]=c;"); WriteOk(file); Write(file, "return 1;"); Write(file, "}"); first_set = false; } if (t.IsValueType) Write(file, "setBack(l,self);"); } Write(file, "LuaDLL.lua_pushstring(l,\"No matched override function to call\");"); } Write(file, "return 1;"); WriteCatchExecption(file); Write(file, "}"); funcname.Add("setItem"); } } void WriteTry(StreamWriter file) { Write(file, "try {"); } void WriteCatchExecption(StreamWriter file) { Write(file, "}"); Write(file, "catch(Exception e) {"); Write(file, "return error(l,e);"); Write(file, "}"); } void WriteCheckType(StreamWriter file, Type t, int n, string v = "v", string nprefix = "") { if (t.IsEnum) Write(file, "checkEnum(l,{2}{0},out {1});", n, v, nprefix); else if (t.BaseType == typeof(System.MulticastDelegate)) Write(file, "int op=LuaDelegation.checkDelegate(l,{2}{0},out {1});", n, v, nprefix); else if (IsValueType(t)) Write(file, "checkValueType(l,{2}{0},out {1});", n, v, nprefix); else Write(file, "checkType(l,{2}{0},out {1});", n, v, nprefix); } void WriteValueCheck(StreamWriter file, Type t, int n, string v = "v", string nprefix = "") { Write(file, "{0} {1};", SimpleType(t), v); WriteCheckType(file, t, n, v, nprefix); } private void WriteFunctionAttr(StreamWriter file) { Write(file, "[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]"); } ConstructorInfo[] GetValidConstructor(Type t) { List<ConstructorInfo> ret = new List<ConstructorInfo>(); if (t.GetConstructor(Type.EmptyTypes) == null && t.IsAbstract && t.IsSealed) return ret.ToArray(); if (t.IsAbstract) return ret.ToArray(); if (t.BaseType != null && t.BaseType.Name == "MonoBehaviour") return ret.ToArray(); ConstructorInfo[] cons = t.GetConstructors(BindingFlags.Instance | BindingFlags.Public); foreach (ConstructorInfo ci in cons) { if (!IsObsolete(ci) && !DontExport(ci) && !ContainUnsafe(ci)) ret.Add(ci); } return ret.ToArray(); } bool ContainUnsafe(MethodBase mi) { foreach (ParameterInfo p in mi.GetParameters()) { if (p.ParameterType.FullName.Contains("*")) return true; } return false; } bool DontExport(MemberInfo mi) { return mi.GetCustomAttributes(typeof(DoNotToLuaAttribute), false).Length > 0; } private void WriteConstructor(Type t, StreamWriter file) { ConstructorInfo[] cons = GetValidConstructor(t); if (cons.Length > 0) { WriteFunctionAttr(file); Write(file, "static public int constructor(IntPtr l) {"); WriteTry(file); if (cons.Length > 1) Write(file, "int argc = LuaDLL.lua_gettop(l);"); Write(file, "{0} o;", TypeDecl(t)); bool first = true; for (int n = 0; n < cons.Length; n++) { ConstructorInfo ci = cons[n]; ParameterInfo[] pars = ci.GetParameters(); if (cons.Length > 1) { if (isUniqueArgsCount(cons, ci)) Write(file, "{0}(argc=={1}){{", first ? "if" : "else if", ci.GetParameters().Length + 1); else Write(file, "{0}(matchType(l,argc,2{1})){{", first ? "if" : "else if", TypeDecl(pars)); } for (int k = 0; k < pars.Length; k++) { ParameterInfo p = pars[k]; bool hasParams = p.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0; CheckArgument(file, p.ParameterType, k, 2, p.IsOut, hasParams); } Write(file, "o=new {0}({1});", TypeDecl(t), FuncCall(ci)); WriteOk(file); if (t.Name == "String") // if export system.string, push string as ud not lua string Write(file, "pushObject(l,o);"); else Write(file, "pushValue(l,o);"); Write(file, "return 2;"); if (cons.Length == 1) WriteCatchExecption(file); Write(file, "}"); first = false; } if (cons.Length > 1) { Write(file, "return error(l,\"New object failed.\");"); WriteCatchExecption(file); Write(file, "}"); } } else if (t.IsValueType) // default constructor { WriteFunctionAttr(file); Write(file, "static public int constructor(IntPtr l) {"); WriteTry(file); Write(file, "{0} o;", FullName(t)); Write(file, "o=new {0}();", FullName(t)); WriteReturn(file,"o"); WriteCatchExecption(file); Write(file, "}"); } } void WriteOk(StreamWriter file) { Write(file, "pushValue(l,true);"); } void WriteBad(StreamWriter file) { Write(file, "pushValue(l,false);"); } void WriteError(StreamWriter file, string err) { WriteBad(file); Write(file, "LuaDLL.lua_pushstring(l,\"{0}\");",err); Write(file, "return 2;"); } void WriteReturn(StreamWriter file, string val) { Write(file, "pushValue(l,true);"); Write(file, "pushValue(l,{0});",val); Write(file, "return 2;"); } bool IsNotSupport(Type t) { if (t.IsSubclassOf(typeof(Delegate))) return true; return false; } string[] prefix = new string[] { "System.Collections.Generic" }; string RemoveRef(string s, bool removearray = true) { if (s.EndsWith("&")) s = s.Substring(0, s.Length - 1); if (s.EndsWith("[]") && removearray) s = s.Substring(0, s.Length - 2); if (s.StartsWith(prefix[0])) s = s.Substring(prefix[0].Length + 1, s.Length - prefix[0].Length - 1); s = s.Replace("+", "."); if (s.Contains("`")) { string regstr = @"`\d"; Regex r = new Regex(regstr, RegexOptions.None); s = r.Replace(s, ""); s = s.Replace("[", "<"); s = s.Replace("]", ">"); } return s; } string GenericBaseName(Type t) { string n = t.FullName; if (n.IndexOf('[') > 0) { n = n.Substring(0, n.IndexOf('[')); } return n.Replace("+", "."); } string GenericName(Type t) { try { Type[] tt = t.GetGenericArguments(); string ret = ""; for (int n = 0; n < tt.Length; n++) { string dt = SimpleType(tt[n]); ret += dt; if (n < tt.Length - 1) ret += "_"; } return ret; } catch (Exception e) { Debug.Log(e.ToString()); return ""; } } string _Name(string n) { string ret = ""; for (int i = 0; i < n.Length; i++) { if (char.IsLetterOrDigit(n[i])) ret += n[i]; else ret += "_"; } return ret; } string TypeDecl(ParameterInfo[] pars) { string ret = ""; for (int n = 0; n < pars.Length; n++) { ret += ",typeof("; if (pars[n].IsOut) ret += "LuaOut"; else ret += SimpleType(pars[n].ParameterType); ret += ")"; } return ret; } bool isUsefullMethod(MethodInfo method) { if (method.Name != "GetType" && method.Name != "GetHashCode" && method.Name != "Equals" && method.Name != "ToString" && method.Name != "Clone" && method.Name != "GetEnumerator" && method.Name != "CopyTo" && method.Name != "op_Implicit" && !method.Name.StartsWith("get_", StringComparison.Ordinal) && !method.Name.StartsWith("set_", StringComparison.Ordinal) && !method.Name.StartsWith("add_", StringComparison.Ordinal) && !IsObsolete(method) && !method.IsGenericMethod && //!method.Name.StartsWith("op_", StringComparison.Ordinal) && !method.Name.StartsWith("remove_", StringComparison.Ordinal)) { return true; } return false; } void WriteFunctionDec(StreamWriter file, string name) { WriteFunctionAttr(file); Write(file, "static public int {0}(IntPtr l) {{", name); } MethodBase[] GetMethods(Type t, string name, BindingFlags bf) { List<MethodBase> methods = new List<MethodBase>(); MemberInfo[] cons = t.GetMember(name, bf); foreach (MemberInfo m in cons) { if (m.MemberType == MemberTypes.Method && !IsObsolete(m) && !DontExport(m) && isUsefullMethod((MethodInfo)m)) methods.Add((MethodBase)m); } methods.Sort((a, b) => { return a.GetParameters().Length - b.GetParameters().Length; }); return methods.ToArray(); } void WriteFunctionImpl(StreamWriter file, MethodInfo m, Type t, BindingFlags bf) { WriteTry(file); MethodBase[] cons = GetMethods(t, m.Name, bf); if (cons.Length == 1) // no override function { if (isUsefullMethod(m) && !m.ReturnType.ContainsGenericParameters && !m.ContainsGenericParameters) // don't support generic method WriteFunctionCall(m, file, t); else { WriteError(file, "No matched override function to call"); } } else // 2 or more override function { Write(file, "int argc = LuaDLL.lua_gettop(l);"); bool first = true; for (int n = 0; n < cons.Length; n++) { if (cons[n].MemberType == MemberTypes.Method) { MethodInfo mi = cons[n] as MethodInfo; ParameterInfo[] pars = mi.GetParameters(); if (isUsefullMethod(mi) && !mi.ReturnType.ContainsGenericParameters /*&& !ContainGeneric(pars)*/) // don't support generic method { if (isUniqueArgsCount(cons, mi)) Write(file, "{0}(argc=={1}){{", first ? "if" : "else if", mi.IsStatic ? mi.GetParameters().Length : mi.GetParameters().Length + 1); else Write(file, "{0}(matchType(l,argc,{1}{2})){{", first ? "if" : "else if", mi.IsStatic ? 1 : 2, TypeDecl(pars)); WriteFunctionCall(mi, file, t); Write(file, "}"); first = false; } } } WriteError(file, "No matched override function to call"); } WriteCatchExecption(file); Write(file, "}"); } bool isUniqueArgsCount(MethodBase[] cons, MethodBase mi) { foreach (MethodBase member in cons) { MethodBase m = (MethodBase)member; if (m != mi && mi.GetParameters().Length == m.GetParameters().Length) return false; } return true; } void WriteCheckSelf(StreamWriter file, Type t) { if (t.IsValueType) { Write(file, "{0} self;", TypeDecl(t)); if(IsBaseType(t)) Write(file, "checkType(l,1,out self);"); else Write(file, "checkValueType(l,1,out self);"); } else Write(file, "{0} self=({0})checkSelf(l);", TypeDecl(t)); } private void WriteFunctionCall(MethodInfo m, StreamWriter file, Type t) { bool hasref = false; ParameterInfo[] pars = m.GetParameters(); int argIndex = 1; if (!m.IsStatic) { WriteCheckSelf(file, t); argIndex++; } for (int n = 0; n < pars.Length; n++) { ParameterInfo p = pars[n]; string pn = p.ParameterType.Name; if (pn.EndsWith("&")) { hasref = true; } bool hasParams = p.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0; CheckArgument(file, p.ParameterType, n, argIndex, p.IsOut, hasParams); } string ret = ""; if (m.ReturnType != typeof(void)) { ret = "var ret="; } if (m.IsStatic) { if (m.Name == "op_Multiply") Write(file, "{0}a1*a2;", ret); else if (m.Name == "op_Subtraction") Write(file, "{0}a1-a2;", ret); else if (m.Name == "op_Addition") Write(file, "{0}a1+a2;", ret); else if (m.Name == "op_Division") Write(file, "{0}a1/a2;", ret); else if (m.Name == "op_UnaryNegation") Write(file, "{0}-a1;", ret); else if (m.Name == "op_Equality") Write(file, "{0}(a1==a2);", ret); else if (m.Name == "op_Inequality") Write(file, "{0}(a1!=a2);", ret); else if (m.Name == "op_LessThan") Write(file, "{0}(a1<a2);", ret); else if (m.Name == "op_GreaterThan") Write(file, "{0}(a2<a1);", ret); else if (m.Name == "op_LessThanOrEqual") Write(file, "{0}(a1<=a2);", ret); else if (m.Name == "op_GreaterThanOrEqual") Write(file, "{0}(a2<=a1);", ret); else Write(file, "{3}{2}.{0}({1});", m.Name, FuncCall(m), TypeDecl(t), ret); } else Write(file, "{2}self.{0}({1});", m.Name, FuncCall(m), ret); WriteOk(file); int retcount = 1; if (m.ReturnType != typeof(void)) { WritePushValue(m.ReturnType, file); retcount = 2; } // push out/ref value for return value if (hasref) { for (int n = 0; n < pars.Length; n++) { ParameterInfo p = pars[n]; if (p.ParameterType.IsByRef) { WritePushValue(p.ParameterType, file, string.Format("a{0}", n + 1)); retcount++; } } } if (t.IsValueType && m.ReturnType == typeof(void) && !m.IsStatic) Write(file, "setBack(l,self);"); Write(file, "return {0};", retcount); } string SimpleType(Type t) { string tn = t.Name; switch (tn) { case "Single": return "float"; case "String": return "string"; case "Double": return "double"; case "Boolean": return "bool"; case "Int32": return "int"; case "Object": return FullName(t); default: tn = TypeDecl(t); tn = tn.Replace("System.Collections.Generic.", ""); tn = tn.Replace("System.Object", "object"); return tn; } } void WritePushValue(Type t, StreamWriter file) { if (t.IsEnum) Write(file, "pushEnum(l,(int)ret);"); else Write(file, "pushValue(l,ret);"); } void WritePushValue(Type t, StreamWriter file, string ret) { if (t.IsEnum) Write(file, "pushEnum(l,(int){0});", ret); else Write(file, "pushValue(l,{0});", ret); } void Write(StreamWriter file, string fmt, params object[] args) { if (fmt.StartsWith("}")) indent--; for (int n = 0; n < indent; n++) file.Write("\t"); if (args.Length == 0) file.WriteLine(fmt); else { string line = string.Format(fmt, args); file.WriteLine(line); } if (fmt.EndsWith("{")) indent++; } private void CheckArgument(StreamWriter file, Type t, int n, int argstart, bool isout, bool isparams) { Write(file, "{0} a{1};", TypeDecl(t), n + 1); if (!isout) { if (t.IsEnum) Write(file, "checkEnum(l,{0},out a{1});", n + argstart, n + 1); else if (t.BaseType == typeof(System.MulticastDelegate)) { tryMake(t); Write(file, "LuaDelegation.checkDelegate(l,{0},out a{1});", n + argstart, n + 1); } else if (isparams) { if(t.GetElementType().IsValueType && !IsBaseType(t.GetElementType())) Write(file, "checkValueParams(l,{0},out a{1});", n + argstart, n + 1); else Write(file, "checkParams(l,{0},out a{1});", n + argstart, n + 1); } else if (IsValueType(t)) { if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) Write(file, "checkNullable(l,{0},out a{1});", n + argstart, n + 1); else Write(file, "checkValueType(l,{0},out a{1});", n + argstart, n + 1); } else Write(file, "checkType(l,{0},out a{1});", n + argstart, n + 1); } } bool IsValueType(Type t) { return t.BaseType == typeof(ValueType) && !IsBaseType(t); } bool IsBaseType(Type t) { if (t.IsByRef) { t = t.GetElementType(); } return t.IsPrimitive || t == typeof(Color) || t == typeof(Vector2) || t == typeof(Vector3) || t == typeof(Vector4) || t == typeof(Quaternion) || t.Name == "Color2&" || t.Name == "Vector2&" || t.Name == "Vector3&" || t.Name == "Vector4&" || t.Name == "Quaternion&"; } string FullName(string str) { if (str == null) { throw new NullReferenceException(); } return RemoveRef(str.Replace("+", ".")); } string TypeDecl(Type t) { if (t.IsGenericType) { string ret = GenericBaseName(t); string gs = ""; gs += "<"; Type[] types = t.GetGenericArguments(); for (int n = 0; n < types.Length; n++) { gs += TypeDecl(types[n]); if (n < types.Length - 1) gs += ","; } gs += ">"; ret = Regex.Replace(ret, @"`\d", gs); return ret; } if (t.IsArray) { return TypeDecl(t.GetElementType()) + "[]"; } else return RemoveRef(t.ToString(), false); } string ExportName(Type t) { if (t.IsGenericType) { return string.Format("Lua_{0}_{1}", _Name(GenericBaseName(t)), _Name(GenericName(t))); } else { string name = RemoveRef(t.FullName, true); name = "Lua_" + name; return name.Replace(".", "_"); } } string FullName(Type t) { if (t.FullName == null) { Debug.Log(t.Name); return t.Name; } return FullName(t.FullName); } string FuncCall(MethodBase m) { string str = ""; ParameterInfo[] pars = m.GetParameters(); for (int n = 0; n < pars.Length; n++) { ParameterInfo p = pars[n]; if (p.ParameterType.IsByRef && p.IsOut) str += string.Format("out a{0}", n + 1); else if (p.ParameterType.IsByRef) str += string.Format("ref a{0}", n + 1); else str += string.Format("a{0}", n + 1); if (n < pars.Length - 1) str += ","; } return str; } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.AutoScaling.Model { /// <summary> /// Container for the parameters to the CreateLaunchConfiguration operation. /// <para> Creates a new launch configuration. The launch configuration name must be unique within the scope of the client's AWS account. The /// maximum limit of launch configurations, which by default is 100, must not yet have been met; otherwise, the call will fail. When created, /// the new launch configuration is available for immediate use. </para> <para>You can create a launch configuration with Amazon EC2 security /// groups or with Amazon VPC security groups. However, you can't use Amazon EC2 security groups together with Amazon VPC security groups, or /// vice versa.</para> <para><b>NOTE:</b> At this time, Auto Scaling launch configurations don't support compressed (e.g. zipped) user data /// files. </para> /// </summary> /// <seealso cref="Amazon.AutoScaling.AmazonAutoScaling.CreateLaunchConfiguration"/> public class CreateLaunchConfigurationRequest : AmazonWebServiceRequest { private string launchConfigurationName; private string imageId; private string keyName; private List<string> securityGroups = new List<string>(); private string userData; private string instanceType; private string kernelId; private string ramdiskId; private List<BlockDeviceMapping> blockDeviceMappings = new List<BlockDeviceMapping>(); private InstanceMonitoring instanceMonitoring; private string spotPrice; private string iamInstanceProfile; private bool? ebsOptimized; private bool? associatePublicIpAddress; /// <summary> /// The name of the launch configuration to create. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 255</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string LaunchConfigurationName { get { return this.launchConfigurationName; } set { this.launchConfigurationName = value; } } /// <summary> /// Sets the LaunchConfigurationName property /// </summary> /// <param name="launchConfigurationName">The value to set for the LaunchConfigurationName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithLaunchConfigurationName(string launchConfigurationName) { this.launchConfigurationName = launchConfigurationName; return this; } // Check to see if LaunchConfigurationName property is set internal bool IsSetLaunchConfigurationName() { return this.launchConfigurationName != null; } /// <summary> /// Unique ID of the <i>Amazon Machine Image</i> (AMI) you want to use to launch your EC2 instances. For information about finding Amazon EC2 /// AMIs, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html">Finding a Suitable AMI</a> in the <i>Amazon /// Elastic Compute Cloud User Guide</i>. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 255</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string ImageId { get { return this.imageId; } set { this.imageId = value; } } /// <summary> /// Sets the ImageId property /// </summary> /// <param name="imageId">The value to set for the ImageId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithImageId(string imageId) { this.imageId = imageId; return this; } // Check to see if ImageId property is set internal bool IsSetImageId() { return this.imageId != null; } /// <summary> /// The name of the Amazon EC2 key pair. For more information, see <a /// href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/generating-a-keypair.html">Getting a Key Pair</a> in the <i>Amazon Elastic Compute /// Cloud User Guide</i>. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 255</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string KeyName { get { return this.keyName; } set { this.keyName = value; } } /// <summary> /// Sets the KeyName property /// </summary> /// <param name="keyName">The value to set for the KeyName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithKeyName(string keyName) { this.keyName = keyName; return this; } // Check to see if KeyName property is set internal bool IsSetKeyName() { return this.keyName != null; } /// <summary> /// The security groups with which to associate Amazon EC2 or Amazon VPC instances. If your instances are launched in EC2, you can either /// specify Amazon EC2 security group names or the security group IDs. For more information about Amazon EC2 security groups, see <a /// href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/index.html?using-network-security.html"> Using Security Groups</a> in the <i>Amazon /// Elastic Compute Cloud User Guide</i>. If your instances are launched within VPC, specify Amazon VPC security group IDs. For more information /// about Amazon VPC security groups, see <a /// href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/index.html?VPC_SecurityGroups.html">Security Groups</a> in the <i>Amazon Virtual /// Private Cloud User Guide</i>. /// /// </summary> public List<string> SecurityGroups { get { return this.securityGroups; } set { this.securityGroups = value; } } /// <summary> /// Adds elements to the SecurityGroups collection /// </summary> /// <param name="securityGroups">The values to add to the SecurityGroups collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithSecurityGroups(params string[] securityGroups) { foreach (string element in securityGroups) { this.securityGroups.Add(element); } return this; } /// <summary> /// Adds elements to the SecurityGroups collection /// </summary> /// <param name="securityGroups">The values to add to the SecurityGroups collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithSecurityGroups(IEnumerable<string> securityGroups) { foreach (string element in securityGroups) { this.securityGroups.Add(element); } return this; } // Check to see if SecurityGroups property is set internal bool IsSetSecurityGroups() { return this.securityGroups.Count > 0; } /// <summary> /// The user data to make available to the launched Amazon EC2 instances. For more information about Amazon EC2 user data, see <a /// href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html#instancedata-user-data-retrieval">User Data /// Retrieval</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 21847</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string UserData { get { return this.userData; } set { this.userData = value; } } /// <summary> /// Sets the UserData property /// </summary> /// <param name="userData">The value to set for the UserData property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithUserData(string userData) { this.userData = userData; return this; } // Check to see if UserData property is set internal bool IsSetUserData() { return this.userData != null; } /// <summary> /// The instance type of the Amazon EC2 instance. For information about available Amazon EC2 instance types, see <a /// href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#AvailableInstanceTypes"> Available Instance Types</a> in the /// <i>Amazon Elastic Cloud Compute User Guide.</i> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 255</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string InstanceType { get { return this.instanceType; } set { this.instanceType = value; } } /// <summary> /// Sets the InstanceType property /// </summary> /// <param name="instanceType">The value to set for the InstanceType property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithInstanceType(string instanceType) { this.instanceType = instanceType; return this; } // Check to see if InstanceType property is set internal bool IsSetInstanceType() { return this.instanceType != null; } /// <summary> /// The ID of the kernel associated with the Amazon EC2 AMI. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 255</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string KernelId { get { return this.kernelId; } set { this.kernelId = value; } } /// <summary> /// Sets the KernelId property /// </summary> /// <param name="kernelId">The value to set for the KernelId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithKernelId(string kernelId) { this.kernelId = kernelId; return this; } // Check to see if KernelId property is set internal bool IsSetKernelId() { return this.kernelId != null; } /// <summary> /// The ID of the RAM disk associated with the Amazon EC2 AMI. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 255</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string RamdiskId { get { return this.ramdiskId; } set { this.ramdiskId = value; } } /// <summary> /// Sets the RamdiskId property /// </summary> /// <param name="ramdiskId">The value to set for the RamdiskId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithRamdiskId(string ramdiskId) { this.ramdiskId = ramdiskId; return this; } // Check to see if RamdiskId property is set internal bool IsSetRamdiskId() { return this.ramdiskId != null; } /// <summary> /// A list of mappings that specify how block devices are exposed to the instance. Each mapping is made up of a <i>VirtualName</i>, a /// <i>DeviceName</i>, and an <i>ebs</i> data structure that contains information about the associated Elastic Block Storage volume. For more /// information about Amazon EC2 BlockDeviceMappings, go to <a /// href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/index.html?block-device-mapping-concepts.html"> Block Device Mapping</a> in the /// Amazon EC2 product documentation. /// /// </summary> public List<BlockDeviceMapping> BlockDeviceMappings { get { return this.blockDeviceMappings; } set { this.blockDeviceMappings = value; } } /// <summary> /// Adds elements to the BlockDeviceMappings collection /// </summary> /// <param name="blockDeviceMappings">The values to add to the BlockDeviceMappings collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithBlockDeviceMappings(params BlockDeviceMapping[] blockDeviceMappings) { foreach (BlockDeviceMapping element in blockDeviceMappings) { this.blockDeviceMappings.Add(element); } return this; } /// <summary> /// Adds elements to the BlockDeviceMappings collection /// </summary> /// <param name="blockDeviceMappings">The values to add to the BlockDeviceMappings collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithBlockDeviceMappings(IEnumerable<BlockDeviceMapping> blockDeviceMappings) { foreach (BlockDeviceMapping element in blockDeviceMappings) { this.blockDeviceMappings.Add(element); } return this; } // Check to see if BlockDeviceMappings property is set internal bool IsSetBlockDeviceMappings() { return this.blockDeviceMappings.Count > 0; } /// <summary> /// Enables detailed monitoring if it is disabled. Detailed monitoring is enabled by default. When detailed monitoring is enabled, Amazon /// Cloudwatch will generate metrics every minute and your account will be charged a fee. When you disable detailed monitoring, by specifying /// <c>False</c>, Cloudwatch will generate metrics every 5 minutes. For more information, see <a /// href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/as-instance-monitoring.html">Monitor Your Auto Scaling Instances</a>. For /// information about Amazon CloudWatch, see the <a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/Welcome.html">Amazon /// CloudWatch Developer Guide</a>. /// /// </summary> public InstanceMonitoring InstanceMonitoring { get { return this.instanceMonitoring; } set { this.instanceMonitoring = value; } } /// <summary> /// Sets the InstanceMonitoring property /// </summary> /// <param name="instanceMonitoring">The value to set for the InstanceMonitoring property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithInstanceMonitoring(InstanceMonitoring instanceMonitoring) { this.instanceMonitoring = instanceMonitoring; return this; } // Check to see if InstanceMonitoring property is set internal bool IsSetInstanceMonitoring() { return this.instanceMonitoring != null; } /// <summary> /// The maximum hourly price to be paid for any Spot Instance launched to fulfill the request. Spot Instances are launched when the price you /// specify exceeds the current Spot market price. For more information on launching Spot Instances, see <a /// href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/US-SpotInstances.html"> Using Auto Scaling to Launch Spot Instances</a> /// in the <i>Auto Scaling Developer Guide</i>. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 255</description> /// </item> /// </list> /// </para> /// </summary> public string SpotPrice { get { return this.spotPrice; } set { this.spotPrice = value; } } /// <summary> /// Sets the SpotPrice property /// </summary> /// <param name="spotPrice">The value to set for the SpotPrice property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithSpotPrice(string spotPrice) { this.spotPrice = spotPrice; return this; } // Check to see if SpotPrice property is set internal bool IsSetSpotPrice() { return this.spotPrice != null; } /// <summary> /// The name or the Amazon Resource Name (ARN) of the instance profile associated with the IAM role for the instance. Amazon EC2 instances /// launched with an IAM role will automatically have AWS security credentials available. You can use IAM roles with Auto Scaling to /// automatically enable applications running on your Amazon EC2 instances to securely access other AWS resources. For information on launching /// EC2 instances with an IAM role, go to <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/us-iam-role.html">Launching Auto /// Scaling Instances With an IAM Role</a> in the <i>Auto Scaling Developer Guide</i>. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 1600</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string IamInstanceProfile { get { return this.iamInstanceProfile; } set { this.iamInstanceProfile = value; } } /// <summary> /// Sets the IamInstanceProfile property /// </summary> /// <param name="iamInstanceProfile">The value to set for the IamInstanceProfile property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithIamInstanceProfile(string iamInstanceProfile) { this.iamInstanceProfile = iamInstanceProfile; return this; } // Check to see if IamInstanceProfile property is set internal bool IsSetIamInstanceProfile() { return this.iamInstanceProfile != null; } /// <summary> /// Whether the instance is optimized for EBS I/O. The optimization provides dedicated throughput to Amazon EBS and an optimized configuration /// stack to provide optimal EBS I/O performance. This optimization is not available with all instance types. Additional usage charges apply /// when using an EBS Optimized instance. By default the instance is not optimized for EBS I/O. For information about EBS-optimized instances, /// go to <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#EBSOptimized">EBS-Optimized Instances</a> in the /// <i>Amazon Elastic Compute Cloud User Guide</i>. /// /// </summary> public bool EbsOptimized { get { return this.ebsOptimized ?? default(bool); } set { this.ebsOptimized = value; } } /// <summary> /// Sets the EbsOptimized property /// </summary> /// <param name="ebsOptimized">The value to set for the EbsOptimized property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithEbsOptimized(bool ebsOptimized) { this.ebsOptimized = ebsOptimized; return this; } // Check to see if EbsOptimized property is set internal bool IsSetEbsOptimized() { return this.ebsOptimized.HasValue; } /// <summary> /// Used for Auto Scaling groups that launch instances into a Virtual Private Cloud (VPC). Specifies whether to assign a public IP address to /// each instance launched in a Amazon VPC. <note> If you specify a value for this parameter, be sure to specify at least one VPC subnet using /// the <i>VPCZoneIdentifier</i> parameter when you create your Auto Scaling group. </note> Default: If the instance is launched in default VPC, /// the default is <c>true</c>. If the instance is launched in EC2-VPC, the default is <c>false</c>. For more information about the platforms /// supported by Auto Scaling, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/US_BasicSetup.html">Basic Auto Scaling /// Configuration</a>. /// /// </summary> public bool AssociatePublicIpAddress { get { return this.associatePublicIpAddress ?? default(bool); } set { this.associatePublicIpAddress = value; } } /// <summary> /// Sets the AssociatePublicIpAddress property /// </summary> /// <param name="associatePublicIpAddress">The value to set for the AssociatePublicIpAddress property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateLaunchConfigurationRequest WithAssociatePublicIpAddress(bool associatePublicIpAddress) { this.associatePublicIpAddress = associatePublicIpAddress; return this; } // Check to see if AssociatePublicIpAddress property is set internal bool IsSetAssociatePublicIpAddress() { return this.associatePublicIpAddress.HasValue; } } }
using System; using System.Windows.Forms; using System.Diagnostics; using System.Collections.Generic; using Microsoft.Win32; using System.IO; using System.Text; using System.Runtime.InteropServices; // MRI list manager. // // Written by: Alex Farber // // alexm@cmt.co.il /******************************************************************************* Using: 1) Add menu item Recent Files (or any name you want) to main application menu. This item is used by MRUManager as popup menu for MRU list. 2) Implement IMRUClient inteface in the form class: public class Form1 : System.Windows.Forms.Form, IMRUClient { public void OpenMRUFile(string fileName) { // open file here } // ... } 3) Add MRUManager member to the form class and initialize it: private MRUManager mruManager; private void Form1_Load(object sender, System.EventArgs e) { mruManager = new MRUManager(); mruManager.Initialize( this, // owner form mnuFileMRU, // Recent Files menu item "Software\\MyCompany\\MyProgram"); // Registry path to keep MRU list // Optional. Call these functions to change default values: mruManager.CurrentDir = "....."; // default is current directory mruManager.MaxMRULength = ...; // default is 10 mruMamager.MaxDisplayNameLength = ...; // default is 40 } NOTES: - If Registry path is, for example, "Software\MyCompany\MyProgram", MRU list is kept in HKEY_CURRENT_USER\Software\MyCompany\MyProgram\MRU Registry entry. - CurrentDir is used to show file names in the menu. If file is in this directory, only file name is shown. 4) Call MRUManager Add and Remove functions when necessary: mruManager.Add(fileName); // when file is successfully opened mruManager.Remove(fileName); // when Open File operation failed *******************************************************************************/ // Implementation details: // // MRUManager loads MRU list from Registry in Initialize function. // List is saved in Registry when owner form is closed. // // MRU list in the menu is updated when parent menu is poped-up. // // Owner form OpenMRUFile function is called when user selects file // from MRU list. /// <summary> /// Interface which should be implemented by owner form /// to use MRUManager. /// </summary> public interface IMRUClient { void OpenMRUFile(string fileName); } /// <summary> /// MRU manager - manages Most Recently Used Files list /// for Windows Form application. /// </summary> public class MRUManager : IEnumerable<String> { #region Members private Form ownerForm; // owner form private MenuItem menuItemMRU; // Recent Files menu item private MenuItem menuItemParent; // Recent Files menu item parent private string registryPath; // Registry path to keep MRU list private int maxNumberOfFiles = 10; // maximum number of files in MRU list private int maxDisplayLength = 40; // maximum length of file name for display private string currentDirectory; // current directory private List<String> mruList; // MRU list (file names) private const string regEntryName = "file"; // entry name to keep MRU (file0, file1...) #endregion #region Windows API // BOOL PathCompactPathEx( // LPTSTR pszOut, // LPCTSTR pszSrc, // UINT cchMax, // DWORD dwFlags // ); [DllImport("shlwapi.dll", CharSet = CharSet.Auto)] private static extern bool PathCompactPathEx( StringBuilder pszOut, string pszPath, int cchMax, int reserved); #endregion #region Constructor public MRUManager() { mruList = new List<string>(); } #endregion #region Public Properties /// <summary> /// Maximum length of displayed file name in menu (default is 40). /// /// Set this property to change default value (optional). /// </summary> public int MaxDisplayNameLength { set { maxDisplayLength = value; if (maxDisplayLength < 10) maxDisplayLength = 10; } get { return maxDisplayLength; } } /// <summary> /// Maximum length of MRU list (default is 10). /// /// Set this property to change default value (optional). /// </summary> public int MaxMRULength { set { maxNumberOfFiles = value; if (maxNumberOfFiles < 1) maxNumberOfFiles = 1; if (mruList.Count > maxNumberOfFiles) mruList.RemoveRange(maxNumberOfFiles - 1, mruList.Count - maxNumberOfFiles); } get { return maxNumberOfFiles; } } /// <summary> /// Set current directory. /// /// Default value is program current directory which is set when /// Initialize function is called. /// /// Set this property to change default value (optional) /// after call to Initialize. /// </summary> public string CurrentDir { set { currentDirectory = value; } get { return currentDirectory; } } #endregion #region Public Functions /// <summary> /// Initialization. Call this function in form Load handler. /// </summary> /// <param name="owner">Owner form</param> /// <param name="mruItem">Recent Files menu item</param> /// <param name="regPath">Registry Path to keep MRU list</param> public void Initialize(Form owner, MenuItem mruItem, string regPath) { // keep reference to owner form ownerForm = owner; // check if owner form implements IMRUClient interface if (!(owner is IMRUClient)) { throw new Exception( "MRUManager: Owner form doesn't implement IMRUClient interface"); } // keep reference to MRU menu item menuItemMRU = mruItem; if (menuItemMRU != null) { try { menuItemParent = (MenuItem) menuItemMRU.Parent; } catch { } } // keep Registry path adding MRU key to it registryPath = regPath; // keep current directory in the time of initialization currentDirectory = Directory.GetCurrentDirectory(); // subscribe to MRU parent Popup event if (menuItemParent != null) { menuItemParent.Popup += new EventHandler(this.OnMRUParentPopup); } // subscribe to owner form Closing event ownerForm.Closing += new System.ComponentModel.CancelEventHandler(OnOwnerClosing); // load MRU list from Registry LoadMRU(); } /// <summary> /// Add file name to MRU list. /// Call this function when file is opened successfully. /// If file already exists in the list, it is moved to the first place. /// </summary> /// <param name="file">File Name</param> public void Add(string file) { Remove(file); // if array has maximum length, remove last element if (mruList.Count == maxNumberOfFiles) mruList.RemoveAt(maxNumberOfFiles - 1); // add new file name to the start of array mruList.Insert(0, file); } public void Clear() { mruList.Clear(); } public void AddRange(IEnumerable<String> files) { foreach (String file in files) { Add(file); } } /// <summary> /// Remove file name from MRU list. /// Call this function when File - Open operation failed. /// </summary> /// <param name="file">File Name</param> public void Remove(string file) { int i = 0; IEnumerator<String> myEnumerator = mruList.GetEnumerator(); while (myEnumerator.MoveNext()) { if (myEnumerator.Current == file) { mruList.RemoveAt(i); return; } i++; } } #endregion #region Event Handlers /// <summary> /// Update MRU list when MRU menu item parent is opened /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnMRUParentPopup(object sender, EventArgs e) { // remove all childs if (menuItemMRU.IsParent) { menuItemMRU.MenuItems.Clear(); } // Disable menu item if MRU list is empty if (mruList.Count == 0) { menuItemMRU.Enabled = false; return; } // enable menu item and add child items menuItemMRU.Enabled = true; MenuItem item; IEnumerator<String> myEnumerator = mruList.GetEnumerator(); while (myEnumerator.MoveNext()) { item = new MenuItem(GetDisplayName((string)myEnumerator.Current)); // subscribe to item's Click event item.Click += new EventHandler(this.OnMRUClicked); menuItemMRU.MenuItems.Add(item); } } /// <summary> /// MRU menu item is clicked - call owner's OpenMRUFile function /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnMRUClicked(object sender, EventArgs e) { string s; // cast sender object to MenuItem MenuItem item = (MenuItem)sender; if (item != null) { // Get file name from list using item index s = mruList[item.Index]; // call owner's OpenMRUFile function if (s.Length > 0) { ((IMRUClient)ownerForm).OpenMRUFile(s); } } } /// <summary> /// Save MRU list in Registry when owner form is closing /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnOwnerClosing(object sender, System.ComponentModel.CancelEventArgs e) { int i, n; RegistryKey key = Registry.CurrentUser.CreateSubKey(registryPath); if (key != null) { n = mruList.Count; for (i = 0; i < maxNumberOfFiles; i++) { key.DeleteValue(regEntryName + i.ToString(), false); } for (i = 0; i < n; i++) { key.SetValue(regEntryName + i.ToString(), mruList[i]); } } } #endregion #region Private Functions /// <summary> /// Load MRU list from Registry. /// Called from Initialize. /// </summary> private void LoadMRU() { string sKey, s; mruList.Clear(); RegistryKey key = Registry.CurrentUser.OpenSubKey(registryPath); if (key != null) { for (int i = 0; i < maxNumberOfFiles; i++) { sKey = regEntryName + i.ToString(); s = (string)key.GetValue(sKey, ""); if (s.Length == 0) break; mruList.Add(s); } } } /// <summary> /// Get display file name from full name. /// </summary> /// <param name="fullName">Full file name</param> /// <returns>Short display name</returns> private string GetDisplayName(string fullName) { // if file is in current directory, show only file name FileInfo fileInfo = new FileInfo(fullName); if (fileInfo.DirectoryName == currentDirectory) return GetShortDisplayName(fileInfo.Name, maxDisplayLength); return GetShortDisplayName(fullName, maxDisplayLength); } /// <summary> /// Truncate a path to fit within a certain number of characters /// by replacing path components with ellipses. /// /// This solution is provided by CodeProject and GotDotNet C# expert /// Richard Deeming. /// /// </summary> /// <param name="longName">Long file name</param> /// <param name="maxLen">Maximum length</param> /// <returns>Truncated file name</returns> private string GetShortDisplayName(string longName, int maxLen) { StringBuilder pszOut = new StringBuilder(maxLen + maxLen + 2); // for safety if (PathCompactPathEx(pszOut, longName, maxLen, 0)) { return pszOut.ToString(); } else { return longName; } } #endregion #region IEnumerable<string> Members public IEnumerator<string> GetEnumerator() { return mruList.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return mruList.GetEnumerator(); } #endregion }
/*- * Copyright (c) 2009, 2020 Oracle and/or its affiliates. All rights reserved. * * See the file LICENSE for license information. * */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using NUnit.Framework; using BerkeleyDB; namespace CsharpAPITest { [TestFixture] public class CursorTest : CSharpTestFixture { private DatabaseEnvironment paramEnv; private BTreeDatabase paramDB; private Transaction readTxn; private Transaction updateTxn; private EventWaitHandle signal; private delegate void CursorMoveFuncDelegate( Cursor cursor, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lockingInfo); private CursorMoveFuncDelegate cursorFunc; [TestFixtureSetUp] public void SetUpTestFixture() { testFixtureName = "CursorTest"; base.SetUpTestfixture(); } [Test] public void TestAdd() { BTreeDatabase db; BTreeCursor cursor; testName = "TestAdd"; SetUpTest(true); // Open a database and a cursor. GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add a record and confirm that it exists. AddOneByCursor(db, cursor); // Intend to insert pair to a wrong position. KeyValuePair<DatabaseEntry, DatabaseEntry> pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>( new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key")), new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data"))); try { try { cursor.Add(pair, Cursor.InsertLocation.AFTER); throw new TestException(); } catch (ArgumentException) {} try { cursor.Add(pair, Cursor.InsertLocation.BEFORE); throw new TestException(); } catch (ArgumentException) {} } finally { cursor.Close(); db.Close(); } } [Test] public void TestCompare() { BTreeDatabase db; BTreeCursor dbc1, dbc2; DatabaseEntry data, key; testName = "TestCompare"; SetUpTest(true); // Open a database and a cursor. Then close it. GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out dbc1); dbc2 = db.Cursor(); for (int i = 0; i < 10; i++) { key = new DatabaseEntry(BitConverter.GetBytes(i)); data = new DatabaseEntry(BitConverter.GetBytes(i)); db.Put(key, data); } key = new DatabaseEntry(BitConverter.GetBytes(5)); Assert.IsTrue(dbc1.Move(key, true)); Assert.IsTrue(dbc2.Move(key, true)); Assert.IsTrue(dbc1.Compare(dbc2)); Assert.IsTrue(dbc1.MoveNext()); Assert.IsFalse(dbc1.Compare(dbc2)); dbc1.Close(); dbc2.Close(); db.Close(); } [Test] public void TestClose() { BTreeDatabase db; BTreeCursor cursor; testName = "TestClose"; SetUpTest(true); // Open a database and a cursor. Then close it. GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); cursor.Close(); db.Close(); } [Test] public void TestCloseResmgr() { testName = "TestCloseResmgr"; SetUpTest(true); TestCloseResmgr_int(true); TestCloseResmgr_int(false); } void TestCloseResmgr_int(bool havetxn) { BTreeDatabase db; BTreeCursor cursor, csr; CursorConfig cursorConfig; DatabaseEnvironment env; Transaction txn; DatabaseEntry key, data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; txn = null; cursorConfig = new CursorConfig(); // Open an environment, a database and a cursor. if (havetxn) GetCursorInBtreeDBInTDS(testHome, testName, cursorConfig, out env, out db, out cursor, out txn); else GetCursorInBtreeDB(testHome, testName, cursorConfig, out env, out db, out cursor); // Add a record to db via cursor. key = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")); data = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("data")); pair = new KeyValuePair<DatabaseEntry,DatabaseEntry> (key, data); byte []kbytes; byte []dbytes; for (int i = 0; i < 100; i++) { kbytes = ASCIIEncoding.ASCII. GetBytes("key" + i); dbytes = ASCIIEncoding.ASCII. GetBytes("data" + i); key.Data = kbytes; data.Data = dbytes; cursor.Add(pair); } // Do not close cursor. csr = db.Cursor(cursorConfig, txn); while (csr.MoveNext()) { // Do nothing for now. } // Do not close csr. if (havetxn && txn != null) txn.Commit(); env.CloseForceSync(); } [Test] public void TestCount() { BTreeDatabase db; BTreeCursor cursor; testName = "TestCount"; SetUpTest(true); // Write one record into database with cursor. GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); AddOneByCursor(db, cursor); /* * Confirm that that the count operation returns 1 as * the number of records in the database. */ Assert.AreEqual(1, cursor.Count()); cursor.Close(); db.Close(); } [Test] public void TestCurrent() { BTreeDatabase db; BTreeCursor cursor; testName = "TestCurrent"; SetUpTest(true); // Write a record into database with cursor. GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); AddOneByCursor(db, cursor); /* * Confirm the current record that the cursor * points to is the one that just added by the * cursor. */ Assert.IsTrue(cursor.MoveFirst()); Assert.AreEqual( ASCIIEncoding.ASCII.GetBytes("key"), cursor.Current.Key.Data); Assert.AreEqual( ASCIIEncoding.ASCII.GetBytes("data"), cursor.Current.Value.Data); cursor.Close(); db.Close(); } [Test] public void TestDelete() { BTreeDatabase db; BTreeCursor cursor; testName = "TestDelete"; SetUpTest(true); // Write a record into database with cursor. GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); AddOneByCursor(db, cursor); // Delete the current record. cursor.Delete(); // Confirm that the record no longer exists in the db. Assert.AreEqual(0, cursor.Count()); cursor.Close(); db.Close(); } [Test] public void TestDispose() { BTreeDatabase db; BTreeCursor cursor; testName = "TestDispose"; SetUpTest(true); // Write a record into database with cursor. GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Dispose the cursor. cursor.Dispose(); db.Close(); } [Test] public void TestDuplicate() { DatabaseEnvironment env; BTreeDatabase db; BTreeCursor cursor; Transaction txn; testName = "TestDuplicate"; SetUpTest(true); GetCursorInBtreeDBInTDS(testHome, testName, new CursorConfig(), out env, out db, out cursor, out txn); for (int i = 0; i < 10; i++) cursor.Add(new KeyValuePair< DatabaseEntry, DatabaseEntry>( new DatabaseEntry(BitConverter.GetBytes(i)), new DatabaseEntry(BitConverter.GetBytes(i)))); // Duplicate the cursor and keep its position. BTreeCursor newCursor = cursor.Duplicate(true); Assert.AreEqual(newCursor.Current.Key, cursor.Current.Key); Assert.AreEqual(newCursor.Current.Key, cursor.Current.Key); cursor.Close(); newCursor.Close(); db.Close(); txn.Commit(); env.Close(); } [Test] public void TestIsolationDegree() { BTreeDatabase db; BTreeCursor cursor; CursorConfig cursorConfig; DatabaseEnvironment env; Transaction txn; testName = "TestIsolationDegree"; SetUpTest(true); Isolation[] isolationDegrees = new Isolation[3]; isolationDegrees[0] = Isolation.DEGREE_ONE; isolationDegrees[1] = Isolation.DEGREE_TWO; isolationDegrees[2] = Isolation.DEGREE_THREE; IsolationDelegate[] delegates = { new IsolationDelegate(CursorReadUncommited), new IsolationDelegate(CursorReadCommited), new IsolationDelegate(CursorRead)}; cursorConfig = new CursorConfig(); for (int i = 0; i < 3; i++) { cursorConfig.IsolationDegree = isolationDegrees[i]; GetCursorInBtreeDBInTDS(testHome + "/" + i.ToString(), testName, cursorConfig, out env, out db, out cursor, out txn); cursor.Close(); db.Close(); txn.Commit(); env.Close(); } } public delegate void IsolationDelegate( DatabaseEnvironment env, BTreeDatabase db, Cursor cursor, Transaction txn); /* * Configure a transactional cursor to have degree 2 * isolation, which permits data read by this cursor * to be deleted prior to the commit of the transaction * for this cursor. */ public void CursorReadCommited( DatabaseEnvironment env, BTreeDatabase db, Cursor cursor, Transaction txn) { Console.WriteLine("CursorReadCommited"); } /* * Configure a transactional cursor to have degree 1 * isolation. The cursor's read operations could return * modified but not yet commited data. */ public void CursorReadUncommited( DatabaseEnvironment env, BTreeDatabase db, Cursor cursor, Transaction txn) { Console.WriteLine("CursorReadUncommited"); } /* * Only return committed data. */ public void CursorRead( DatabaseEnvironment env, BTreeDatabase db, Cursor cursor, Transaction txn) { Console.WriteLine("CursorRead"); } [Test] public void TestMoveToExactKey() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMoveToExactKey"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add one record into database. DatabaseEntry key = new DatabaseEntry( BitConverter.GetBytes((int)0)); DatabaseEntry data = new DatabaseEntry( BitConverter.GetBytes((int)0)); KeyValuePair<DatabaseEntry, DatabaseEntry> pair = new KeyValuePair<DatabaseEntry,DatabaseEntry>( key, data); cursor.Add(pair); // Move the cursor exactly to the specified key. MoveCursor(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMoveToExactPair() { BTreeDatabase db; BTreeCursor cursor; DatabaseEntry key, data; testName = "TestMoveToExactPair"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add one record into database. key = new DatabaseEntry( BitConverter.GetBytes((int)0)); data = new DatabaseEntry( BitConverter.GetBytes((int)0)); KeyValuePair<DatabaseEntry, DatabaseEntry> pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); cursor.Add(pair); // Move the cursor exactly to the specified key/data pair. MoveCursor(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMoveWithRMW() { testName = "TestMoveWithRMW"; SetUpTest(true); // Use MoveCursor() as its move function. cursorFunc = new CursorMoveFuncDelegate(MoveCursor); // Move to a specified key and a key/data pair. MoveWithRMW(testHome, testName); } [Test] public void TestMoveFirst() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMoveFirst"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); AddOneByCursor(db, cursor); // Move to the first record. MoveCursorToFirst(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMoveFirstWithRMW() { testName = "TestMoveFirstWithRMW"; SetUpTest(true); // Use MoveCursorToFirst() as its move function. cursorFunc = new CursorMoveFuncDelegate(MoveCursorToFirst); // Read the first record with write lock. MoveWithRMW(testHome, testName); } [Test] public void TestMoveLast() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMoveLast"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); AddOneByCursor(db, cursor); // Move the cursor to the last record. MoveCursorToLast(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMoveLastWithRMW() { testName = "TestMoveLastWithRMW"; SetUpTest(true); // Use MoveCursorToLast() as its move function. cursorFunc = new CursorMoveFuncDelegate(MoveCursorToLast); // Read the last recod with write lock. MoveWithRMW(testHome, testName); } [Test] public void TestMoveNext() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMoveNext"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Put ten records to the database. for (int i = 0; i < 10; i++) db.Put(new DatabaseEntry(BitConverter.GetBytes(i)), new DatabaseEntry(BitConverter.GetBytes(i))); // Move the cursor from the first record to the fifth. MoveCursorToNext(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMoveNextWithRMW() { testName = "TestMoveLastWithRMW"; SetUpTest(true); // Use MoveCursorToNext() as its move function. cursorFunc = new CursorMoveFuncDelegate( MoveCursorToNext); /* * Read the first record to the fifth record with * write lock. */ MoveWithRMW(testHome, testName); } [Test] public void TestMoveNextDuplicate() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMoveNextDuplicate"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add ten duplicate records to the database. for (int i = 0; i < 10; i++) db.Put(new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")), new DatabaseEntry( BitConverter.GetBytes(i))); /* * Move the cursor from one duplicate record to * another duplicate one. */ MoveCursorToNextDuplicate(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMoveNextDuplicateWithRMW() { testName = "TestMoveNextDuplicateWithRMW"; SetUpTest(true); /* * Use MoveCursorToNextDuplicate() as its * move function. */ cursorFunc = new CursorMoveFuncDelegate( MoveCursorToNextDuplicate); /* * Read the first record to the fifth record with * write lock. */ MoveWithRMW(testHome, testName); } [Test] public void TestMoveNextUnique() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMoveNextUnique"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add ten different records to the database. for (int i = 0; i < 10; i++) db.Put(new DatabaseEntry( BitConverter.GetBytes(i)), new DatabaseEntry( BitConverter.GetBytes(i))); // Move to five unique records. MoveCursorToNextUnique(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMoveNextUniqueWithRMW() { testName = "TestMoveNextUniqueWithRMW"; SetUpTest(true); /* * Use MoveCursorToNextUnique() as its * move function. */ cursorFunc = new CursorMoveFuncDelegate( MoveCursorToNextUnique); /* * Move to five unique records. */ MoveWithRMW(testHome, testName); } [Test] public void TestMovePrev() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMovePrev"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add ten records to the database. for (int i = 0; i < 10; i++) AddOneByCursor(db, cursor); // Move the cursor to previous five records MoveCursorToPrev(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMovePrevWithRMW() { testName = "TestMovePrevWithRMW"; SetUpTest(true); /* * Use MoveCursorToNextDuplicate() as its * move function. */ cursorFunc = new CursorMoveFuncDelegate( MoveCursorToPrev); // Read previous record in write lock. MoveWithRMW(testHome, testName); } [Test] public void TestMovePrevDuplicate() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMovePrevDuplicate"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add ten records to the database. for (int i = 0; i < 10; i++) AddOneByCursor(db, cursor); // Move the cursor to previous duplicate records. MoveCursorToPrevDuplicate(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMovePrevDuplicateWithRMW() { testName = "TestMovePrevDuplicateWithRMW"; SetUpTest(true); /* * Use MoveCursorToNextDuplicate() as its * move function. */ cursorFunc = new CursorMoveFuncDelegate( MoveCursorToPrevDuplicate); // Read the previous duplicate record in write lock. MoveWithRMW(testHome, testName); } [Test] public void TestMovePrevUnique() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMovePrevUnique"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add ten records to the database. for (int i = 0; i < 10; i++) db.Put(new DatabaseEntry(BitConverter.GetBytes(i)), new DatabaseEntry(BitConverter.GetBytes(i))); // Move the cursor to previous unique records. MoveCursorToPrevUnique(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMovePrevUniqueWithRMW() { testName = "TestMovePrevDuplicateWithRMW"; SetUpTest(true); /* * Use MoveCursorToPrevUnique() as its * move function. */ cursorFunc = new CursorMoveFuncDelegate( MoveCursorToPrevUnique); // Read the previous unique record in write lock. MoveWithRMW(testHome, testName); } [Test] public void TestPartialPut() { testName = "TestPartialPut"; SetUpTest(true); BTreeDatabaseConfig cfg = new BTreeDatabaseConfig(); cfg.Creation = CreatePolicy.IF_NEEDED; BTreeDatabase db = BTreeDatabase.Open( testHome + "/" + testName, cfg); PopulateDb(ref db); /* * Partially replace the first byte in the current * data with 'a', and verify that the first byte in * the retrieved current data is 'a'. */ BTreeCursor cursor = db.Cursor(); byte[] bytes = new byte[1]; bytes[0] = (byte)'a'; DatabaseEntry data = new DatabaseEntry(bytes, 0, 1); KeyValuePair<DatabaseEntry, DatabaseEntry> pair; while(cursor.MoveNext()) { cursor.Overwrite(data); Assert.IsTrue(cursor.Refresh()); pair = cursor.Current; Assert.AreEqual((byte)'a', pair.Value.Data[0]); } cursor.Close(); db.Close(); } private void PopulateDb(ref BTreeDatabase db) { if (db == null) { BTreeDatabaseConfig cfg = new BTreeDatabaseConfig(); cfg.Creation = CreatePolicy.IF_NEEDED; db = BTreeDatabase.Open( testHome + "/" + testName, cfg); } for (int i = 0; i < 100; i++) db.Put( new DatabaseEntry(BitConverter.GetBytes(i)), new DatabaseEntry(BitConverter.GetBytes(i))); } [Test] public void TestPriority() { CachePriority[] priorities; CursorConfig cursorConfig; testName = "TestPriority"; SetUpTest(true); cursorConfig = new CursorConfig(); priorities = new CachePriority[6]; priorities[0] = CachePriority.DEFAULT; priorities[1] = CachePriority.HIGH; priorities[2] = CachePriority.LOW; priorities[3] = CachePriority.VERY_HIGH; priorities[4] = CachePriority.VERY_LOW; priorities[5] = null; for (int i = 0; i < 6; i++) { if (priorities[i] != null) { cursorConfig.Priority = priorities[i]; Assert.AreEqual(priorities[i], cursorConfig.Priority); } GetCursorWithConfig(testHome + "/" + testName + ".db", DatabaseType.BTREE.ToString(), cursorConfig, DatabaseType.BTREE); GetCursorWithConfig(testHome + "/" + testName + ".db", DatabaseType.HASH.ToString(), cursorConfig, DatabaseType.HASH); GetCursorWithConfig(testHome + "/" + testName + ".db", DatabaseType.QUEUE.ToString(), cursorConfig, DatabaseType.QUEUE); GetCursorWithConfig(testHome + "/" + testName + ".db", DatabaseType.RECNO.ToString(), cursorConfig, DatabaseType.RECNO); } } private void GetCursorWithConfig(string dbFile, string dbName, CursorConfig cfg, DatabaseType type) { Database db; Cursor cursor; Configuration.ClearDir(testHome); if (type == DatabaseType.BTREE) { BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; db = BTreeDatabase.Open(dbFile, dbName, dbConfig); cursor = ((BTreeDatabase)db).Cursor(cfg); } else if (type == DatabaseType.HASH) { HashDatabaseConfig dbConfig = new HashDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; db = (HashDatabase)HashDatabase.Open(dbFile, dbName, dbConfig); cursor = ((HashDatabase)db).Cursor(cfg); } else if (type == DatabaseType.QUEUE) { QueueDatabaseConfig dbConfig = new QueueDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Length = 100; db = QueueDatabase.Open(dbFile, dbConfig); cursor = ((QueueDatabase)db).Cursor(cfg); } else if (type == DatabaseType.RECNO) { RecnoDatabaseConfig dbConfig = new RecnoDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; db = RecnoDatabase.Open(dbFile, dbName, dbConfig); cursor = ((RecnoDatabase)db).Cursor(cfg); } else throw new TestException(); if (cfg.Priority != null) Assert.AreEqual(cursor.Priority, cfg.Priority); else Assert.AreEqual(CachePriority.DEFAULT, cursor.Priority); Cursor dupCursor = cursor.Duplicate(false); Assert.AreEqual(cursor.Priority, dupCursor.Priority); cursor.Close(); db.Close(); } [Test] public void TestRefresh() { BTreeDatabase db; BTreeCursor cursor; DatabaseEnvironment env; Transaction txn; testName = "TestRefresh"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Write a record with cursor and Refresh the cursor. MoveCursorToCurrentRec(cursor, 1, 1, 2, 2, null); cursor.Dispose(); db.Dispose(); Configuration.ClearDir(testHome); GetCursorInBtreeDBInTDS(testHome, testName, null, out env, out db, out cursor, out txn); LockingInfo lockingInfo = new LockingInfo(); lockingInfo.IsolationDegree = Isolation.DEGREE_ONE; MoveCursorToCurrentRec(cursor, 1, 1, 2, 2, lockingInfo); cursor.Close(); txn.Commit(); db.Close(); env.Close(); } [Test] public void TestRefreshWithRMW() { testName = "TestRefreshWithRMW"; SetUpTest(true); cursorFunc = new CursorMoveFuncDelegate( MoveCursorToCurrentRec); // Read the previous unique record in write lock. MoveWithRMW(testHome, testName); } [Test] public void TestSnapshotIsolation() { BTreeDatabaseConfig dbConfig; DatabaseEntry key, data; DatabaseEnvironmentConfig envConfig; Thread readThread, updateThread; Transaction txn; updateTxn = null; readTxn = null; paramDB = null; paramEnv = null; testName = "TestSnapshotIsolation"; SetUpTest(true); /* * Open environment with DB_MULTIVERSION * which is required by DB_TXN_SNAPSHOT. */ envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseMVCC = true; envConfig.UseTxns = true; envConfig.UseMPool = true; envConfig.UseLocking = true; envConfig.TxnTimeout = 1000; paramEnv = DatabaseEnvironment.Open( testHome, envConfig); paramEnv.DetectDeadlocks(DeadlockPolicy.YOUNGEST); /* * Open a transactional database and put 1000 records * into it within transaction. */ txn = paramEnv.BeginTransaction(); dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.UseMVCC = true; dbConfig.Env = paramEnv; paramDB = BTreeDatabase.Open( testName + ".db", dbConfig, txn); for (int i = 0; i < 256; i++) { key = new DatabaseEntry( BitConverter.GetBytes(i)); data = new DatabaseEntry( BitConverter.GetBytes(i)); paramDB.Put(key, data, txn); } txn.Commit(); /* * Begin two threads, read and update thread. * The update thread runs a update transaction * using full read/write locking. The read thread * set DB_TXN_SNAPSHOT on read-only cursor. */ readThread = new Thread(new ThreadStart(ReadTxn)); updateThread = new Thread(new ThreadStart(UpdateTxn)); updateThread.Start(); Thread.Sleep(1000); readThread.Start(); readThread.Join(); updateThread.Join(); // Commit transacion in both two threads. if (updateTxn != null) updateTxn.Commit(); if (readTxn != null) readTxn.Commit(); /* * Confirm that the overwrite operation works. */ ConfirmOverwrite(); paramDB.Close(); paramEnv.Close(); } public void ReadTxn() { // Get a new transaction for reading the db. TransactionConfig txnConfig = new TransactionConfig(); txnConfig.Snapshot = true; readTxn = paramEnv.BeginTransaction( txnConfig); // Get a new cursor for putting record into db. CursorConfig cursorConfig = new CursorConfig(); cursorConfig.WriteCursor = false; BTreeCursor cursor = paramDB.Cursor( cursorConfig, readTxn); // Continually reading record from db. try { Assert.IsTrue(cursor.MoveFirst()); int i = 0; do { Assert.AreEqual( BitConverter.ToInt32( cursor.Current.Key.Data, 0), BitConverter.ToInt32( cursor.Current.Value.Data, 0)); } while (i <= 1000 && cursor.MoveNext()); } catch (DeadlockException) { } finally { cursor.Close(); } } public void UpdateTxn() { int int32Value; DatabaseEntry data; // Get a new transaction for updating the db. TransactionConfig txnConfig = new TransactionConfig(); txnConfig.IsolationDegree = Isolation.DEGREE_THREE; updateTxn = paramEnv.BeginTransaction(txnConfig); // Continually putting record to db. BTreeCursor cursor = paramDB.Cursor(updateTxn); // Move the cursor to the first record. Assert.IsTrue(cursor.MoveFirst()); int i = 0; try { do { int32Value = BitConverter.ToInt32( cursor.Current.Value.Data, 0); data = new DatabaseEntry( BitConverter.GetBytes(int32Value - 1)); cursor.Overwrite(data); } while (i <= 1000 && cursor.MoveNext()); } catch (DeadlockException) { } finally { cursor.Close(); } } [Test] public void TestWriteCursor() { BTreeCursor cursor; BTreeDatabase db; CursorConfig cursorConfig; DatabaseEnvironment env; testName = "TestWriteCursor"; SetUpTest(true); cursorConfig = new CursorConfig(); cursorConfig.WriteCursor = true; GetCursorInBtreeDBInCDS(testHome, testName, cursorConfig, out env, out db, out cursor); /* * Add a record by cursor to the database. If the * WriteCursor doesn't work, exception will be * throwed in the environment which is configured * with DB_INIT_CDB. */ try { AddOneByCursor(db, cursor); } catch (DatabaseException) { throw new TestException(); } finally { cursor.Close(); db.Close(); env.Close(); } } public void ConfirmOverwrite() { Transaction confirmTxn = paramEnv.BeginTransaction(); BTreeCursor cursor = paramDB.Cursor(confirmTxn); int i = 0; Assert.IsTrue(cursor.MoveFirst()); do { Assert.AreNotEqual( cursor.Current.Key.Data, cursor.Current.Value.Data); } while (i <= 1000 && cursor.MoveNext()); cursor.Close(); confirmTxn.Commit(); } public static void AddOneByCursor(Database db, Cursor cursor) { DatabaseEntry key, data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; // Add a record to db via cursor. key = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key")); data = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data")); pair = new KeyValuePair<DatabaseEntry,DatabaseEntry>(key, data); cursor.Add(pair); // Confirm that the record has been put to the database. Assert.IsTrue(db.Exists(key)); } public static void GetCursorInBtreeDBWithoutEnv( string home, string name, out BTreeDatabase db, out BTreeCursor cursor) { string dbFileName = home + "/" + name + ".db"; BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Duplicates = DuplicatesPolicy.UNSORTED; db = BTreeDatabase.Open(dbFileName, dbConfig); cursor = db.Cursor(); } public static void GetCursorInBtreeDBInTDS( string home, string name, CursorConfig cursorConfig, out DatabaseEnvironment env, out BTreeDatabase db, out BTreeCursor cursor, out Transaction txn) { string dbFileName = name + ".db"; Configuration.ClearDir(home); // Open an environment. DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseMPool = true; envConfig.UseTxns = true; envConfig.NoMMap = false; envConfig.UseLocking = true; env = DatabaseEnvironment.Open(home, envConfig); // Begin a transaction. txn = env.BeginTransaction(); /* * Open an btree database. The underlying database * should be opened with ReadUncommitted if the * cursor's isolation degree will be set to be 1. */ BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; if (cursorConfig != null && cursorConfig.IsolationDegree == Isolation.DEGREE_ONE) dbConfig.ReadUncommitted = true; db = BTreeDatabase.Open(dbFileName, dbConfig, txn); // Get a cursor in the transaction. if (cursorConfig != null) cursor = db.Cursor(cursorConfig, txn); else cursor = db.Cursor(txn); } public static void GetCursorInBtreeDB( string home, string name, CursorConfig cursorConfig, out DatabaseEnvironment env, out BTreeDatabase db, out BTreeCursor cursor) { string dbFileName = name + ".db"; Configuration.ClearDir(home); // Open an environment. DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseMPool = true; envConfig.UseTxns = true; envConfig.NoMMap = false; envConfig.UseLocking = true; env = DatabaseEnvironment.Open(home, envConfig); /* * Open an btree database. The underlying database * should be opened with ReadUncommitted if the * cursor's isolation degree will be set to be 1. */ BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; if (cursorConfig.IsolationDegree == Isolation.DEGREE_ONE) dbConfig.ReadUncommitted = true; db = BTreeDatabase.Open(dbFileName, dbConfig, null); // Get a cursor in the transaction. cursor = db.Cursor(cursorConfig, null); } // Get a cursor in CDS. public static void GetCursorInBtreeDBInCDS( string home, string name, CursorConfig cursorConfig, out DatabaseEnvironment env, out BTreeDatabase db, out BTreeCursor cursor) { string dbFileName = name + ".db"; Configuration.ClearDir(home); // Open an environment. DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseCDB = true; envConfig.UseMPool = true; env = DatabaseEnvironment.Open(home, envConfig); /* * Open an btree database. The underlying database * should be opened with ReadUncommitted if the * cursor's isolation degree will be set to be 1. */ BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; if (cursorConfig.IsolationDegree == Isolation.DEGREE_ONE) dbConfig.ReadUncommitted = true; db = BTreeDatabase.Open(dbFileName, dbConfig); // Get a cursor in the transaction. cursor = db.Cursor(cursorConfig); } public void RdMfWt() { Transaction txn = paramEnv.BeginTransaction(); Cursor dbc = paramDB.Cursor(txn); try { LockingInfo lck = new LockingInfo(); lck.ReadModifyWrite = true; // Read record. cursorFunc(dbc, 1, 1, 2, 2, lck); // Block the current thread until event is set. signal.WaitOne(); // Write new records into database. DatabaseEntry key = new DatabaseEntry( BitConverter.GetBytes(55)); DatabaseEntry data = new DatabaseEntry( BitConverter.GetBytes(55)); dbc.Add(new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data)); dbc.Close(); txn.Commit(); } catch (DeadlockException) { dbc.Close(); txn.Abort(); } } public void MoveWithRMW(string home, string name) { paramEnv = null; paramDB = null; // Open the environment. DatabaseEnvironmentConfig envCfg = new DatabaseEnvironmentConfig(); envCfg.Create = true; envCfg.FreeThreaded = true; envCfg.UseLocking = true; envCfg.UseLogging = true; envCfg.UseMPool = true; envCfg.UseTxns = true; paramEnv = DatabaseEnvironment.Open(home, envCfg); // Open database in transaction. Transaction openTxn = paramEnv.BeginTransaction(); BTreeDatabaseConfig cfg = new BTreeDatabaseConfig(); cfg.Creation = CreatePolicy.ALWAYS; cfg.Env = paramEnv; cfg.FreeThreaded = true; cfg.PageSize = 4096; cfg.Duplicates = DuplicatesPolicy.UNSORTED; paramDB = BTreeDatabase.Open(name + ".db", cfg, openTxn); openTxn.Commit(); /* * Put 10 different, 2 duplicate and another different * records into database. */ Transaction txn = paramEnv.BeginTransaction(); for (int i = 0; i < 14; i++) { DatabaseEntry key, data; if (i == 10 || i == 11 || i == 12) { key = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")); data = new DatabaseEntry( BitConverter.GetBytes(i)); } else { key = new DatabaseEntry( BitConverter.GetBytes(i)); data = new DatabaseEntry( BitConverter.GetBytes(i)); } paramDB.Put(key, data, txn); } txn.Commit(); // Get a event wait handle. signal = new EventWaitHandle(false, EventResetMode.ManualReset); /* * Start RdMfWt() in two threads. RdMfWt() reads * and writes data into database. */ Thread t1 = new Thread(new ThreadStart(RdMfWt)); Thread t2 = new Thread(new ThreadStart(RdMfWt)); t1.Start(); t2.Start(); /* * Give both threads time to read before signalling * them to write. */ Thread.Sleep(1000); // Invoke the write operation in both threads. signal.Set(); // Return the number of deadlocks. while (t1.IsAlive || t2.IsAlive) { /* * Give both threads time to write before * counting the number of deadlocks. */ Thread.Sleep(1000); uint deadlocks = paramEnv.DetectDeadlocks( DeadlockPolicy.DEFAULT); // Confirm that there won't be any deadlock. Assert.AreEqual(0, deadlocks); } t1.Join(); t2.Join(); paramDB.Close(); paramEnv.Close(); } /* * Move the cursor to an exisiting key and key/data * pair with LockingInfo. */ public void MoveCursor(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { DatabaseEntry key, data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; key = new DatabaseEntry( BitConverter.GetBytes((int)0)); data = new DatabaseEntry( BitConverter.GetBytes((int)0)); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); if (lck == null) { // Move to an existing key. Assert.IsTrue(dbc.Move(key, true)); // Move to an existing key/data pair. Assert.IsTrue(dbc.Move(pair, true)); /* Move to an existing key, and return * partial data. */ data = new DatabaseEntry(dOffset, dLen); Assert.IsTrue(dbc.Move(key, data, true)); CheckPartial(null, 0, 0, dbc.Current.Value, dOffset, dLen); // Partially key match. byte[] partbytes = new byte[kLen]; for (int i = 0; i < kLen; i++) partbytes[i] = BitConverter.GetBytes( (int)1)[kOffset + i]; key = new DatabaseEntry(partbytes, kOffset, kLen); Assert.IsTrue(dbc.Move(key, false)); Assert.AreEqual(kLen, dbc.Current.Key.Data.Length); CheckPartial(dbc.Current.Key, kOffset, kLen, null, 0, 0); } else { // Move to an existing key. Assert.IsTrue(dbc.Move(key, true, lck)); // Move to an existing key/data pair. Assert.IsTrue(dbc.Move(pair, true, lck)); /* * Move to an existing key, and return * partial data. */ data = new DatabaseEntry(dOffset, dLen); Assert.IsTrue(dbc.Move(key, data, true, lck)); CheckPartial(null, 0, 0, dbc.Current.Value, dOffset, dLen); // Partially key match. byte[] partbytes = new byte[kLen]; for (int i = 0; i < kLen; i++) partbytes[i] = BitConverter.GetBytes( (int)1)[kOffset + i]; key = new DatabaseEntry(partbytes, kOffset, kLen); Assert.IsTrue(dbc.Move(key, false, lck)); Assert.AreEqual(kLen, dbc.Current.Key.Data.Length); CheckPartial(dbc.Current.Key, kOffset, kLen, null, 0, 0); } } /* * Move the cursor to the first record in a nonempty * database. The returning value should be true. */ public void MoveCursorToFirst(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { DatabaseEntry key = new DatabaseEntry(kOffset, kLen); DatabaseEntry data = new DatabaseEntry(dOffset, dLen); if (lck == null) { Assert.IsTrue(dbc.MoveFirst()); Assert.IsTrue(dbc.MoveFirst(key, data)); } else { Assert.IsTrue(dbc.MoveFirst(lck)); Assert.IsTrue(dbc.MoveFirst(key, data, lck)); } CheckPartial(dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } /* * Move the cursor to last record in a nonempty * database. The returning value should be true. */ public void MoveCursorToLast(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { DatabaseEntry key = new DatabaseEntry(kOffset, kLen); DatabaseEntry data = new DatabaseEntry(dOffset, dLen); if (lck == null) { Assert.IsTrue(dbc.MoveLast()); Assert.IsTrue(dbc.MoveLast(key, data)); } else { Assert.IsTrue(dbc.MoveLast(lck)); Assert.IsTrue(dbc.MoveLast(key, data, lck)); } CheckPartial(dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } /* * Move the cursor to the next record in the database * with more than five records. The returning values of * every move operation should be true. */ public void MoveCursorToNext(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { DatabaseEntry key = new DatabaseEntry(kOffset, kLen); DatabaseEntry data = new DatabaseEntry(dOffset, dLen); for (int i = 0; i < 5; i++) { if (lck == null) { Assert.IsTrue(dbc.MoveNext()); Assert.IsTrue(dbc.MoveNext(key, data)); } else { Assert.IsTrue(dbc.MoveNext(lck)); Assert.IsTrue( dbc.MoveNext(key, data, lck)); } CheckPartial(dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } } /* * Move the cursor to the next duplicate record in * the database which has more than 2 duplicate * records. The returning value should be true. */ public void MoveCursorToNextDuplicate(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { DatabaseEntry key = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")); /* * The cursor should point to any record in the * database before it move to the next duplicate * record. */ if (lck == null) { dbc.Move(key, true); Assert.IsTrue(dbc.MoveNextDuplicate()); Assert.IsTrue(dbc.MoveNextDuplicate( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen))); } else { /* * Both the move and move next duplicate * operation should use LockingInfo. If any * one doesn't use LockingInfo, deadlock still * occurs. */ dbc.Move(key, true, lck); Assert.IsTrue(dbc.MoveNextDuplicate(lck)); Assert.IsTrue(dbc.MoveNextDuplicate( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen), lck)); } } /* * Move the cursor to next unique record in the database. * The returning value should be true. */ public void MoveCursorToNextUnique(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { for (int i = 0; i < 5; i++) { if (lck == null) { Assert.IsTrue(dbc.MoveNextUnique()); Assert.IsTrue(dbc.MoveNextUnique( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen))); } else { Assert.IsTrue(dbc.MoveNextUnique(lck)); Assert.IsTrue(dbc.MoveNextUnique( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen), lck)); } CheckPartial(dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } } /* * Move the cursor to previous record in the database. * The returning value should be true; */ public void MoveCursorToPrev(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { if (lck == null) { dbc.MoveLast(); for (int i = 0; i < 5; i++) { Assert.IsTrue(dbc.MovePrev()); dbc.MoveNext(); Assert.IsTrue(dbc.MovePrev( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen))); CheckPartial( dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } } else { dbc.MoveLast(lck); for (int i = 0; i < 5; i++) { Assert.IsTrue(dbc.MovePrev(lck)); dbc.MoveNext(); Assert.IsTrue(dbc.MovePrev( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen), lck)); CheckPartial( dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } } } /* * Move the cursor to a duplicate record and then to * another duplicate one. And finally move to it previous * one. Since the previous duplicate one exist, the return * value of move previous duplicate record should be * true; */ public void MoveCursorToPrevDuplicate(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { if (lck == null) { dbc.Move(new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")), true); dbc.MoveNextDuplicate(); Assert.IsTrue(dbc.MovePrevDuplicate()); dbc.Move(new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")), true); dbc.MoveNextDuplicate(); Assert.IsTrue(dbc.MovePrevDuplicate( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen))); } else { dbc.Move(new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")), true, lck); dbc.MoveNextDuplicate(lck); Assert.IsTrue(dbc.MovePrevDuplicate(lck)); dbc.Move(new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")), true, lck); dbc.MoveNextDuplicate(lck); Assert.IsTrue(dbc.MovePrevDuplicate( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen), lck)); } CheckPartial(dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } /* * Move the cursor to previous unique record in a * database with more than 2 records. The returning * value should be true. */ public void MoveCursorToPrevUnique(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { DatabaseEntry key = new DatabaseEntry(kOffset, kLen); DatabaseEntry data = new DatabaseEntry(dOffset, dLen); for (int i = 0; i < 5; i++) { if (lck == null) { Assert.IsTrue(dbc.MovePrevUnique()); Assert.IsTrue( dbc.MovePrevUnique(key, data)); } else { Assert.IsTrue(dbc.MovePrevUnique(lck)); Assert.IsTrue( dbc.MovePrevUnique(key, data, lck)); } CheckPartial(dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } } /* * Move the cursor to current existing record. The returning * value should be true. */ public void MoveCursorToCurrentRec(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { DatabaseEntry key, data; // Add a record to the database. KeyValuePair<DatabaseEntry, DatabaseEntry> pair; key = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")); data = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("data")); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); dbc.Add(pair); if (lck == null) Assert.IsTrue(dbc.Refresh()); else Assert.IsTrue(dbc.Refresh(lck)); Assert.AreEqual(key.Data, dbc.Current.Key.Data); Assert.AreEqual(data.Data, dbc.Current.Value.Data); key = new DatabaseEntry(kOffset, kLen); data = new DatabaseEntry(dOffset, dLen); if (lck == null) Assert.IsTrue(dbc.Refresh(key, data)); else Assert.IsTrue(dbc.Refresh(key, data, lck)); CheckPartial(dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } public void CheckPartial( DatabaseEntry key, uint kOffset, uint kLen, DatabaseEntry data, uint dOffset, uint dLen) { if (key != null) { Assert.IsTrue(key.Partial); Assert.AreEqual(kOffset, key.PartialOffset); Assert.AreEqual(kLen, key.PartialLen); Assert.AreEqual(kLen, (uint)key.Data.Length); } if (data != null) { Assert.IsTrue(data.Partial); Assert.AreEqual(dOffset, data.PartialOffset); Assert.AreEqual(dLen, data.PartialLen); Assert.AreEqual(dLen, (uint)data.Data.Length); } } } }
// HtmlHelp.cs - helper class to create HTML Help compiler files // Copyright (C) 2001 Kral Ferch, Jason Diamond // // 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 using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Reflection; using System.Xml; using System.Globalization; using Microsoft.Win32; using NDoc.Core; namespace NDoc.Documenter.Msdn2 { /// <summary>HTML Help file utilities.</summary> /// <remarks>This class is used by the MsdnHelp documenter /// to create the files needed by the HTML Help compiler.</remarks> public class HtmlHelp { private string _directoryName = null; private string _projectName = null; private string _defaultTopic = null; private string _htmlHelpCompiler = null; private bool _includeFavorites = false; private bool _binaryTOC = false; private short _langID=1033; private bool _generateTocOnly; private StreamWriter streamHtmlHelp = null; private ArrayList _tocFiles = new ArrayList(); private XmlTextWriter tocWriter; /// <summary>Initializes a new instance of the HtmlHelp class.</summary> /// <param name="directoryName">The directory to write the HTML Help files to.</param> /// <param name="projectName">The name of the HTML Help project.</param> /// <param name="defaultTopic">The default topic for the compiled HTML Help file.</param> /// <param name="generateTocOnly">When true, HtmlHelp only outputs the HHC file and does not compile the CHM.</param> public HtmlHelp( string directoryName, string projectName, string defaultTopic, bool generateTocOnly) { _directoryName = directoryName; _projectName = projectName; _defaultTopic = defaultTopic; _generateTocOnly = generateTocOnly; } /// <summary>Gets the directory name containing the HTML Help files.</summary> public string DirectoryName { get { return _directoryName; } } /// <summary>Gets the HTML Help project name.</summary> public string ProjectName { get { return _projectName; } } /// <summary>Gets or sets the IncludeFavorites property.</summary> /// <remarks> /// Setting this to <see langword="true" /> will include the "favorites" /// tab in the compiled HTML Help file. /// </remarks> public bool IncludeFavorites { get { return _includeFavorites; } set { _includeFavorites = value; } } /// <summary>Gets or sets the BinaryTOC property.</summary> /// <remarks> /// Setting this to <see langword="true" /> will force the compiler /// to create a binary TOC in the chm file. /// </remarks> public bool BinaryTOC { get { return _binaryTOC; } set { _binaryTOC = value; } } /// <summary> /// /// </summary> public short LangID { get { return _langID; } set { _langID = value; } } /// <summary>Gets or sets the DefaultTopic property.</summary> public string DefaultTopic { get { return _defaultTopic; } set { _defaultTopic = value; } } /// <summary>Gets the path to the Html Help Compiler.</summary> /// <exception cref="PlatformNotSupportedException">NDoc is running on unix.</exception> internal string HtmlHelpCompiler { get { if ((int) Environment.OSVersion.Platform == 128) { throw new PlatformNotSupportedException( "The HTML Help Compiler is not supported on unix."); } if (_htmlHelpCompiler != null && File.Exists(_htmlHelpCompiler)) { return _htmlHelpCompiler; } //try the default Html Help Workshop installation directory _htmlHelpCompiler = Path.Combine( Environment.GetFolderPath( Environment.SpecialFolder.ProgramFiles), @"HTML Help Workshop\hhc.exe"); if (File.Exists(_htmlHelpCompiler)) { return _htmlHelpCompiler; } //not in default dir, try to locate it from the registry RegistryKey key = Registry.ClassesRoot.OpenSubKey("hhc.file"); if (key != null) { key = key.OpenSubKey("DefaultIcon"); if (key != null) { object val = key.GetValue(null); if (val != null) { string hhw = (string)val; if (hhw.Length > 0) { hhw = hhw.Split(new Char[] {','})[0]; hhw = Path.GetDirectoryName(hhw); _htmlHelpCompiler = Path.Combine(hhw, "hhc.exe"); } } } } if (File.Exists(_htmlHelpCompiler)) { return _htmlHelpCompiler; } // we still can't find the compiler, see if a location is stored in the machine settings file Settings settings = new Settings( Settings.MachineSettingsFile ); string path = settings.GetSetting( "compilers", "htmlHelpWorkshopLocation", "" ); if ( path.Length > 0 ) { _htmlHelpCompiler = Path.Combine(path, "hhc.exe"); if (File.Exists(_htmlHelpCompiler)) { return _htmlHelpCompiler; } } //still not finding the compiler, give up throw new DocumenterException( "Unable to find the HTML Help Compiler. Please verify that" + " the HTML Help Workshop has been installed."); } } private string GetContentsFilename() { return (_tocFiles.Count > 0) ? (string)_tocFiles[0] : string.Empty; } private string GetIndexFilename() { return _projectName + ".hhk"; } private string GetLogFilename() { return _projectName + ".log"; } private string GetCompiledHtmlFilename() { return _projectName + ".chm"; } /// <summary>Gets the path the the HHP file.</summary> public string GetPathToProjectFile() { return Path.Combine(_directoryName, _projectName) + ".hhp"; } /// <summary>Gets the path the the HHC file.</summary> public string GetPathToContentsFile() { return Path.Combine(_directoryName, GetContentsFilename()); } /// <summary>Gets the path the the HHK file.</summary> public string GetPathToIndexFile() { return Path.Combine(_directoryName, _projectName) + ".hhk"; } /// <summary>Gets the path the the LOG file.</summary> public string GetPathToLogFile() { return Path.Combine(_directoryName, _projectName) + ".log"; } /// <summary>Gets the path the the CHM file.</summary> /// <returns>The path to the CHM file.</returns> public string GetPathToCompiledHtmlFile() { return Path.Combine(_directoryName, _projectName) + ".chm"; } /// <summary>Opens an HTML Help project file for writing.</summary> public void OpenProjectFile() { if (_generateTocOnly) return; streamHtmlHelp = new StreamWriter(File.Open(GetPathToProjectFile(), FileMode.Create), System.Text.Encoding.Default); streamHtmlHelp.WriteLine("[FILES]"); } /// <summary>Adds a file to the HTML Help project file.</summary> /// <param name="filename">The filename to add.</param> public void AddFileToProject(string filename) { if (_generateTocOnly) return; streamHtmlHelp.WriteLine(filename); } /// <summary>Closes the HTML Help project file.</summary> public void CloseProjectFile() { if (_generateTocOnly) return; string options; if (_includeFavorites) { options = "0x63520,220"; } else { options = "0x62520,220"; } if (_defaultTopic.Length > 0) { options += ",0x387e,[86,51,872,558],,,,,,,0"; } else { options += ",0x383e,[86,51,872,558],,,,,,,0"; } streamHtmlHelp.WriteLine(); streamHtmlHelp.WriteLine("[OPTIONS]"); streamHtmlHelp.WriteLine("Title=" + _projectName); streamHtmlHelp.WriteLine("Auto Index=Yes"); if (_binaryTOC) streamHtmlHelp.WriteLine("Binary TOC=Yes"); streamHtmlHelp.WriteLine("Compatibility=1.1 or later"); streamHtmlHelp.WriteLine("Compiled file=" + GetCompiledHtmlFilename()); streamHtmlHelp.WriteLine("Default Window=MsdnHelp"); streamHtmlHelp.WriteLine("Default topic=" + _defaultTopic); streamHtmlHelp.WriteLine("Display compile progress=No"); streamHtmlHelp.WriteLine("Error log file=" + GetLogFilename()); streamHtmlHelp.WriteLine("Full-text search=Yes"); streamHtmlHelp.WriteLine("Index file=" + GetIndexFilename()); CultureInfo ci = new CultureInfo(_langID); string LangIDString = "Language=0x" + _langID.ToString("x") + " " + ci.DisplayName; streamHtmlHelp.WriteLine(LangIDString); foreach( string tocFile in _tocFiles ) { streamHtmlHelp.WriteLine("Contents file=" + tocFile); } streamHtmlHelp.WriteLine(); streamHtmlHelp.WriteLine("[WINDOWS]"); streamHtmlHelp.WriteLine("MsdnHelp=\"" + _projectName + " Help\",\"" + GetContentsFilename() + "\",\"" + GetIndexFilename() + "\",\"" + _defaultTopic + "\",\"" + _defaultTopic + "\",,,,," + options); streamHtmlHelp.WriteLine(); streamHtmlHelp.WriteLine("[INFOTYPES]"); streamHtmlHelp.Close(); } /// <summary>Opens a HTML Help contents file for writing.</summary> public void OpenContentsFile(string tocName, bool isDefault) { // TODO: we would need a more robust way of maintaining the list // of tocs that have been opened... if (tocName == string.Empty) { tocName = _projectName; } if (!tocName.EndsWith(".hhc")) { tocName += ".hhc"; } if (isDefault) { _tocFiles.Insert(0, tocName); } else { _tocFiles.Add( tocName ); } // Create the table of contents writer. This can't use // indenting because the HTML Help Compiler doesn't like // newlines between the <LI> and <Object> tags. tocWriter = new XmlTextWriter(Path.Combine(_directoryName, tocName), System.Text.Encoding.Default ); // these formatting options cannot be used, because they make the // Html Help Compiler hang. // tocWriter.Formatting = Formatting.Indented; // tocWriter.IndentChar = '\t'; // tocWriter.Indentation = 1; // We don't call WriteStartDocument because that outputs // the XML declaration which the HTML Help Compiler doesn't like. tocWriter.WriteComment("This document contains Table of Contents information for the HtmlHelp compiler."); tocWriter.WriteStartElement("UL"); } /// <summary>Creates a new "book" in the HTML Help contents file.</summary> public void OpenBookInContents() { tocWriter.WriteStartElement("UL"); } /// <summary>Adds a topic to the contents file.</summary> /// <param name="headingName">The name as it should appear in the contents.</param> /// <remarks>Adds a topic node with no URL associated with the node into the /// table of contents.</remarks> public void AddFileToContents(string headingName) { tocWriter.WriteStartElement("LI"); tocWriter.WriteStartElement("OBJECT"); tocWriter.WriteAttributeString("type", "text/sitemap"); tocWriter.WriteStartElement("param"); tocWriter.WriteAttributeString("name", "Name"); tocWriter.WriteAttributeString("value", headingName.Replace('$', '.')); tocWriter.WriteEndElement(); // param tocWriter.WriteEndElement(); // OBJECT tocWriter.WriteEndElement(); // LI } /// <summary>Adds a topic to the contents file.</summary> /// <param name="headingName">The name as it should appear in the contents.</param> /// <remarks>Adds a topic node with no URL associated with the node into the /// table of contents.</remarks> /// <param name="icon">The image for this entry.</param> public void AddFileToContents(string headingName, HtmlHelpIcon icon) { tocWriter.WriteStartElement("LI"); tocWriter.WriteStartElement("OBJECT"); tocWriter.WriteAttributeString("type", "text/sitemap"); tocWriter.WriteStartElement("param"); tocWriter.WriteAttributeString("name", "Name"); tocWriter.WriteAttributeString("value", headingName.Replace('$', '.')); tocWriter.WriteEndElement(); // param tocWriter.WriteStartElement("param"); tocWriter.WriteAttributeString("name", "ImageNumber"); tocWriter.WriteAttributeString("value", ((int)icon).ToString()); tocWriter.WriteEndElement(); // param tocWriter.WriteEndElement(); // OBJECT tocWriter.WriteEndElement(); // LI } /// <summary>Adds a file to the contents file.</summary> /// <param name="headingName">The name as it should appear in the contents.</param> /// <param name="htmlFilename">The filename for this entry.</param> public void AddFileToContents(string headingName, string htmlFilename) { tocWriter.WriteStartElement("LI"); tocWriter.WriteStartElement("OBJECT"); tocWriter.WriteAttributeString("type", "text/sitemap"); tocWriter.WriteStartElement("param"); tocWriter.WriteAttributeString("name", "Name"); tocWriter.WriteAttributeString("value", headingName.Replace('$', '.')); tocWriter.WriteEndElement(); tocWriter.WriteStartElement("param"); tocWriter.WriteAttributeString("name", "Local"); tocWriter.WriteAttributeString("value", htmlFilename); tocWriter.WriteEndElement(); tocWriter.WriteEndElement(); tocWriter.WriteEndElement(); } /// <summary>Adds a file to the contents file.</summary> /// <param name="headingName">The name as it should appear in the contents.</param> /// <param name="htmlFilename">The filename for this entry.</param> /// <param name="icon">The image for this entry.</param> public void AddFileToContents(string headingName, string htmlFilename, HtmlHelpIcon icon) { tocWriter.WriteStartElement("LI"); tocWriter.WriteStartElement("OBJECT"); tocWriter.WriteAttributeString("type", "text/sitemap"); tocWriter.WriteStartElement("param"); tocWriter.WriteAttributeString("name", "Name"); tocWriter.WriteAttributeString("value", headingName.Replace('$', '.')); tocWriter.WriteEndElement(); tocWriter.WriteStartElement("param"); tocWriter.WriteAttributeString("name", "Local"); tocWriter.WriteAttributeString("value", htmlFilename); tocWriter.WriteEndElement(); tocWriter.WriteStartElement("param"); tocWriter.WriteAttributeString("name", "ImageNumber"); tocWriter.WriteAttributeString("value", ((int)icon).ToString()); tocWriter.WriteEndElement(); tocWriter.WriteEndElement(); tocWriter.WriteEndElement(); } /// <summary>Closes the last opened "book" in the contents file.</summary> public void CloseBookInContents() { tocWriter.WriteEndElement(); } /// <summary>Closes the contents file.</summary> public void CloseContentsFile() { tocWriter.WriteEndElement(); tocWriter.Close(); } /// <summary>Writes an empty index file.</summary> /// <remarks>The HTML Help Compiler will complain if this file doesn't exist.</remarks> public void WriteEmptyIndexFile() { if (_generateTocOnly) return; // Create an empty index file to avoid compilation errors. XmlTextWriter indexWriter = new XmlTextWriter(GetPathToIndexFile(), null); // Don't call WriteStartDocument to avoid XML declaration. indexWriter.WriteStartElement("HTML"); indexWriter.WriteStartElement("BODY"); indexWriter.WriteComment(" http://ndoc.sourceforge.net/ "); indexWriter.WriteEndElement(); indexWriter.WriteEndElement(); // Don't call WriteEndDocument since we didn't call WriteStartDocument. indexWriter.Close(); } /// <summary>Compiles the HTML Help project.</summary> public void CompileProject() { if (_generateTocOnly) return; Process helpCompileProcess = new Process(); try { try { string path = GetPathToCompiledHtmlFile(); if (File.Exists(path)) { File.Delete(path); } } catch (Exception e) { throw new DocumenterException("The compiled HTML Help file is probably open.", e); } ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.FileName = HtmlHelpCompiler; processStartInfo.Arguments = "\"" + Path.GetFullPath(GetPathToProjectFile()) + "\""; processStartInfo.ErrorDialog = false; processStartInfo.WorkingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); processStartInfo.WindowStyle = ProcessWindowStyle.Hidden; processStartInfo.UseShellExecute = false; processStartInfo.CreateNoWindow = true; processStartInfo.RedirectStandardError = false; //no point redirecting as HHC does not use stdErr processStartInfo.RedirectStandardOutput = true; helpCompileProcess.StartInfo = processStartInfo; // Start the help compile and bail if it takes longer than 10 minutes. Trace.WriteLine( "Compiling Html Help file" ); string stdOut = ""; try { helpCompileProcess.Start(); // Read the standard output of the spawned process. stdOut = helpCompileProcess.StandardOutput.ReadToEnd(); // compiler std out includes a bunch of unneccessary line feeds + new lines // remplace all the line feed and keep the new lines stdOut = stdOut.Replace( "\r", "" ); } catch (Exception e) { string msg = String.Format("The HTML Help compiler '{0}' was not found.", HtmlHelpCompiler); throw new DocumenterException(msg, e); } helpCompileProcess.WaitForExit(); // if (!helpCompileProcess.WaitForExit(600000)) // { // throw new DocumenterException("Compile did not complete after 10 minutes and was aborted"); // } // Errors return 0 (success or warnings returns 1) if (helpCompileProcess.ExitCode == 0) { string ErrMsg = "The Help compiler reported errors"; if (!File.Exists(GetPathToCompiledHtmlFile())) { ErrMsg += " - The CHM file was not been created."; } throw new DocumenterException(ErrMsg + "\n\n" + stdOut); } else { Trace.WriteLine(stdOut); } Trace.WriteLine( "Html Help compile complete" ); } finally { helpCompileProcess.Close(); } } } /// <summary> /// HtmlHelp v1 TOC icons /// </summary> public enum HtmlHelpIcon { /// <summary> /// Contents Book /// </summary> Book=1, /// <summary> /// Contents Folder /// </summary> Folder=5, /// <summary> /// Page with Question Mark /// </summary> Question=9, /// <summary> /// Standard Blank Page /// </summary> Page=11, /// <summary> /// World /// </summary> World=13, /// <summary> /// World w IE icon /// </summary> WorldInternetExplorer=15, /// <summary> /// Information /// </summary> Information=17, /// <summary> /// Shortcut /// </summary> Shortcut=19, /// <summary> /// BookPage /// </summary> BookPage=21, /// <summary> /// Envelope /// </summary> Envelope=23, /// <summary> /// Person /// </summary> Person=27, /// <summary> /// Sound /// </summary> Sound=29, /// <summary> /// Disc /// </summary> Disc=31, /// <summary> /// Video /// </summary> Video=33, /// <summary> /// Steps /// </summary> Steps=35, /// <summary> /// LightBulb /// </summary> LightBulb=37, /// <summary> /// Pencil /// </summary> Pencil=39, /// <summary> /// Tool /// </summary> Tool=41 } }
using System; using System.Linq; using UnityEditor; using UnityEditor.AnimatedValues; using UnityEngine; using UnityWeld.Binding; using UnityWeld.Binding.Internal; namespace UnityWeld_Editor { [CustomEditor(typeof(TwoWayPropertyBinding))] class TwoWayPropertyBindingEditor : BaseBindingEditor { private TwoWayPropertyBinding targetScript; private AnimBool viewAdapterOptionsFade; private AnimBool viewModelAdapterOptionsFade; private AnimBool exceptionAdapterOptionsFade; // Whether properties in the target script differ from the value in the prefab. // Needed to know which ones to display as bold in the inspector. private bool viewEventPrefabModified; private bool viewPropertyPrefabModified; private bool viewAdapterPrefabModified; private bool viewAdapterOptionsPrefabModified; private bool viewModelPropertyPrefabModified; private bool viewModelAdapterPrefabModified; private bool viewModelAdapterOptionsPrefabModified; private bool exceptionPropertyPrefabModified; private bool exceptionAdapterPrefabModified; private bool exceptionAdapterOptionsPrefabModified; private void OnEnable() { targetScript = (TwoWayPropertyBinding)target; Type adapterType; viewAdapterOptionsFade = new AnimBool(ShouldShowAdapterOptions( targetScript.ViewAdapterTypeName, out adapterType )); viewModelAdapterOptionsFade = new AnimBool(ShouldShowAdapterOptions( targetScript.ViewModelAdapterTypeName, out adapterType )); exceptionAdapterOptionsFade = new AnimBool(ShouldShowAdapterOptions( targetScript.ExceptionAdapterTypeName, out adapterType )); viewAdapterOptionsFade.valueChanged.AddListener(Repaint); viewModelAdapterOptionsFade.valueChanged.AddListener(Repaint); exceptionAdapterOptionsFade.valueChanged.AddListener(Repaint); } private void OnDisable() { viewAdapterOptionsFade.valueChanged.RemoveListener(Repaint); viewModelAdapterOptionsFade.valueChanged.RemoveListener(Repaint); exceptionAdapterOptionsFade.valueChanged.RemoveListener(Repaint); } public override void OnInspectorGUI() { if (CannotModifyInPlayMode()) { GUI.enabled = false; } UpdatePrefabModifiedProperties(); var defaultLabelStyle = EditorStyles.label.fontStyle; EditorStyles.label.fontStyle = viewEventPrefabModified ? FontStyle.Bold : defaultLabelStyle; ShowEventMenu( UnityEventWatcher.GetBindableEvents(targetScript.gameObject) .OrderBy(evt => evt.Name) .ToArray(), updatedValue => targetScript.ViewEventName = updatedValue, targetScript.ViewEventName ); EditorStyles.label.fontStyle = viewPropertyPrefabModified ? FontStyle.Bold : defaultLabelStyle; Type viewPropertyType; ShowViewPropertyMenu( new GUIContent("View property", "Property on the view to bind to"), PropertyFinder.GetBindableProperties(targetScript.gameObject) .OrderBy(prop => prop.ViewModelTypeName) .ThenBy(prop => prop.MemberName) .ToArray(), updatedValue => targetScript.ViewPropertName = updatedValue, targetScript.ViewPropertName, out viewPropertyType ); // Don't let the user set other options until they've set the event and view property. var guiPreviouslyEnabled = GUI.enabled; if (string.IsNullOrEmpty(targetScript.ViewEventName) || string.IsNullOrEmpty(targetScript.ViewPropertName)) { GUI.enabled = false; } var viewAdapterTypeNames = GetAdapterTypeNames( type => viewPropertyType == null || TypeResolver.IsTypeCastableTo(TypeResolver.FindAdapterAttribute(type).OutputType, viewPropertyType) ); EditorStyles.label.fontStyle = viewAdapterPrefabModified ? FontStyle.Bold : defaultLabelStyle; ShowAdapterMenu( new GUIContent( "View adapter", "Adapter that converts values sent from the view-model to the view." ), viewAdapterTypeNames, targetScript.ViewAdapterTypeName, newValue => { // Get rid of old adapter options if we changed the type of the adapter. if (newValue != targetScript.ViewAdapterTypeName) { Undo.RecordObject(targetScript, "Set view adapter options"); targetScript.ViewAdapterOptions = null; } UpdateProperty( updatedValue => targetScript.ViewAdapterTypeName = updatedValue, targetScript.ViewAdapterTypeName, newValue, "Set view adapter" ); } ); EditorStyles.label.fontStyle = viewAdapterOptionsPrefabModified ? FontStyle.Bold : defaultLabelStyle; Type viewAdapterType; viewAdapterOptionsFade.target = ShouldShowAdapterOptions( targetScript.ViewAdapterTypeName, out viewAdapterType ); ShowAdapterOptionsMenu( "View adapter options", viewAdapterType, options => targetScript.ViewAdapterOptions = options, targetScript.ViewAdapterOptions, viewAdapterOptionsFade.faded ); EditorGUILayout.Space(); EditorStyles.label.fontStyle = viewModelPropertyPrefabModified ? FontStyle.Bold : defaultLabelStyle; var adaptedViewPropertyType = AdaptTypeBackward( viewPropertyType, targetScript.ViewAdapterTypeName ); ShowViewModelPropertyMenu( new GUIContent( "View-model property", "Property on the view-model to bind to." ), TypeResolver.FindBindableProperties(targetScript), updatedValue => targetScript.ViewModelPropertyName = updatedValue, targetScript.ViewModelPropertyName, prop => TypeResolver.IsTypeCastableTo(prop.PropertyType, adaptedViewPropertyType) ); var viewModelAdapterTypeNames = GetAdapterTypeNames( type => adaptedViewPropertyType == null || TypeResolver.IsTypeCastableTo(adaptedViewPropertyType, TypeResolver.FindAdapterAttribute(type).OutputType) ); EditorStyles.label.fontStyle = viewModelAdapterPrefabModified ? FontStyle.Bold : defaultLabelStyle; ShowAdapterMenu( new GUIContent( "View-model adapter", "Adapter that converts from the view back to the view-model" ), viewModelAdapterTypeNames, targetScript.ViewModelAdapterTypeName, newValue => { if (newValue != targetScript.ViewModelAdapterTypeName) { Undo.RecordObject(targetScript, "Set view-model adapter options"); targetScript.ViewModelAdapterOptions = null; } UpdateProperty( updatedValue => targetScript.ViewModelAdapterTypeName = updatedValue, targetScript.ViewModelAdapterTypeName, newValue, "Set view-model adapter" ); } ); EditorStyles.label.fontStyle = viewModelAdapterOptionsPrefabModified ? FontStyle.Bold : defaultLabelStyle; Type viewModelAdapterType; viewModelAdapterOptionsFade.target = ShouldShowAdapterOptions( targetScript.ViewModelAdapterTypeName, out viewModelAdapterType ); ShowAdapterOptionsMenu( "View-model adapter options", viewModelAdapterType, options => targetScript.ViewModelAdapterOptions = options, targetScript.ViewModelAdapterOptions, viewModelAdapterOptionsFade.faded ); EditorGUILayout.Space(); var expectionAdapterTypeNames = GetAdapterTypeNames( type => TypeResolver.IsTypeCastableTo(TypeResolver.FindAdapterAttribute(type).InputType, typeof(Exception)) ); EditorStyles.label.fontStyle = exceptionPropertyPrefabModified ? FontStyle.Bold : defaultLabelStyle; var adaptedExceptionPropertyType = AdaptTypeForward( typeof(Exception), targetScript.ExceptionAdapterTypeName ); ShowViewModelPropertyMenuWithNone( new GUIContent( "Exception property", "Property on the view-model to bind the exception to." ), TypeResolver.FindBindableProperties(targetScript), updatedValue => targetScript.ExceptionPropertyName = updatedValue, targetScript.ExceptionPropertyName, prop => TypeResolver.IsTypeCastableTo(prop.PropertyType, adaptedExceptionPropertyType) ); EditorStyles.label.fontStyle = exceptionAdapterPrefabModified ? FontStyle.Bold : defaultLabelStyle; ShowAdapterMenu( new GUIContent( "Exception adapter", "Adapter that handles exceptions thrown by the view-model adapter" ), expectionAdapterTypeNames, targetScript.ExceptionAdapterTypeName, newValue => { if (newValue != targetScript.ExceptionAdapterTypeName) { Undo.RecordObject(targetScript, "Set exception adapter options"); targetScript.ExceptionAdapterOptions = null; } UpdateProperty( updatedValue => targetScript.ExceptionAdapterTypeName = updatedValue, targetScript.ExceptionAdapterTypeName, newValue, "Set exception adapter" ); } ); EditorStyles.label.fontStyle = exceptionAdapterOptionsPrefabModified ? FontStyle.Bold : defaultLabelStyle; Type exceptionAdapterType; exceptionAdapterOptionsFade.target = ShouldShowAdapterOptions( targetScript.ExceptionAdapterTypeName, out exceptionAdapterType ); ShowAdapterOptionsMenu( "Exception adapter options", exceptionAdapterType, options => targetScript.ExceptionAdapterOptions = options, targetScript.ExceptionAdapterOptions, exceptionAdapterOptionsFade.faded ); EditorStyles.label.fontStyle = defaultLabelStyle; GUI.enabled = guiPreviouslyEnabled; } /// <summary> /// Check whether each of the properties on the object have been changed /// from the value in the prefab. /// </summary> private void UpdatePrefabModifiedProperties() { var property = serializedObject.GetIterator(); // Need to call Next(true) to get the first child. Once we have it, Next(false) // will iterate through the properties. property.Next(true); do { switch (property.name) { case "viewEventName": viewEventPrefabModified = property.prefabOverride; break; case "viewPropertyName": viewPropertyPrefabModified = property.prefabOverride; break; case "viewAdapterTypeName": viewAdapterPrefabModified = property.prefabOverride; break; case "viewAdapterOptions": viewAdapterOptionsPrefabModified = property.prefabOverride; break; case "viewModelPropertyName": viewModelPropertyPrefabModified = property.prefabOverride; break; case "viewModelAdapterTypeName": viewModelAdapterPrefabModified = property.prefabOverride; break; case "viewModelAdapterOptions": viewModelAdapterOptionsPrefabModified = property.prefabOverride; break; case "exceptionPropertyName": exceptionPropertyPrefabModified = property.prefabOverride; break; case "exceptionAdapterTypeName": exceptionAdapterPrefabModified = property.prefabOverride; break; case "exceptionAdapterOptions": exceptionAdapterOptionsPrefabModified = property.prefabOverride; break; } } while (property.Next(false)); } } }
using Lucene.Net.Support; using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Represents <see cref="T:long[]"/>, as a slice (offset + length) into an /// existing <see cref="T:long[]"/>. The <see cref="Int64s"/> member should never be <c>null</c>; use /// <see cref="EMPTY_INT64S"/> if necessary. /// <para/> /// NOTE: This was LongsRef in Lucene /// <para/> /// @lucene.internal /// </summary> #if FEATURE_SERIALIZABLE [Serializable] #endif public sealed class Int64sRef : IComparable<Int64sRef> #if FEATURE_CLONEABLE , System.ICloneable #endif { /// <summary> /// An empty <see cref="long"/> array for convenience /// <para/> /// NOTE: This was EMPTY_LONGS in Lucene /// </summary> public static readonly long[] EMPTY_INT64S = #if FEATURE_ARRAYEMPTY Array.Empty<long>(); #else new long[0]; #endif /// <summary> /// The contents of the <see cref="Int64sRef"/>. Should never be <c>null</c>. /// <para/> /// NOTE: This was longs (field) in Lucene /// </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public long[] Int64s { get => longs; set { if (value == null) { throw new ArgumentNullException("value"); } longs = value; } } private long[] longs; /// <summary> /// Offset of first valid long. </summary> public int Offset { get; set; } /// <summary> /// Length of used longs. </summary> public int Length { get; set; } /// <summary> /// Create a <see cref="Int64sRef"/> with <see cref="EMPTY_INT64S"/> </summary> public Int64sRef() { longs = EMPTY_INT64S; } /// <summary> /// Create a <see cref="Int64sRef"/> pointing to a new array of size <paramref name="capacity"/>. /// Offset and length will both be zero. /// </summary> public Int64sRef(int capacity) { longs = new long[capacity]; } /// <summary> /// This instance will directly reference <paramref name="longs"/> w/o making a copy. /// <paramref name="longs"/> should not be <c>null</c>. /// </summary> public Int64sRef(long[] longs, int offset, int length) { this.longs = longs; this.Offset = offset; this.Length = length; Debug.Assert(IsValid()); } /// <summary> /// Returns a shallow clone of this instance (the underlying <see cref="long"/>s are /// <b>not</b> copied and will be shared by both the returned object and this /// object. /// </summary> /// <seealso cref="DeepCopyOf(Int64sRef)"/> public object Clone() { return new Int64sRef(longs, Offset, Length); } public override int GetHashCode() { const int prime = 31; int result = 0; long end = Offset + Length; for (int i = Offset; i < end; i++) { result = prime * result + (int)(longs[i] ^ ((long)((ulong)longs[i] >> 32))); } return result; } public override bool Equals(object other) { if (other == null) { return false; } if (other is Int64sRef) { return this.Int64sEquals((Int64sRef)other); } return false; } /// <summary> /// NOTE: This was longsEquals() in Lucene /// </summary> public bool Int64sEquals(Int64sRef other) { if (Length == other.Length) { int otherUpto = other.Offset; long[] otherInts = other.longs; long end = Offset + Length; for (int upto = Offset; upto < end; upto++, otherUpto++) { if (longs[upto] != otherInts[otherUpto]) { return false; } } return true; } else { return false; } } /// <summary> /// Signed <see cref="int"/> order comparison </summary> public int CompareTo(Int64sRef other) { if (this == other) { return 0; } long[] aInts = this.longs; int aUpto = this.Offset; long[] bInts = other.longs; int bUpto = other.Offset; long aStop = aUpto + Math.Min(this.Length, other.Length); while (aUpto < aStop) { long aInt = aInts[aUpto++]; long bInt = bInts[bUpto++]; if (aInt > bInt) { return 1; } else if (aInt < bInt) { return -1; } } // One is a prefix of the other, or, they are equal: return this.Length - other.Length; } /// <summary> /// NOTE: This was copyLongs() in Lucene /// </summary> public void CopyInt64s(Int64sRef other) { if (longs.Length - Offset < other.Length) { longs = new long[other.Length]; Offset = 0; } Array.Copy(other.longs, other.Offset, longs, Offset, other.Length); Length = other.Length; } /// <summary> /// Used to grow the reference array. /// <para/> /// In general this should not be used as it does not take the offset into account. /// <para/> /// @lucene.internal /// </summary> public void Grow(int newLength) { Debug.Assert(Offset == 0); if (longs.Length < newLength) { longs = ArrayUtil.Grow(longs, newLength); } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append('['); long end = Offset + Length; for (int i = Offset; i < end; i++) { if (i > Offset) { sb.Append(' '); } sb.Append(longs[i].ToString("x")); } sb.Append(']'); return sb.ToString(); } /// <summary> /// Creates a new <see cref="Int64sRef"/> that points to a copy of the <see cref="long"/>s from /// <paramref name="other"/>. /// <para/> /// The returned <see cref="Int64sRef"/> will have a length of <c>other.Length</c> /// and an offset of zero. /// </summary> public static Int64sRef DeepCopyOf(Int64sRef other) { Int64sRef clone = new Int64sRef(); clone.CopyInt64s(other); return clone; } /// <summary> /// Performs internal consistency checks. /// Always returns <c>true</c> (or throws <see cref="InvalidOperationException"/>) /// </summary> public bool IsValid() { if (longs == null) { throw new InvalidOperationException("longs is null"); } if (Length < 0) { throw new InvalidOperationException("length is negative: " + Length); } if (Length > longs.Length) { throw new InvalidOperationException("length is out of bounds: " + Length + ",longs.length=" + longs.Length); } if (Offset < 0) { throw new InvalidOperationException("offset is negative: " + Offset); } if (Offset > longs.Length) { throw new InvalidOperationException("offset out of bounds: " + Offset + ",longs.length=" + longs.Length); } if (Offset + Length < 0) { throw new InvalidOperationException("offset+length is negative: offset=" + Offset + ",length=" + Length); } if (Offset + Length > longs.Length) { throw new InvalidOperationException("offset+length out of bounds: offset=" + Offset + ",length=" + Length + ",longs.length=" + longs.Length); } return true; } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.ComponentModel; using System.Globalization; using DotSpatial.Serialization; using GeoAPI.Geometries; namespace DotSpatial.Data { /// <summary> /// Extent works like an envelope but is faster acting, has a minimum memory profile, /// only works in 2D and has no events. /// </summary> [Serializable] [TypeConverter(typeof(ExpandableObjectConverter))] public class Extent : ICloneable, IExtent { /// <summary> /// Initializes a new instance of the <see cref="Extent"/> class. /// This introduces no error checking and assumes that the user knows what they are doing when working with this. /// </summary> public Extent() { MinX = double.NaN; // changed by jany_ (2015-07-17) default extent is empty because if there is no content there is no extent MaxX = double.NaN; MinY = double.NaN; MaxY = double.NaN; } /// <summary> /// Initializes a new instance of the <see cref="Extent"/> class from the specified ordinates. /// </summary> /// <param name="xMin">The minimum X value.</param> /// <param name="yMin">The minimum Y value.</param> /// <param name="xMax">The maximum X value.</param> /// <param name="yMax">The maximum Y value.</param> public Extent(double xMin, double yMin, double xMax, double yMax) { MinX = xMin; MinY = yMin; MaxX = xMax; MaxY = yMax; } /// <summary> /// Initializes a new instance of the <see cref="Extent"/> class based on the given values. /// </summary> /// <param name="values">Values used to initialize XMin, YMin, XMax, YMax in the given order.</param> /// <param name="offset">Offset indicates at which position we can find MinX. The other values follow directly after that.</param> public Extent(double[] values, int offset) { if (values.Length < 4 + offset) throw new IndexOutOfRangeException("The length of the array of double values should be greater than or equal to 4 plus the value of the offset."); MinX = values[0 + offset]; MinY = values[1 + offset]; MaxX = values[2 + offset]; MaxY = values[3 + offset]; } /// <summary> /// Initializes a new instance of the <see cref="Extent"/> class. /// </summary> /// <param name="values">Values used to initialize XMin, YMin, XMax, YMax in the given order.</param> public Extent(double[] values) { if (values.Length < 4) throw new IndexOutOfRangeException("The length of the array of double values should be greater than or equal to 4."); MinX = values[0]; MinY = values[1]; MaxX = values[2]; MaxY = values[3]; } /// <summary> /// Initializes a new instance of the <see cref="Extent"/> class from the specified envelope. /// </summary> /// <param name="env">Envelope used for Extent creation.</param> public Extent(Envelope env) { if (Equals(env, null)) throw new ArgumentNullException(nameof(env)); MinX = env.MinX; MinY = env.MinY; MaxX = env.MaxX; MaxY = env.MaxY; } #region Properties /// <summary> /// Gets the Center of this extent. /// </summary> public Coordinate Center { get { double x = MinX + ((MaxX - MinX) / 2); double y = MinY + ((MaxY - MinY) / 2); return new Coordinate(x, y); } } /// <summary> /// Gets a value indicating whether the M values are used. M values are considered optional, and not mandatory. /// Unused could mean either bound is NaN for some reason, or else that the bounds are invalid by the Min being less than the Max. /// </summary> public virtual bool HasM => false; /// <summary> /// Gets a value indicating whether the Z values are used. Z values are considered optional, and not mandatory. /// Unused could mean either bound is NaN for some reason, or else that the bounds are invalid by the Min being less than the Max. /// </summary> public virtual bool HasZ => false; /// <summary> /// Gets or sets the height. Getting this returns MaxY - MinY. Setting this will update MinY, keeping MaxY the same. (Pinned at top left corner). /// </summary> public double Height { get { return MaxY - MinY; } set { MinY = MaxY - value; } } /// <summary> /// Gets or sets the maximum X. /// </summary> [Serialize("MaxX")] public double MaxX { get; set; } /// <summary> /// Gets or sets the maximum Y. /// </summary> [Serialize("MaxY")] public double MaxY { get; set; } /// <summary> /// Gets or sets the minimumg X. /// </summary> [Serialize("MinX")] public double MinX { get; set; } /// <summary> /// Gets or sets the minimumg Y. /// </summary> [Serialize("MinY")] public double MinY { get; set; } /// <summary> /// Gets or sets the width. Getting this returns MaxX - MinX. Setting this will update MaxX, keeping MinX the same. (Pinned at top left corner). /// </summary> public double Width { get { return MaxX - MinX; } set { MaxX = MinX + value; } } /// <summary> /// Gets or sets the X. Getting this returns MinX. Setting this will shift both MinX and MaxX, keeping the width the same. /// </summary> public double X { get { return MinX; } set { double w = Width; MinX = value; Width = w; } } /// <summary> /// Gets or sets the Y. Getting this will return MaxY. Setting this will shift both MinY and MaxY, keeping the height the same. /// </summary> public double Y { get { return MaxY; } set { double h = Height; MaxY = value; Height = h; } } #endregion /// <summary> /// Equality test /// </summary> /// <param name="left">First extent to test.</param> /// <param name="right">Second extent to test.</param> /// <returns>True, if the extents equal.</returns> public static bool operator ==(Extent left, IExtent right) { if ((object)left == null) return right == null; return left.Equals(right); } /// <summary> /// Inequality test /// </summary> /// <param name="left">First extent to test.</param> /// <param name="right">Second extent to test.</param> /// <returns>True, if the extents do not equal.</returns> public static bool operator !=(Extent left, IExtent right) { if ((object)left == null) return right != null; return !left.Equals(right); } #region Methods /// <summary> /// This allows parsing the X and Y values from a string version of the extent as: 'X[-180|180], Y[-90|90]' /// Where minimum always precedes maximum. The correct M or MZ version of extent will be returned if the string has those values. /// </summary> /// <param name="text">The string text to parse.</param> /// <returns>The parsed extent.</returns> /// <exception cref="ExtentParseException">Is thrown if the string could not be parsed to an extent.</exception> public static Extent Parse(string text) { Extent result; string fail; if (TryParse(text, out result, out fail)) return result; throw new ExtentParseException(string.Format(DataStrings.ReadingExtentFromStringFailedOnTerm, fail)) { Expression = text }; } /// <summary> /// This allows parsing the X and Y values from a string version of the extent as: 'X[-180|180], Y[-90|90]' /// Where minimum always precedes maximum. The correct M or MZ version of extent will be returned if the string has those values. /// </summary> /// <param name="text">Text that contains the extent values.</param> /// <param name="result">Extent that was created.</param> /// <param name="nameFailed">Indicates which value failed.</param> /// <returns>True if the string could be parsed to an extent.</returns> public static bool TryParse(string text, out Extent result, out string nameFailed) { double xmin, xmax, ymin, ymax, mmin, mmax; result = null; if (text.Contains("Z")) { double zmin, zmax; nameFailed = "Z"; ExtentMz mz = new ExtentMz(); if (!TryExtract(text, "Z", out zmin, out zmax)) return false; mz.MinZ = zmin; mz.MaxZ = zmax; nameFailed = "M"; if (!TryExtract(text, "M", out mmin, out mmax)) return false; mz.MinM = mmin; mz.MaxM = mmax; result = mz; } else if (text.Contains("M")) { nameFailed = "M"; ExtentM me = new ExtentM(); if (!TryExtract(text, "M", out mmin, out mmax)) return false; me.MinM = mmin; me.MaxM = mmax; result = me; } else { result = new Extent(); } nameFailed = "X"; if (!TryExtract(text, "X", out xmin, out xmax)) return false; result.MinX = xmin; result.MaxX = xmax; nameFailed = "Y"; if (!TryExtract(text, "Y", out ymin, out ymax)) return false; result.MinY = ymin; result.MaxY = ymax; return true; } /// <summary> /// Produces a clone, rather than using this same object. /// </summary> /// <returns>The cloned Extent.</returns> public virtual object Clone() { return new Extent(MinX, MinY, MaxX, MaxY); } /// <summary> /// Tests if the specified extent is contained by this extent. /// </summary> /// <param name="ext">Extent that might be contained.</param> /// <returns>True if this extent contains the specified extent.</returns> /// <exception cref="ArgumentNullException">Thrown if ext is null.</exception> public virtual bool Contains(IExtent ext) { if (Equals(ext, null)) throw new ArgumentNullException(nameof(ext)); return Contains(ext.MinX, ext.MaxX, ext.MinY, ext.MaxY); } /// <summary> /// Tests if the specified coordinate is contained by this extent. /// </summary> /// <param name="c">The coordinate to test.</param> /// <returns>True if this extent contains the specified coordinate.</returns> /// <exception cref="ArgumentNullException">Thrown if c is null.</exception> public virtual bool Contains(Coordinate c) { if (Equals(c, null)) throw new ArgumentNullException(nameof(c)); return Contains(c.X, c.X, c.Y, c.Y); } /// <summary> /// Tests if the specified envelope is contained by this extent. /// </summary> /// <param name="env">Envelope that might be contained.</param> /// <returns>True if this extent contains the specified envelope.</returns> /// <exception cref="ArgumentNullException">Thrown if env is null.</exception> public virtual bool Contains(Envelope env) { if (Equals(env, null)) throw new ArgumentNullException(nameof(env)); return Contains(env.MinX, env.MaxX, env.MinY, env.MaxY); } /// <summary> /// Copies the MinX, MaxX, MinY, MaxY values from extent. /// </summary> /// <param name="extent">Any IExtent implementation.</param> public virtual void CopyFrom(IExtent extent) { if (Equals(extent, null)) throw new ArgumentNullException(nameof(extent)); MinX = extent.MinX; MaxX = extent.MaxX; MinY = extent.MinY; MaxY = extent.MaxY; } /// <summary> /// Checks whether this extent and the specified extent are equal. /// </summary> /// <param name="obj">Second Extent to check.</param> /// <returns>True, if extents are the same (either both null or equal in all X and Y values).</returns> public override bool Equals(object obj) { // Check the identity case for reference equality // ReSharper disable once BaseObjectEqualsIsObjectEquals if (base.Equals(obj)) return true; IExtent other = obj as IExtent; if (other == null) return false; return MinX == other.MinX && MinY == other.MinY && MaxX == other.MaxX && MaxY == other.MaxY; } /// <summary> /// Expand will adjust both the minimum and maximum by the specified sizeX and sizeY /// </summary> /// <param name="padX">The amount to expand left and right.</param> /// <param name="padY">The amount to expand up and down.</param> public void ExpandBy(double padX, double padY) { MinX -= padX; MaxX += padX; MinY -= padY; MaxY += padY; } /// <summary> /// This expand the extent by the specified padding on all bounds. So the width will /// change by twice the padding for instance. To Expand only x and y, use /// the overload with those values explicitly specified. /// </summary> /// <param name="padding">The double padding to expand the extent.</param> public virtual void ExpandBy(double padding) { MinX -= padding; MaxX += padding; MinY -= padding; MaxY += padding; } /// <summary> /// Expands this extent to include the domain of the specified extent. /// </summary> /// <param name="ext">The extent to include.</param> public virtual void ExpandToInclude(IExtent ext) { if (ext == null) return; ExpandToInclude(ext.MinX, ext.MaxX, ext.MinY, ext.MaxY); } /// <summary> /// Expands this extent to include the domain of the specified point. /// </summary> /// <param name="x">The x value to include.</param> /// <param name="y">The y value to include.</param> public void ExpandToInclude(double x, double y) { ExpandToInclude(x, x, y, y); } /// <summary> /// Spreads the values for the basic X, Y extents across the whole range of int. /// Repetition will occur, but it should be rare. /// </summary> /// <returns>Integer</returns> public override int GetHashCode() { // 215^4 ~ Int.MaxValue so the value will cover the range based mostly on first 2 sig figs. int xmin = Convert.ToInt32((MinX * 430 / MinX) - 215); int xmax = Convert.ToInt32((MaxX * 430 / MaxX) - 215); int ymin = Convert.ToInt32((MinY * 430 / MinY) - 215); int ymax = Convert.ToInt32((MaxY * 430 / MaxY) - 215); return xmin * xmax * ymin * ymax; } /// <summary> /// Calculates the intersection of this extent and the other extent. A result /// with a min greater than the max in either direction is considered invalid /// and represents no intersection. /// </summary> /// <param name="other">The other extent to intersect with.</param> /// <returns>The resulting extent.</returns> public virtual Extent Intersection(Extent other) { if (Equals(other, null)) throw new ArgumentNullException(nameof(other)); Extent result = new Extent { MinX = MinX > other.MinX ? MinX : other.MinX, MaxX = MaxX < other.MaxX ? MaxX : other.MaxX, MinY = MinY > other.MinY ? MinY : other.MinY, MaxY = MaxY < other.MaxY ? MaxY : other.MaxY }; return result; } /// <summary> /// Tests if this extent intersects the specified coordinate. /// </summary> /// <param name="c">The coordinate that might intersect this extent.</param> /// <returns>True if this extent intersects the specified coordinate.</returns> /// <exception cref="ArgumentNullException">Thrown if c is null.</exception> public virtual bool Intersects(Coordinate c) { if (Equals(c, null)) throw new ArgumentNullException(nameof(c)); return Intersects(c.X, c.Y); } /// <summary> /// Tests for intersection with the specified coordinate. /// </summary> /// <param name="x">The double ordinate to test intersection with in the X direction.</param> /// <param name="y">The double ordinate to test intersection with in the Y direction.</param> /// <returns>True if a point with the specified x and y coordinates is within or on the border /// of this extent object. NAN values will always return false.</returns> public bool Intersects(double x, double y) { if (double.IsNaN(x) || double.IsNaN(y)) return false; return x >= MinX && x <= MaxX && y >= MinY && y <= MaxY; } /// <summary> /// Tests if this extent intersects the specified vertex. /// </summary> /// <param name="vert">The vertex that might intersect this extent.</param> /// <returns>True if this extent intersects the specified vertex.</returns> /// <exception cref="ArgumentNullException">Thrown if vert is null.</exception> public bool Intersects(Vertex vert) { if (Equals(vert, null)) throw new ArgumentNullException(nameof(vert)); return Intersects(vert.X, vert.Y); } /// <summary> /// Tests if this extent intersects the specified extent. /// </summary> /// <param name="ext">The extent that might intersect this extent.</param> /// <returns>True if this extent intersects the specified extent.</returns> /// <exception cref="ArgumentNullException">Thrown if ext is null.</exception> public virtual bool Intersects(IExtent ext) { if (Equals(ext, null)) throw new ArgumentNullException(nameof(ext)); return Intersects(ext.MinX, ext.MaxX, ext.MinY, ext.MaxY); } /// <summary> /// Tests if this extent intersects the specified envelope. /// </summary> /// <param name="env">The envelope that might intersect this extent.</param> /// <returns>True if this extent intersects the specified envelope.</returns> /// <exception cref="ArgumentNullException">Thrown if env is null.</exception> public virtual bool Intersects(Envelope env) { if (Equals(env, null)) throw new ArgumentNullException(nameof(env)); return Intersects(env.MinX, env.MaxX, env.MinY, env.MaxY); } /// <summary> /// If this is undefined, it will have a min that is larger than the max, or else any value is NaN. /// This only applies to the X and Y terms. Check HasM or HasZ for higher dimensions. /// </summary> /// <returns>Boolean, true if the envelope has not had values set for it yet.</returns> public bool IsEmpty() { if (double.IsNaN(MinX) || double.IsNaN(MaxX) || double.IsNaN(MinY) || double.IsNaN(MaxY)) return true; return MinX > MaxX || MinY > MaxY; // Simplified } /// <summary> /// This centers the X and Y aspect of the extent on the specified center location. /// </summary> /// <param name="centerX">The X value of the center coordinate to set.</param> /// <param name="centerY">The Y value of the center coordinate to set.</param> /// <param name="width">The new extent width.</param> /// <param name="height">The new extent height.</param> public void SetCenter(double centerX, double centerY, double width, double height) { MinX = centerX - (width / 2); MaxX = centerX + (width / 2); MinY = centerY - (height / 2); MaxY = centerY + (height / 2); } /// <summary> /// This centers the X and Y aspect of the extent on the specified center location. /// </summary> /// <param name="center">The center coordinate to set.</param> /// <param name="width">The new extent width.</param> /// <param name="height">The new extent height.</param> /// <exception cref="ArgumentNullException">Thrown if center is null.</exception> public void SetCenter(Coordinate center, double width, double height) { if (Equals(center, null)) throw new ArgumentNullException(nameof(center)); SetCenter(center.X, center.Y, width, height); } /// <summary> /// This centers the extent on the specified coordinate, keeping the width and height the same. /// </summary> /// <param name="center">Center value which is used to center the extent.</param> /// <exception cref="ArgumentNullException">Thrown if center is null.</exception> public void SetCenter(Coordinate center) { // prevents NullReferenceException when accessing center.X and center.Y if (Equals(center, null)) throw new ArgumentNullException(nameof(center)); SetCenter(center.X, center.Y, Width, Height); } /// <summary> /// Sets the values for xMin, xMax, yMin and yMax. /// </summary> /// <param name="minX">The double Minimum in the X direction.</param> /// <param name="minY">The double Minimum in the Y direction.</param> /// <param name="maxX">The double Maximum in the X direction.</param> /// <param name="maxY">The double Maximum in the Y direction.</param> public void SetValues(double minX, double minY, double maxX, double maxY) { MinX = minX; MinY = minY; MaxX = maxX; MaxY = maxY; } /// <summary> /// Creates a geometric envelope interface from this. /// </summary> /// <returns>An envelope with the min and max values of this extent.</returns> public Envelope ToEnvelope() { if (double.IsNaN(MinX)) return new Envelope(); return new Envelope(MinX, MaxX, MinY, MaxY); } /// <summary> /// Creates a string that shows the extent. /// </summary> /// <returns>The string form of the extent.</returns> public override string ToString() { return "X[" + MinX + "|" + MaxX + "], Y[" + MinY + "|" + MaxY + "]"; } /// <summary> /// Tests if this extent is within the specified extent. /// </summary> /// <param name="ext">Extent that might contain this extent.</param> /// <returns>True if this extent is within the specified extent.</returns> /// <exception cref="ArgumentNullException">Thrown if ext is null.</exception> public virtual bool Within(IExtent ext) { if (Equals(ext, null)) throw new ArgumentNullException(nameof(ext)); return Within(ext.MinX, ext.MaxX, ext.MinY, ext.MaxY); } /// <summary> /// Tests if this extent is within the specified envelope. /// </summary> /// <param name="env">Envelope that might contain this extent.</param> /// <returns>True if this extent is within the specified envelope.</returns> /// <exception cref="ArgumentNullException">Thrown if env is null.</exception> public virtual bool Within(Envelope env) { if (Equals(env, null)) throw new ArgumentNullException(nameof(env)); return Within(env.MinX, env.MaxX, env.MinY, env.MaxY); } /// <summary> /// Attempts to extract the min and max from one element of text. The element should be /// formatted like X[1.5|2.7] using an invariant culture. /// </summary> /// <param name="entireText">Complete text from which the values should be parsed.</param> /// <param name="name">The name of the dimension, like X.</param> /// <param name="min">The minimum that gets assigned</param> /// <param name="max">The maximum that gets assigned</param> /// <returns>Boolean, true if the parse was successful.</returns> private static bool TryExtract(string entireText, string name, out double min, out double max) { int i = entireText.IndexOf(name, StringComparison.Ordinal); i += name.Length + 1; int j = entireText.IndexOf(']', i); string vals = entireText.Substring(i, j - i); return TryParseExtremes(vals, out min, out max); } /// <summary> /// Attempts to extract the min and max from the text. The text should be formatted like 1.5|2.7 using an invariant culture. /// </summary> /// <param name="numeric">Text that should be parsed.</param> /// <param name="min">The minimum that gets assigned.</param> /// <param name="max">The maximum that gets assigned.</param> /// <returns>True, if the numeric was parsed successfully.</returns> private static bool TryParseExtremes(string numeric, out double min, out double max) { string[] res = numeric.Split('|'); max = double.NaN; if (!double.TryParse(res[0].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out min)) return false; if (res.Length < 2) return false; if (!double.TryParse(res[1].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out max)) return false; return true; } /// <summary> /// Tests if the specified extent is contained by this extent. /// </summary> /// <param name="minX">MinX value of the extent that might be contained.</param> /// <param name="maxX">MaxX value of the extent that might be contained.</param> /// <param name="minY">MinY value of the extent that might be contained.</param> /// <param name="maxY">MaxY value of the extent that might be contained.</param> /// <returns>True if this extent contains the specified extent.</returns> private bool Contains(double minX, double maxX, double minY, double maxY) { return minX >= MinX && maxX <= MaxX && minY >= MinY && maxY <= MaxY; } /// <summary> /// Expands this extent to include the domain of the specified extent. /// </summary> /// <param name="minX">MinX value of the extent that might intersect this extent.</param> /// <param name="maxX">MaxX value of the extent that might intersect this extent.</param> /// <param name="minY">MinY value of the extent that might intersect this extent.</param> /// <param name="maxY">MaxY value of the extent that might intersect this extent.</param> private void ExpandToInclude(double minX, double maxX, double minY, double maxY) { if (double.IsNaN(MinX) || minX < MinX) MinX = minX; if (double.IsNaN(MinY) || minY < MinY) MinY = minY; if (double.IsNaN(MaxX) || maxX > MaxX) MaxX = maxX; if (double.IsNaN(MaxY) || maxY > MaxY) MaxY = maxY; } /// <summary> /// Tests if this extent intersects the specified extent. /// </summary> /// <param name="minX">MinX value of the extent that might intersect this extent.</param> /// <param name="maxX">MaxX value of the extent that might intersect this extent.</param> /// <param name="minY">MinY value of the extent that might intersect this extent.</param> /// <param name="maxY">MaxY value of the extent that might intersect this extent.</param> /// <returns>True if this extent intersects the specified extent.</returns> private bool Intersects(double minX, double maxX, double minY, double maxY) { return maxX >= MinX && minX <= MaxX && maxY >= MinY && minY <= MaxY; } /// <summary> /// Tests if this extent is within the specified extent. /// </summary> /// <param name="minX">MinX value of the extent that might contain this extent.</param> /// <param name="maxX">MaxX value of the extent that might contain this extent.</param> /// <param name="minY">MinY value of the extent that might contain this extent.</param> /// <param name="maxY">MaxY value of the extent that might contain this extent.</param> /// <returns>True if this extent is within the specified extent.</returns> private bool Within(double minX, double maxX, double minY, double maxY) { return MinX >= minX && MaxX <= maxX && MinY >= minY && MaxY <= maxY; } #endregion } }
using System; using Csla; using SelfLoadSoftDelete.DataAccess; using SelfLoadSoftDelete.DataAccess.ERLevel; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G07_Country_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="G07_Country_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="G06_Country"/> collection. /// </remarks> [Serializable] public partial class G07_Country_ReChild : BusinessBase<G07_Country_ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Country_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Country_Child_NameProperty = RegisterProperty<string>(p => p.Country_Child_Name, "Regions Child Name"); /// <summary> /// Gets or sets the Regions Child Name. /// </summary> /// <value>The Regions Child Name.</value> public string Country_Child_Name { get { return GetProperty(Country_Child_NameProperty); } set { SetProperty(Country_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G07_Country_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="G07_Country_ReChild"/> object.</returns> internal static G07_Country_ReChild NewG07_Country_ReChild() { return DataPortal.CreateChild<G07_Country_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="G07_Country_ReChild"/> object, based on given parameters. /// </summary> /// <param name="country_ID2">The Country_ID2 parameter of the G07_Country_ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="G07_Country_ReChild"/> object.</returns> internal static G07_Country_ReChild GetG07_Country_ReChild(int country_ID2) { return DataPortal.FetchChild<G07_Country_ReChild>(country_ID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G07_Country_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public G07_Country_ReChild() { // 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="G07_Country_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G07_Country_ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="country_ID2">The Country ID2.</param> protected void Child_Fetch(int country_ID2) { var args = new DataPortalHookArgs(country_ID2); OnFetchPre(args); using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var dal = dalManager.GetProvider<IG07_Country_ReChildDal>(); var data = dal.Fetch(country_ID2); Fetch(data); } OnFetchPost(args); // check all object rules and property rules BusinessRules.CheckRules(); } /// <summary> /// Loads a <see cref="G07_Country_ReChild"/> object from the given <see cref="G07_Country_ReChildDto"/>. /// </summary> /// <param name="data">The G07_Country_ReChildDto to use.</param> private void Fetch(G07_Country_ReChildDto data) { // Value properties LoadProperty(Country_Child_NameProperty, data.Country_Child_Name); var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="G07_Country_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G06_Country parent) { var dto = new G07_Country_ReChildDto(); dto.Parent_Country_ID = parent.Country_ID; dto.Country_Child_Name = Country_Child_Name; using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IG07_Country_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="G07_Country_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(G06_Country parent) { if (!IsDirty) return; var dto = new G07_Country_ReChildDto(); dto.Parent_Country_ID = parent.Country_ID; dto.Country_Child_Name = Country_Child_Name; using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IG07_Country_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="G07_Country_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(G06_Country parent) { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IG07_Country_ReChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Country_ID); } 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 } }
// // Fallen8.cs // // Author: // Henning Rauch <Henning@RauchEntwicklung.biz> // // Copyright (c) 2012-2015 Henning Rauch // // 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. #region Usings using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Threading; using NoSQL.GraphDB.Algorithms.Path; using NoSQL.GraphDB.Error; using NoSQL.GraphDB.Expression; using NoSQL.GraphDB.Helper; using NoSQL.GraphDB.Index; using NoSQL.GraphDB.Index.Fulltext; using NoSQL.GraphDB.Index.Range; using NoSQL.GraphDB.Index.Spatial; using NoSQL.GraphDB.Log; using NoSQL.GraphDB.Model; using NoSQL.GraphDB.Persistency; using NoSQL.GraphDB.Plugin; using NoSQL.GraphDB.Service; using System.Threading.Tasks; #endregion namespace NoSQL.GraphDB { /// <summary> /// Fallen8. /// </summary> public sealed class Fallen8 : AThreadSafeElement, IRead, IWrite, IDisposable { #region Data /// <summary> /// The graph elements /// </summary> private List<AGraphElement> _graphElements; /// <summary> /// The delegate to find elements in the big list /// </summary> /// <param name="objectOfT">The to be analyzed object of T</param> /// <returns>True or false</returns> public delegate Boolean ElementSeeker(AGraphElement objectOfT); /// <summary> /// The index factory. /// </summary> public IndexFactory IndexFactory { get; internal set; } /// <summary> /// The index factory. /// </summary> public ServiceFactory ServiceFactory { get; internal set; } /// <summary> /// The count of edges /// </summary> public Int32 EdgeCount { get; private set; } /// <summary> /// The count of vertices /// </summary> public Int32 VertexCount { get; private set; } /// <summary> /// The current identifier. /// </summary> private Int32 _currentId = 0; /// <summary> /// Binary operator delegate. /// </summary> private delegate Boolean BinaryOperatorDelegate(IComparable property, IComparable literal); #endregion #region Constructor /// <summary> /// Initializes a new instance of the Fallen-8 class. /// </summary> public Fallen8() { IndexFactory = new IndexFactory(); _graphElements = new List<AGraphElement>(); ServiceFactory = new ServiceFactory(this); IndexFactory.Indices.Clear(); } /// <summary> /// Initializes a new instance of the Fallen-8 class and loads the vertices from a save point. /// </summary> /// <param name='path'> Path to the save point. </param> public Fallen8(String path) :this() { Load(path, true); } #endregion #region IWrite implementation public void Load(String path, Boolean startServices = false) { if (String.IsNullOrWhiteSpace(path)) { Logger.LogInfo(String.Format("There is no path given, so nothing will be loaded.")); return; } Logger.LogInfo(String.Format("Fallen-8 now loads a savegame from path \"{0}\"", path)); if (ReadResource()) { try { var oldIndexFactory = IndexFactory; var oldServiceFactory = ServiceFactory; oldServiceFactory.ShutdownAllServices(); var oldGraphElements = _graphElements; #if __MonoCS__ //mono specific code #else GC.Collect(); GC.Collect(); GC.WaitForFullGCComplete(-1); GC.WaitForPendingFinalizers(); #endif _graphElements = new List<AGraphElement>(); var success = PersistencyFactory.Load(this, ref _graphElements, path, ref _currentId, startServices); if (success) { oldIndexFactory.DeleteAllIndices(); } else { _graphElements = oldGraphElements; IndexFactory = oldIndexFactory; ServiceFactory = oldServiceFactory; ServiceFactory.StartAllServices(); } TrimPrivate(); } finally { FinishReadResource(); } return; } throw new CollisionException(this); } public void Trim() { if (WriteResource()) { try { TrimPrivate(); } finally { FinishWriteResource(); } return; } throw new CollisionException(this); } public void TabulaRasa() { if (WriteResource()) { try { _currentId = 0; _graphElements = new List<AGraphElement>(); IndexFactory.DeleteAllIndices(); VertexCount = 0; EdgeCount = 0; } finally { FinishWriteResource(); } return; } throw new CollisionException(this); } public VertexModel CreateVertex(UInt32 creationDate, PropertyContainer[] properties = null) { if (WriteResource()) { try { //create the new vertex var newVertex = new VertexModel(_currentId, creationDate, properties); //insert it _graphElements.Add(newVertex); //increment the id Interlocked.Increment(ref _currentId); //Increase the vertex count VertexCount++; return newVertex; } finally { FinishWriteResource(); } } throw new CollisionException(this); } public EdgeModel CreateEdge(Int32 sourceVertexId, UInt16 edgePropertyId, Int32 targetVertexId, UInt32 creationDate, PropertyContainer[] properties = null) { if (WriteResource()) { try { EdgeModel outgoingEdge = null; var sourceVertex = _graphElements[sourceVertexId] as VertexModel; var targetVertex = _graphElements[targetVertexId] as VertexModel; //get the related vertices if (sourceVertex != null && targetVertex != null) { outgoingEdge = new EdgeModel(_currentId, creationDate, targetVertex, sourceVertex, properties); //add the edge to the graph elements _graphElements.Add(outgoingEdge); //increment the ids Interlocked.Increment(ref _currentId); //add the edge to the source vertex sourceVertex.AddOutEdge(edgePropertyId, outgoingEdge); //link the vertices targetVertex.AddIncomingEdge(edgePropertyId, outgoingEdge); //increase the edgeCount EdgeCount++; } return outgoingEdge; } finally { FinishWriteResource(); } } throw new CollisionException(this); } public bool TryAddProperty(Int32 graphElementId, UInt16 propertyId, Object property) { if (WriteResource()) { try { var success = false; AGraphElement graphElement = _graphElements[graphElementId]; if (graphElement != null) { success = graphElement != null && graphElement.TryAddProperty(propertyId, property); } return success; } finally { FinishWriteResource(); } } throw new CollisionException(this); } public bool TryRemoveProperty(Int32 graphElementId, UInt16 propertyId) { if (WriteResource()) { try { var graphElement = _graphElements[graphElementId]; var success = graphElement != null && graphElement.TryRemoveProperty(propertyId); return success; } finally { FinishWriteResource(); } } throw new CollisionException(this); } public bool TryRemoveGraphElement(Int32 graphElementId) { if (WriteResource()) { try { AGraphElement graphElement = _graphElements[graphElementId]; if (graphElement == null) { return false; } //used if an edge is removed List<UInt16> inEdgeRemovals = null; List<UInt16> outEdgeRemovals = null; try { #region remove element _graphElements[graphElementId] = null; if (graphElement is VertexModel) { #region remove vertex var vertex = (VertexModel) graphElement; #region out edges var outgoingEdgeConatiner = vertex.GetOutgoingEdges(); if (outgoingEdgeConatiner != null) { for (var i = 0; i < outgoingEdgeConatiner.Count; i++) { var aOutEdgeContainer = outgoingEdgeConatiner[i]; for (var j = 0; j < aOutEdgeContainer.Edges.Count; j++) { var aOutEdge = aOutEdgeContainer.Edges[j]; //remove from incoming edges of target vertex aOutEdge.TargetVertex.RemoveIncomingEdge(aOutEdgeContainer.EdgePropertyId, aOutEdge); //remove the edge itself _graphElements[aOutEdge.Id] = null; } } } #endregion #region in edges var incomingEdgeContainer = vertex.GetIncomingEdges(); if (incomingEdgeContainer != null) { for (var i = 0; i < incomingEdgeContainer.Count; i++) { var aInEdgeContainer = incomingEdgeContainer[i]; for (var j = 0; j < aInEdgeContainer.Edges.Count; j++) { var aInEdge = aInEdgeContainer.Edges[j]; //remove from outgoing edges of source vertex aInEdge.SourceVertex.RemoveOutGoingEdge(aInEdgeContainer.EdgePropertyId, aInEdge); //remove the edge itself _graphElements[aInEdge.Id] = null; } } } #endregion //update the EdgeCount --> hard way RecalculateGraphElementCounter(); #endregion } else { #region remove edge var edge = (EdgeModel) graphElement; //remove from incoming edges of target vertex inEdgeRemovals = edge.TargetVertex.RemoveIncomingEdge(edge); //remove from outgoing edges of source vertex outEdgeRemovals = edge.SourceVertex.RemoveOutGoingEdge(edge); //update the EdgeCount --> easy way EdgeCount--; #endregion } #endregion } catch (Exception) { #region restore _graphElements.Insert(graphElementId, graphElement); if (graphElement is VertexModel) { #region restore vertex var vertex = (VertexModel) graphElement; #region out edges var outgoingEdgeConatiner = vertex.GetOutgoingEdges(); if (outgoingEdgeConatiner != null) { for (var i = 0; i < outgoingEdgeConatiner.Count; i++) { var aOutEdgeContainer = outgoingEdgeConatiner[i]; for (var j = 0; j < aOutEdgeContainer.Edges.Count; j++) { var aOutEdge = aOutEdgeContainer.Edges[j]; //remove from incoming edges of target vertex aOutEdge.TargetVertex.AddIncomingEdge(aOutEdgeContainer.EdgePropertyId, aOutEdge); //reset the edge _graphElements.Insert(aOutEdge.Id, aOutEdge); } } } #endregion #region in edges var incomingEdgeContainer = vertex.GetIncomingEdges(); if (incomingEdgeContainer != null) { for (var i = 0; i < incomingEdgeContainer.Count; i++) { var aInEdgeContainer = incomingEdgeContainer[i]; for (var j = 0; j < aInEdgeContainer.Edges.Count; j++) { var aInEdge = aInEdgeContainer.Edges[j]; //remove from outgoing edges of source vertex aInEdge.SourceVertex.AddOutEdge(aInEdgeContainer.EdgePropertyId, aInEdge); //reset the edge _graphElements.Insert(aInEdge.Id, aInEdge); } } } #endregion #endregion } else { #region restore edge var edge = (EdgeModel) graphElement; if (inEdgeRemovals != null) { for (var i = 0; i < inEdgeRemovals.Count; i++) { edge.TargetVertex.AddIncomingEdge(inEdgeRemovals[i], edge); } } if (outEdgeRemovals != null) { for (var i = 0; i < outEdgeRemovals.Count; i++) { edge.SourceVertex.AddOutEdge(outEdgeRemovals[i], edge); } } #endregion } //recalculate the counter RecalculateGraphElementCounter(); #endregion throw; } } finally { FinishWriteResource(); } return true; } throw new CollisionException(this); } #endregion #region IRead implementation public Boolean TryGetVertex(out VertexModel result, Int32 id) { if (ReadResource()) { try { result = _graphElements[id] as VertexModel; return result != null; } finally { FinishReadResource(); } } throw new CollisionException(this); } public Boolean TryGetEdge(out EdgeModel result, Int32 id) { if (ReadResource()) { try { result = _graphElements[id] as EdgeModel; return result != null; } finally { FinishReadResource(); } } throw new CollisionException(this); } public Boolean TryGetGraphElement(out AGraphElement result, Int32 id) { if (ReadResource()) { try { result = _graphElements[id]; return result != null; } finally { FinishReadResource(); } } throw new CollisionException(this); } public bool CalculateShortestPath( out List<Path> result, string algorithmname, Int32 sourceVertexId, Int32 destinationVertexId, Int32 maxDepth = 1, Double maxPathWeight = Double.MaxValue, Int32 maxResults = 1, PathDelegates.EdgePropertyFilter edgePropertyFilter = null, PathDelegates.VertexFilter vertexFilter = null, PathDelegates.EdgeFilter edgeFilter = null, PathDelegates.EdgeCost edgeCost = null, PathDelegates.VertexCost vertexCost = null) { IShortestPathAlgorithm algo; if (PluginFactory.TryFindPlugin(out algo, algorithmname)) { algo.Initialize(this, null); if (ReadResource()) { try { result = algo.Calculate(sourceVertexId, destinationVertexId, maxDepth, maxPathWeight, maxResults, edgePropertyFilter, vertexFilter, edgeFilter, edgeCost, vertexCost); return result != null && result.Count > 0; } finally { FinishReadResource(); } } throw new CollisionException(this); } result = null; return false; } public bool GraphScan(out List<AGraphElement> result, UInt16 propertyId, IComparable literal, BinaryOperator binOp) { #region binary operation switch (binOp) { case BinaryOperator.Equals: result = FindElements(BinaryEqualsMethod, literal, propertyId); break; case BinaryOperator.Greater: result = FindElements(BinaryGreaterMethod, literal, propertyId); break; case BinaryOperator.GreaterOrEquals: result = FindElements(BinaryGreaterOrEqualMethod, literal, propertyId); break; case BinaryOperator.LowerOrEquals: result = FindElements(BinaryLowerOrEqualMethod, literal, propertyId); break; case BinaryOperator.Lower: result = FindElements(BinaryLowerMethod, literal, propertyId); break; case BinaryOperator.NotEquals: result = FindElements(BinaryNotEqualsMethod, literal, propertyId); break; default: result = new List<AGraphElement>(); break; } #endregion return result.Count > 0; } public bool IndexScan(out ReadOnlyCollection<AGraphElement> result, String indexId, IComparable literal, BinaryOperator binOp) { IIndex index; if (!IndexFactory.TryGetIndex(out index, indexId)) { result = null; return false; } #region binary operation switch (binOp) { case BinaryOperator.Equals: if( ! index.TryGetValue(out result, literal)) { result = null; return false; } break; case BinaryOperator.Greater: result = FindElementsIndex(BinaryGreaterMethod, literal, index); break; case BinaryOperator.GreaterOrEquals: result = FindElementsIndex(BinaryGreaterOrEqualMethod, literal, index); break; case BinaryOperator.LowerOrEquals: result = FindElementsIndex(BinaryLowerOrEqualMethod, literal, index); break; case BinaryOperator.Lower: result = FindElementsIndex(BinaryLowerMethod, literal, index); break; case BinaryOperator.NotEquals: result = FindElementsIndex(BinaryNotEqualsMethod, literal, index); break; default: result = null; return false; } #endregion return result.Count > 0; } public bool RangeIndexScan(out ReadOnlyCollection<AGraphElement> result, String indexId, IComparable leftLimit, IComparable rightLimit, bool includeLeft, bool includeRight) { IIndex index; if (!IndexFactory.TryGetIndex(out index, indexId)) { result = null; return false; } var rangeIndex = index as IRangeIndex; if (rangeIndex != null) { return rangeIndex.Between(out result, leftLimit, rightLimit, includeLeft, includeRight); } result = null; return false; } public bool FulltextIndexScan(out FulltextSearchResult result, String indexId, string searchQuery) { IIndex index; if (!IndexFactory.TryGetIndex(out index, indexId)) { result = null; return false; } var fulltextIndex = index as IFulltextIndex; if (fulltextIndex != null) { return fulltextIndex.TryQuery(out result, searchQuery); } result = null; return false; } public bool SpatialIndexScan(out ReadOnlyCollection<AGraphElement> result, String indexId, IGeometry geometry) { IIndex index; if (!IndexFactory.TryGetIndex(out index, indexId)) { result = null; return false; } var spatialIndex = index as ISpatialIndex; if (spatialIndex != null) { return spatialIndex.TryGetValue(out result, geometry); } result = null; return false; } public void Save(String path, UInt32 savePartitions = 5) { if (ReadResource()) { try { PersistencyFactory.Save(this, _graphElements, path, savePartitions, _currentId); } finally { FinishReadResource(); } return; } throw new CollisionException(this); } #endregion #region public methods /// <summary> /// Shutdown this Fallen-8 server. /// </summary> public void Shutdown() { ServiceFactory.ShutdownAllServices(); } #endregion #region private helper methods /// <summary> /// Finds the elements. /// </summary> /// <returns> The elements. </returns> /// <param name='finder'> Finder. </param> /// <param name='literal'> Literal. </param> /// <param name='propertyId'> Property identifier. </param> private List<AGraphElement> FindElements(BinaryOperatorDelegate finder, IComparable literal, UInt16 propertyId) { if (ReadResource()) { try { var result = FindElements( aGraphElement => { Object property; return aGraphElement.TryGetProperty(out property, propertyId) && finder(property as IComparable, literal); }); return result; } finally { FinishReadResource(); } } throw new CollisionException(this); } /// <summary> /// Find elements by scanning the list /// </summary> /// <param name="seeker">A delegate to search for the right element</param> /// <returns>A list of matching graph elements</returns> private List<AGraphElement> FindElements(ElementSeeker seeker) { return _graphElements.AsParallel() .Where(_ => _!=null && seeker(_)) .ToList(); } /// <summary> /// Finds elements via an index. /// </summary> /// <returns> The elements. </returns> /// <param name='finder'> Finder delegate. </param> /// <param name='literal'> Literal. </param> /// <param name='index'> Index. </param> private static ReadOnlyCollection<AGraphElement> FindElementsIndex(BinaryOperatorDelegate finder, IComparable literal, IIndex index) { return new ReadOnlyCollection<AGraphElement>(index.GetKeyValues() .AsParallel() .Select(aIndexElement => new KeyValuePair<IComparable, ReadOnlyCollection<AGraphElement>>((IComparable)aIndexElement.Key, aIndexElement.Value)) .Where(aTypedIndexElement => finder(aTypedIndexElement.Key, literal)) .Select(_ => _.Value) .SelectMany(__ => __) .Distinct() .ToList()); } /// <summary> /// Method for binary comparism /// </summary> /// <returns> <c>true</c> for equality; otherwise, <c>false</c> . </returns> /// <param name='property'> Property. </param> /// <param name='literal'> Literal. </param> private static Boolean BinaryEqualsMethod(IComparable property, IComparable literal) { return property.Equals(literal); } /// <summary> /// Method for binary comparism /// </summary> /// <returns> <c>true</c> for inequality; otherwise, <c>false</c> . </returns> /// <param name='property'> Property. </param> /// <param name='literal'> Literal. </param> private static Boolean BinaryNotEqualsMethod(IComparable property, IComparable literal) { return !property.Equals(literal); } /// <summary> /// Method for binary comparism /// </summary> /// <returns> <c>true</c> for greater property; otherwise, <c>false</c> . </returns> /// <param name='property'> Property. </param> /// <param name='literal'> Literal. </param> private static Boolean BinaryGreaterMethod(IComparable property, IComparable literal) { return property.CompareTo(literal) > 0; } /// <summary> /// Method for binary comparism /// </summary> /// <returns> <c>true</c> for lower property; otherwise, <c>false</c> . </returns> /// <param name='property'> Property. </param> /// <param name='literal'> Literal. </param> private static Boolean BinaryLowerMethod(IComparable property, IComparable literal) { return property.CompareTo(literal) < 0; } /// <summary> /// Method for binary comparism /// </summary> /// <returns> <c>true</c> for lower or equal property; otherwise, <c>false</c> . </returns> /// <param name='property'> Property. </param> /// <param name='literal'> Literal. </param> private static Boolean BinaryLowerOrEqualMethod(IComparable property, IComparable literal) { return property.CompareTo(literal) <= 0; } /// <summary> /// Method for binary comparism /// </summary> /// <returns> <c>true</c> for greater or equal property; otherwise, <c>false</c> . </returns> /// <param name='property'> Property. </param> /// <param name='literal'> Literal. </param> private static Boolean BinaryGreaterOrEqualMethod(IComparable property, IComparable literal) { return property.CompareTo(literal) >= 0; } /// <summary> /// Trims the Fallen-8. /// </summary> private void TrimPrivate() { for (var i = 0; i < _currentId; i++) { AGraphElement graphElement = _graphElements[i]; if (graphElement != null) { graphElement.Trim(); } } List<AGraphElement> newGraphElementList = new List<AGraphElement>(); //copy the list and exclude nulls foreach (var aGraphElement in _graphElements) { if (aGraphElement != null) { newGraphElementList.Add(aGraphElement); } } //check the IDs for (int i = 0; i < newGraphElementList.Count; i++) { newGraphElementList[i].SetId(i) ; } //set the correct currentID _currentId = newGraphElementList.Count; //cleanup and switch _graphElements.Clear(); _graphElements = newGraphElementList; #if __MonoCS__ //mono specific code #else GC.Collect(); GC.Collect(); GC.WaitForFullGCComplete(-1); GC.WaitForPendingFinalizers(); #endif #if __MonoCS__ //mono specific code #else var errorCode = SaveNativeMethods.EmptyWorkingSet(Process.GetCurrentProcess().Handle); #endif RecalculateGraphElementCounter(); } /// <summary> /// Recalculates the count of the graph elements /// </summary> private void RecalculateGraphElementCounter() { EdgeCount = GetCountOf<EdgeModel>(); VertexCount = GetCountOf<VertexModel>(); } public int GetCountOf<TInteresting>() { return _graphElements.AsParallel() .Where(_ => _ != null && _ is TInteresting).Count(); } #endregion #region IDisposable Members public void Dispose() { TabulaRasa(); _graphElements = null; IndexFactory.DeleteAllIndices(); IndexFactory = null; ServiceFactory.ShutdownAllServices(); ServiceFactory = null; } #endregion } }
#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.Diagnostics; using Microsoft.Identity.Json.Utilities; using System.Globalization; #if HAVE_DYNAMIC using System.Dynamic; using System.Linq.Expressions; #endif #if HAVE_BIG_INTEGER using System.Numerics; #endif namespace Microsoft.Identity.Json.Linq { /// <summary> /// Represents a value in JSON (string, integer, date, etc). /// </summary> internal partial class JValue : JToken, IEquatable<JValue>, IFormattable, IComparable, IComparable<JValue> #if HAVE_ICONVERTIBLE , IConvertible #endif { private JTokenType _valueType; private object _value; internal JValue(object value, JTokenType type) { _value = value; _valueType = type; } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class from another <see cref="JValue"/> object. /// </summary> /// <param name="other">A <see cref="JValue"/> object to copy from.</param> public JValue(JValue other) : this(other.Value, other.Type) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(long value) : this(value, JTokenType.Integer) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(decimal value) : this(value, JTokenType.Float) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(char value) : this(value, JTokenType.String) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> // [ClsCompliant(false)] public JValue(ulong value) : this(value, JTokenType.Integer) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(double value) : this(value, JTokenType.Float) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(float value) : this(value, JTokenType.Float) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(DateTime value) : this(value, JTokenType.Date) { } #if HAVE_DATE_TIME_OFFSET /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(DateTimeOffset value) : this(value, JTokenType.Date) { } #endif /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(bool value) : this(value, JTokenType.Boolean) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(string value) : this(value, JTokenType.String) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(Guid value) : this(value, JTokenType.Guid) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(Uri value) : this(value, (value != null) ? JTokenType.Uri : JTokenType.Null) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(TimeSpan value) : this(value, JTokenType.TimeSpan) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(object value) : this(value, GetValueType(null, value)) { } internal override bool DeepEquals(JToken node) { if (!(node is JValue other)) { return false; } if (other == this) { return true; } return ValuesEquals(this, other); } /// <summary> /// Gets a value indicating whether this token has child tokens. /// </summary> /// <value> /// <c>true</c> if this token has child values; otherwise, <c>false</c>. /// </value> public override bool HasValues => false; #if HAVE_BIG_INTEGER private static int CompareBigInteger(BigInteger i1, object i2) { int result = i1.CompareTo(ConvertUtils.ToBigInteger(i2)); if (result != 0) { return result; } // converting a fractional number to a BigInteger will lose the fraction // check for fraction if result is two numbers are equal if (i2 is decimal d1) { return 0m.CompareTo(Math.Abs(d1 - Math.Truncate(d1))); } else if (i2 is double || i2 is float) { double d = Convert.ToDouble(i2, CultureInfo.InvariantCulture); return 0d.CompareTo(Math.Abs(d - Math.Truncate(d))); } return result; } #endif internal static int Compare(JTokenType valueType, object objA, object objB) { if (objA == objB) { return 0; } if (objB == null) { return 1; } if (objA == null) { return -1; } switch (valueType) { case JTokenType.Integer: { #if HAVE_BIG_INTEGER if (objA is BigInteger integerA) { return CompareBigInteger(integerA, objB); } if (objB is BigInteger integerB) { return -CompareBigInteger(integerB, objA); } #endif if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) { return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)); } else if (objA is float || objB is float || objA is double || objB is double) { return CompareFloat(objA, objB); } else { return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture)); } } case JTokenType.Float: { #if HAVE_BIG_INTEGER if (objA is BigInteger integerA) { return CompareBigInteger(integerA, objB); } if (objB is BigInteger integerB) { return -CompareBigInteger(integerB, objA); } #endif if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) { return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)); } return CompareFloat(objA, objB); } case JTokenType.Comment: case JTokenType.String: case JTokenType.Raw: string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture); string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture); return string.CompareOrdinal(s1, s2); case JTokenType.Boolean: bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture); bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture); return b1.CompareTo(b2); case JTokenType.Date: #if HAVE_DATE_TIME_OFFSET if (objA is DateTime dateA) { #else DateTime dateA = (DateTime)objA; #endif DateTime dateB; #if HAVE_DATE_TIME_OFFSET if (objB is DateTimeOffset offsetB) { dateB = offsetB.DateTime; } else #endif { dateB = Convert.ToDateTime(objB, CultureInfo.InvariantCulture); } return dateA.CompareTo(dateB); #if HAVE_DATE_TIME_OFFSET } else { DateTimeOffset offsetA = (DateTimeOffset)objA; if (!(objB is DateTimeOffset offsetB)) { offsetB = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture)); } return offsetA.CompareTo(offsetB); } #endif case JTokenType.Bytes: if (!(objB is byte[] bytesB)) { throw new ArgumentException("Object must be of type byte[]."); } byte[] bytesA = objA as byte[]; Debug.Assert(bytesA != null); return MiscellaneousUtils.ByteArrayCompare(bytesA, bytesB); case JTokenType.Guid: if (!(objB is Guid)) { throw new ArgumentException("Object must be of type Guid."); } Guid guid1 = (Guid)objA; Guid guid2 = (Guid)objB; return guid1.CompareTo(guid2); case JTokenType.Uri: Uri uri2 = objB as Uri; if (uri2 == null) { throw new ArgumentException("Object must be of type Uri."); } Uri uri1 = (Uri)objA; return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString()); case JTokenType.TimeSpan: if (!(objB is TimeSpan)) { throw new ArgumentException("Object must be of type TimeSpan."); } TimeSpan ts1 = (TimeSpan)objA; TimeSpan ts2 = (TimeSpan)objB; return ts1.CompareTo(ts2); default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(valueType), valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType)); } } private static int CompareFloat(object objA, object objB) { double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture); double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture); // take into account possible floating point errors if (MathUtils.ApproxEquals(d1, d2)) { return 0; } return d1.CompareTo(d2); } #if HAVE_EXPRESSIONS private static bool Operation(ExpressionType operation, object objA, object objB, out object result) { if (objA is string || objB is string) { if (operation == ExpressionType.Add || operation == ExpressionType.AddAssign) { result = objA?.ToString() + objB?.ToString(); return true; } } #if HAVE_BIG_INTEGER if (objA is BigInteger || objB is BigInteger) { if (objA == null || objB == null) { result = null; return true; } // not that this will lose the fraction // BigInteger doesn't have operators with non-integer types BigInteger i1 = ConvertUtils.ToBigInteger(objA); BigInteger i2 = ConvertUtils.ToBigInteger(objB); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = i1 + i2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = i1 - i2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = i1 * i2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = i1 / i2; return true; } } else #endif if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) { if (objA == null || objB == null) { result = null; return true; } decimal d1 = Convert.ToDecimal(objA, CultureInfo.InvariantCulture); decimal d2 = Convert.ToDecimal(objB, CultureInfo.InvariantCulture); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = d1 + d2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = d1 - d2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = d1 * d2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = d1 / d2; return true; } } else if (objA is float || objB is float || objA is double || objB is double) { if (objA == null || objB == null) { result = null; return true; } double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture); double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = d1 + d2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = d1 - d2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = d1 * d2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = d1 / d2; return true; } } else if (objA is int || objA is uint || objA is long || objA is short || objA is ushort || objA is sbyte || objA is byte || objB is int || objB is uint || objB is long || objB is short || objB is ushort || objB is sbyte || objB is byte) { if (objA == null || objB == null) { result = null; return true; } long l1 = Convert.ToInt64(objA, CultureInfo.InvariantCulture); long l2 = Convert.ToInt64(objB, CultureInfo.InvariantCulture); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = l1 + l2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = l1 - l2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = l1 * l2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = l1 / l2; return true; } } result = null; return false; } #endif internal override JToken CloneToken() { return new JValue(this); } /// <summary> /// Creates a <see cref="JValue"/> comment with the given value. /// </summary> /// <param name="value">The value.</param> /// <returns>A <see cref="JValue"/> comment with the given value.</returns> public static JValue CreateComment(string value) { return new JValue(value, JTokenType.Comment); } /// <summary> /// Creates a <see cref="JValue"/> string with the given value. /// </summary> /// <param name="value">The value.</param> /// <returns>A <see cref="JValue"/> string with the given value.</returns> public static JValue CreateString(string value) { return new JValue(value, JTokenType.String); } /// <summary> /// Creates a <see cref="JValue"/> null value. /// </summary> /// <returns>A <see cref="JValue"/> null value.</returns> public static JValue CreateNull() { return new JValue(null, JTokenType.Null); } /// <summary> /// Creates a <see cref="JValue"/> undefined value. /// </summary> /// <returns>A <see cref="JValue"/> undefined value.</returns> public static JValue CreateUndefined() { return new JValue(null, JTokenType.Undefined); } private static JTokenType GetValueType(JTokenType? current, object value) { if (value == null) { return JTokenType.Null; } #if HAVE_ADO_NET else if (value == DBNull.Value) { return JTokenType.Null; } #endif else if (value is string) { return GetStringValueType(current); } else if (value is long || value is int || value is short || value is sbyte || value is ulong || value is uint || value is ushort || value is byte) { return JTokenType.Integer; } else if (value is Enum) { return JTokenType.Integer; } #if HAVE_BIG_INTEGER else if (value is BigInteger) { return JTokenType.Integer; } #endif else if (value is double || value is float || value is decimal) { return JTokenType.Float; } else if (value is DateTime) { return JTokenType.Date; } #if HAVE_DATE_TIME_OFFSET else if (value is DateTimeOffset) { return JTokenType.Date; } #endif else if (value is byte[]) { return JTokenType.Bytes; } else if (value is bool) { return JTokenType.Boolean; } else if (value is Guid) { return JTokenType.Guid; } else if (value is Uri) { return JTokenType.Uri; } else if (value is TimeSpan) { return JTokenType.TimeSpan; } throw new ArgumentException("Could not determine JSON object type for type {0}.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); } private static JTokenType GetStringValueType(JTokenType? current) { if (current == null) { return JTokenType.String; } switch (current.GetValueOrDefault()) { case JTokenType.Comment: case JTokenType.String: case JTokenType.Raw: return current.GetValueOrDefault(); default: return JTokenType.String; } } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type => _valueType; /// <summary> /// Gets or sets the underlying token value. /// </summary> /// <value>The underlying token value.</value> public object Value { get => _value; set { Type currentType = _value?.GetType(); Type newType = value?.GetType(); if (currentType != newType) { _valueType = GetValueType(_valueType, value); } _value = value; } } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/>s which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { if (converters != null && converters.Length > 0 && _value != null) { JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); if (matchingConverter != null && matchingConverter.CanWrite) { matchingConverter.WriteJson(writer, _value, JsonSerializer.CreateDefault()); return; } } switch (_valueType) { case JTokenType.Comment: writer.WriteComment(_value?.ToString()); return; case JTokenType.Raw: writer.WriteRawValue(_value?.ToString()); return; case JTokenType.Null: writer.WriteNull(); return; case JTokenType.Undefined: writer.WriteUndefined(); return; case JTokenType.Integer: if (_value is int i) { writer.WriteValue(i); } else if (_value is long l) { writer.WriteValue(l); } else if (_value is ulong ul) { writer.WriteValue(ul); } #if HAVE_BIG_INTEGER else if (_value is BigInteger integer) { writer.WriteValue(integer); } #endif else { writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture)); } return; case JTokenType.Float: if (_value is decimal dec) { writer.WriteValue(dec); } else if (_value is double d) { writer.WriteValue(d); } else if (_value is float f) { writer.WriteValue(f); } else { writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture)); } return; case JTokenType.String: writer.WriteValue(_value?.ToString()); return; case JTokenType.Boolean: writer.WriteValue(Convert.ToBoolean(_value, CultureInfo.InvariantCulture)); return; case JTokenType.Date: #if HAVE_DATE_TIME_OFFSET if (_value is DateTimeOffset offset) { writer.WriteValue(offset); } else #endif { writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture)); } return; case JTokenType.Bytes: writer.WriteValue((byte[])_value); return; case JTokenType.Guid: writer.WriteValue((_value != null) ? (Guid?)_value : null); return; case JTokenType.TimeSpan: writer.WriteValue((_value != null) ? (TimeSpan?)_value : null); return; case JTokenType.Uri: writer.WriteValue((Uri)_value); return; } throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(Type), _valueType, "Unexpected token type."); } internal override int GetDeepHashCode() { int valueHashCode = (_value != null) ? _value.GetHashCode() : 0; // GetHashCode on an enum boxes so cast to int return ((int)_valueType).GetHashCode() ^ valueHashCode; } private static bool ValuesEquals(JValue v1, JValue v2) { return v1 == v2 || (v1._valueType == v2._valueType && Compare(v1._valueType, v1._value, v2._value) == 0); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <returns> /// <c>true</c> if the current object is equal to the <paramref name="other"/> parameter; otherwise, <c>false</c>. /// </returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(JValue other) { if (other == null) { return false; } return ValuesEquals(this, other); } /// <summary> /// Determines whether the specified <see cref="object"/> is equal to the current <see cref="object"/>. /// </summary> /// <param name="obj">The <see cref="object"/> to compare with the current <see cref="object"/>.</param> /// <returns> /// <c>true</c> if the specified <see cref="object"/> is equal to the current <see cref="object"/>; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return Equals(obj as JValue); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="object"/>. /// </returns> public override int GetHashCode() { if (_value == null) { return 0; } return _value.GetHashCode(); } /// <summary> /// Returns a <see cref="string"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="string"/> that represents this instance. /// </returns> public override string ToString() { if (_value == null) { return string.Empty; } return _value.ToString(); } /// <summary> /// Returns a <see cref="string"/> that represents this instance. /// </summary> /// <param name="format">The format.</param> /// <returns> /// A <see cref="string"/> that represents this instance. /// </returns> public string ToString(string format) { return ToString(format, CultureInfo.CurrentCulture); } /// <summary> /// Returns a <see cref="string"/> that represents this instance. /// </summary> /// <param name="formatProvider">The format provider.</param> /// <returns> /// A <see cref="string"/> that represents this instance. /// </returns> public string ToString(IFormatProvider formatProvider) { return ToString(null, formatProvider); } /// <summary> /// Returns a <see cref="string"/> that represents this instance. /// </summary> /// <param name="format">The format.</param> /// <param name="formatProvider">The format provider.</param> /// <returns> /// A <see cref="string"/> that represents this instance. /// </returns> public string ToString(string format, IFormatProvider formatProvider) { if (_value == null) { return string.Empty; } if (_value is IFormattable formattable) { return formattable.ToString(format, formatProvider); } else { return _value.ToString(); } } #if HAVE_DYNAMIC /// <summary> /// Returns the <see cref="DynamicMetaObject"/> responsible for binding operations performed on this object. /// </summary> /// <param name="parameter">The expression tree representation of the runtime value.</param> /// <returns> /// The <see cref="DynamicMetaObject"/> to bind this object. /// </returns> protected override DynamicMetaObject GetMetaObject(Expression parameter) { return new DynamicProxyMetaObject<JValue>(parameter, this, new JValueDynamicProxy()); } private class JValueDynamicProxy : DynamicProxy<JValue> { public override bool TryConvert(JValue instance, ConvertBinder binder, out object result) { if (binder.Type == typeof(JValue) || binder.Type == typeof(JToken)) { result = instance; return true; } object value = instance.Value; if (value == null) { result = null; return ReflectionUtils.IsNullable(binder.Type); } result = ConvertUtils.Convert(value, CultureInfo.InvariantCulture, binder.Type); return true; } public override bool TryBinaryOperation(JValue instance, BinaryOperationBinder binder, object arg, out object result) { object compareValue = arg is JValue value ? value.Value : arg; switch (binder.Operation) { case ExpressionType.Equal: result = Compare(instance.Type, instance.Value, compareValue) == 0; return true; case ExpressionType.NotEqual: result = Compare(instance.Type, instance.Value, compareValue) != 0; return true; case ExpressionType.GreaterThan: result = Compare(instance.Type, instance.Value, compareValue) > 0; return true; case ExpressionType.GreaterThanOrEqual: result = Compare(instance.Type, instance.Value, compareValue) >= 0; return true; case ExpressionType.LessThan: result = Compare(instance.Type, instance.Value, compareValue) < 0; return true; case ExpressionType.LessThanOrEqual: result = Compare(instance.Type, instance.Value, compareValue) <= 0; return true; case ExpressionType.Add: case ExpressionType.AddAssign: case ExpressionType.Subtract: case ExpressionType.SubtractAssign: case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: case ExpressionType.Divide: case ExpressionType.DivideAssign: if (Operation(binder.Operation, instance.Value, compareValue, out result)) { result = new JValue(result); return true; } break; } result = null; return false; } } #endif int IComparable.CompareTo(object obj) { if (obj == null) { return 1; } JTokenType comparisonType; object otherValue; if (obj is JValue value) { otherValue = value.Value; comparisonType = (_valueType == JTokenType.String && _valueType != value._valueType) ? value._valueType : _valueType; } else { otherValue = obj; comparisonType = _valueType; } return Compare(comparisonType, _value, otherValue); } /// <summary> /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings: /// Value /// Meaning /// Less than zero /// This instance is less than <paramref name="obj"/>. /// Zero /// This instance is equal to <paramref name="obj"/>. /// Greater than zero /// This instance is greater than <paramref name="obj"/>. /// </returns> /// <exception cref="ArgumentException"> /// <paramref name="obj"/> is not of the same type as this instance. /// </exception> public int CompareTo(JValue obj) { if (obj == null) { return 1; } JTokenType comparisonType = (_valueType == JTokenType.String && _valueType != obj._valueType) ? obj._valueType : _valueType; return Compare(comparisonType, _value, obj._value); } #if HAVE_ICONVERTIBLE TypeCode IConvertible.GetTypeCode() { if (_value == null) { return TypeCode.Empty; } if (_value is IConvertible convertable) { return convertable.GetTypeCode(); } return TypeCode.Object; } bool IConvertible.ToBoolean(IFormatProvider provider) { return (bool)this; } char IConvertible.ToChar(IFormatProvider provider) { return (char)this; } sbyte IConvertible.ToSByte(IFormatProvider provider) { return (sbyte)this; } byte IConvertible.ToByte(IFormatProvider provider) { return (byte)this; } short IConvertible.ToInt16(IFormatProvider provider) { return (short)this; } ushort IConvertible.ToUInt16(IFormatProvider provider) { return (ushort)this; } int IConvertible.ToInt32(IFormatProvider provider) { return (int)this; } uint IConvertible.ToUInt32(IFormatProvider provider) { return (uint)this; } long IConvertible.ToInt64(IFormatProvider provider) { return (long)this; } ulong IConvertible.ToUInt64(IFormatProvider provider) { return (ulong)this; } float IConvertible.ToSingle(IFormatProvider provider) { return (float)this; } double IConvertible.ToDouble(IFormatProvider provider) { return (double)this; } decimal IConvertible.ToDecimal(IFormatProvider provider) { return (decimal)this; } DateTime IConvertible.ToDateTime(IFormatProvider provider) { return (DateTime)this; } object IConvertible.ToType(Type conversionType, IFormatProvider provider) { return ToObject(conversionType); } #endif } }
using System; using Eto.Forms; using swf = System.Windows.Forms; using sd = System.Drawing; using sdi = System.Drawing.Imaging; using Eto.WinForms.Drawing; using Eto.Drawing; using System.Runtime.InteropServices; using System.IO; using System.ComponentModel; using System.Text; namespace Eto.WinForms.Forms { public class ClipboardHandler : WidgetHandler<swf.DataObject, Clipboard>, Clipboard.IHandler { public ClipboardHandler() { Control = new swf.DataObject(); } void Update() { swf.Clipboard.SetDataObject(Control); } public void SetData(byte[] value, string type) { Control.SetData(type, value); Update(); } public void SetString(string value, string type) { Control.SetData(type, value); Update(); } public string Html { set { Control.SetText(value ?? string.Empty, System.Windows.Forms.TextDataFormat.Html); Update(); } get { return swf.Clipboard.ContainsText(swf.TextDataFormat.Html) ? swf.Clipboard.GetText(swf.TextDataFormat.Html) : null; } } public string Text { set { Control.SetText(value ?? string.Empty); Update(); } get { return swf.Clipboard.ContainsText() ? swf.Clipboard.GetText() : null; } } public Image Image { set { var sdimage = value.ControlObject as sd.Image; if (sdimage != null) { Control.SetImage(sdimage); Update(); } } get { Image result = null; try { var sdimage = GetImageFromClipboard() as sd.Bitmap; if (sdimage != null) { var handler = new BitmapHandler(sdimage); result = new Bitmap(handler); } } catch { } return result; } } /// <summary> /// see http://stackoverflow.com/questions/11273669/how-to-paste-a-transparent-image-from-the-clipboard-in-a-c-sharp-winforms-app /// </summary> static sd.Image GetImageFromClipboard() { if (swf.Clipboard.GetDataObject() == null) return null; if (swf.Clipboard.GetDataObject().GetDataPresent(swf.DataFormats.Dib)) { var dib = ((System.IO.MemoryStream)swf.Clipboard.GetData(swf.DataFormats.Dib)).ToArray(); var width = BitConverter.ToInt32(dib, 4); var height = BitConverter.ToInt32(dib, 8); var bpp = BitConverter.ToInt16(dib, 14); if (bpp == 32) { var gch = GCHandle.Alloc(dib, GCHandleType.Pinned); sd.Bitmap bmp = null; try { var ptr = new IntPtr((long)gch.AddrOfPinnedObject() + 40); bmp = new sd.Bitmap(width, height, width * 4, sdi.PixelFormat.Format32bppArgb, ptr); var result = new sd.Bitmap(bmp); // Images are rotated and flipped for some reason. // This rotates them back. result.RotateFlip(sd.RotateFlipType.Rotate180FlipX); return result; } finally { gch.Free(); if (bmp != null) bmp.Dispose(); } } } if (swf.Clipboard.ContainsFileDropList()) { var list = swf.Clipboard.GetFileDropList(); if (list != null && list.Count > 0) { var path = list[0]; sd.Image bmp = null; try { bmp = sd.Image.FromFile(path); var result = new sd.Bitmap(bmp); return result; } catch { } finally { if (bmp != null) bmp.Dispose(); } } } return swf.Clipboard.ContainsImage() ? swf.Clipboard.GetImage() : null; } public byte[] GetData(string type) { if (swf.Clipboard.ContainsData(type)) { var data = swf.Clipboard.GetData(type); var bytes = data as byte[]; if (bytes != null) return bytes; if (data != null) { var converter = TypeDescriptor.GetConverter(data.GetType()); if (converter != null && converter.CanConvertTo(typeof(byte[]))) { return converter.ConvertTo(data, typeof(byte[])) as byte[]; } } if (data is string) { return Encoding.UTF8.GetBytes(data as string); } if (data is IConvertible) { return Convert.ChangeType(data, typeof(byte[])) as byte[]; } } return null; } public string GetString(string type) { if (swf.Clipboard.ContainsData(type)) return swf.Clipboard.GetData(type) as string; return null; } public string[] Types { get { var data = swf.Clipboard.GetDataObject(); return data != null ? data.GetFormats() : null; } } public void Clear() { swf.Clipboard.Clear(); Control = new swf.DataObject(); } } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Order ///<para>SObject Name: Order</para> ///<para>Custom Object: False</para> ///</summary> public class SfOrder : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "Order"; } } ///<summary> /// Order ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Owner ID /// <para>Name: OwnerId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "ownerId")] public string OwnerId { get; set; } ///<summary> /// Contract ID /// <para>Name: ContractId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "contractId")] public string ContractId { get; set; } ///<summary> /// ReferenceTo: Contract /// <para>RelationshipName: Contract</para> ///</summary> [JsonProperty(PropertyName = "contract")] [Updateable(false), Createable(false)] public SfContract Contract { get; set; } ///<summary> /// Account ID /// <para>Name: AccountId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "accountId")] public string AccountId { get; set; } ///<summary> /// ReferenceTo: Account /// <para>RelationshipName: Account</para> ///</summary> [JsonProperty(PropertyName = "account")] [Updateable(false), Createable(false)] public SfAccount Account { get; set; } ///<summary> /// Price Book ID /// <para>Name: Pricebook2Id</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "pricebook2Id")] public string Pricebook2Id { get; set; } ///<summary> /// ReferenceTo: Pricebook2 /// <para>RelationshipName: Pricebook2</para> ///</summary> [JsonProperty(PropertyName = "pricebook2")] [Updateable(false), Createable(false)] public SfPricebook2 Pricebook2 { get; set; } ///<summary> /// Order ID /// <para>Name: OriginalOrderId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "originalOrderId")] [Updateable(false), Createable(true)] public string OriginalOrderId { get; set; } ///<summary> /// ReferenceTo: Order /// <para>RelationshipName: OriginalOrder</para> ///</summary> [JsonProperty(PropertyName = "originalOrder")] [Updateable(false), Createable(false)] public SfOrder OriginalOrder { get; set; } ///<summary> /// Order Start Date /// <para>Name: EffectiveDate</para> /// <para>SF Type: date</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "effectiveDate")] public DateTime? EffectiveDate { get; set; } ///<summary> /// Order End Date /// <para>Name: EndDate</para> /// <para>SF Type: date</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "endDate")] public DateTime? EndDate { get; set; } ///<summary> /// Reduction Order /// <para>Name: IsReductionOrder</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isReductionOrder")] [Updateable(false), Createable(true)] public bool? IsReductionOrder { get; set; } ///<summary> /// Status /// <para>Name: Status</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } ///<summary> /// Description /// <para>Name: Description</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "description")] public string Description { get; set; } ///<summary> /// Customer Authorized By ID /// <para>Name: CustomerAuthorizedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "customerAuthorizedById")] public string CustomerAuthorizedById { get; set; } ///<summary> /// ReferenceTo: Contact /// <para>RelationshipName: CustomerAuthorizedBy</para> ///</summary> [JsonProperty(PropertyName = "customerAuthorizedBy")] [Updateable(false), Createable(false)] public SfContact CustomerAuthorizedBy { get; set; } ///<summary> /// Customer Authorized Date /// <para>Name: CustomerAuthorizedDate</para> /// <para>SF Type: date</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "customerAuthorizedDate")] public DateTime? CustomerAuthorizedDate { get; set; } ///<summary> /// Company Authorized By ID /// <para>Name: CompanyAuthorizedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "companyAuthorizedById")] public string CompanyAuthorizedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CompanyAuthorizedBy</para> ///</summary> [JsonProperty(PropertyName = "companyAuthorizedBy")] [Updateable(false), Createable(false)] public SfUser CompanyAuthorizedBy { get; set; } ///<summary> /// Company Authorized Date /// <para>Name: CompanyAuthorizedDate</para> /// <para>SF Type: date</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "companyAuthorizedDate")] public DateTime? CompanyAuthorizedDate { get; set; } ///<summary> /// Order Type /// <para>Name: Type</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "type")] public string Type { get; set; } ///<summary> /// Billing Street /// <para>Name: BillingStreet</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingStreet")] public string BillingStreet { get; set; } ///<summary> /// Billing City /// <para>Name: BillingCity</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingCity")] public string BillingCity { get; set; } ///<summary> /// Billing State/Province /// <para>Name: BillingState</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingState")] public string BillingState { get; set; } ///<summary> /// Billing Zip/Postal Code /// <para>Name: BillingPostalCode</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingPostalCode")] public string BillingPostalCode { get; set; } ///<summary> /// Billing Country /// <para>Name: BillingCountry</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingCountry")] public string BillingCountry { get; set; } ///<summary> /// Billing Latitude /// <para>Name: BillingLatitude</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingLatitude")] public double? BillingLatitude { get; set; } ///<summary> /// Billing Longitude /// <para>Name: BillingLongitude</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingLongitude")] public double? BillingLongitude { get; set; } ///<summary> /// Billing Geocode Accuracy /// <para>Name: BillingGeocodeAccuracy</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingGeocodeAccuracy")] public string BillingGeocodeAccuracy { get; set; } ///<summary> /// Billing Address /// <para>Name: BillingAddress</para> /// <para>SF Type: address</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billingAddress")] [Updateable(false), Createable(false)] public Address BillingAddress { get; set; } ///<summary> /// Shipping Street /// <para>Name: ShippingStreet</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "shippingStreet")] public string ShippingStreet { get; set; } ///<summary> /// Shipping City /// <para>Name: ShippingCity</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "shippingCity")] public string ShippingCity { get; set; } ///<summary> /// Shipping State/Province /// <para>Name: ShippingState</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "shippingState")] public string ShippingState { get; set; } ///<summary> /// Shipping Zip/Postal Code /// <para>Name: ShippingPostalCode</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "shippingPostalCode")] public string ShippingPostalCode { get; set; } ///<summary> /// Shipping Country /// <para>Name: ShippingCountry</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "shippingCountry")] public string ShippingCountry { get; set; } ///<summary> /// Shipping Latitude /// <para>Name: ShippingLatitude</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "shippingLatitude")] public double? ShippingLatitude { get; set; } ///<summary> /// Shipping Longitude /// <para>Name: ShippingLongitude</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "shippingLongitude")] public double? ShippingLongitude { get; set; } ///<summary> /// Shipping Geocode Accuracy /// <para>Name: ShippingGeocodeAccuracy</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "shippingGeocodeAccuracy")] public string ShippingGeocodeAccuracy { get; set; } ///<summary> /// Shipping Address /// <para>Name: ShippingAddress</para> /// <para>SF Type: address</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "shippingAddress")] [Updateable(false), Createable(false)] public Address ShippingAddress { get; set; } ///<summary> /// Order Name /// <para>Name: Name</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } ///<summary> /// PO Date /// <para>Name: PoDate</para> /// <para>SF Type: date</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "poDate")] public DateTime? PoDate { get; set; } ///<summary> /// PO Number /// <para>Name: PoNumber</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "poNumber")] public string PoNumber { get; set; } ///<summary> /// Order Reference Number /// <para>Name: OrderReferenceNumber</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "orderReferenceNumber")] public string OrderReferenceNumber { get; set; } ///<summary> /// Bill To Contact ID /// <para>Name: BillToContactId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "billToContactId")] public string BillToContactId { get; set; } ///<summary> /// ReferenceTo: Contact /// <para>RelationshipName: BillToContact</para> ///</summary> [JsonProperty(PropertyName = "billToContact")] [Updateable(false), Createable(false)] public SfContact BillToContact { get; set; } ///<summary> /// Ship To Contact ID /// <para>Name: ShipToContactId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "shipToContactId")] public string ShipToContactId { get; set; } ///<summary> /// ReferenceTo: Contact /// <para>RelationshipName: ShipToContact</para> ///</summary> [JsonProperty(PropertyName = "shipToContact")] [Updateable(false), Createable(false)] public SfContact ShipToContact { get; set; } ///<summary> /// Activated Date /// <para>Name: ActivatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "activatedDate")] [Updateable(true), Createable(false)] public DateTimeOffset? ActivatedDate { get; set; } ///<summary> /// Activated By ID /// <para>Name: ActivatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "activatedById")] [Updateable(true), Createable(false)] public string ActivatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: ActivatedBy</para> ///</summary> [JsonProperty(PropertyName = "activatedBy")] [Updateable(false), Createable(false)] public SfUser ActivatedBy { get; set; } ///<summary> /// Status Category /// <para>Name: StatusCode</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "statusCode")] [Updateable(true), Createable(false)] public string StatusCode { get; set; } ///<summary> /// Order Number /// <para>Name: OrderNumber</para> /// <para>SF Type: string</para> /// <para>AutoNumber field</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "orderNumber")] [Updateable(false), Createable(false)] public string OrderNumber { get; set; } ///<summary> /// Order Amount /// <para>Name: TotalAmount</para> /// <para>SF Type: currency</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "totalAmount")] [Updateable(false), Createable(false)] public decimal? TotalAmount { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Last Viewed Date /// <para>Name: LastViewedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastViewedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastViewedDate { get; set; } ///<summary> /// Last Referenced Date /// <para>Name: LastReferencedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastReferencedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastReferencedDate { get; set; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Reflection.Emit; using Microsoft.PowerShell; using System.Threading; using System.Management.Automation.Internal; namespace System.Management.Automation.Language { internal class TypeDefiner { private static int s_globalCounter = 0; private static readonly object[] s_emptyArgArray = Utils.EmptyArray<object>(); private static readonly CustomAttributeBuilder s_hiddenCustomAttributeBuilder = new CustomAttributeBuilder(typeof(HiddenAttribute).GetConstructor(Type.EmptyTypes), s_emptyArgArray); private static readonly string s_sessionStateKeeperFieldName = "__sessionStateKeeper"; internal static readonly string SessionStateFieldName = "__sessionState"; private static readonly MethodInfo s_sessionStateKeeper_GetSessionState = typeof(SessionStateKeeper).GetMethod("GetSessionState", BindingFlags.Instance | BindingFlags.Public); private static bool TryConvertArg(object arg, Type type, out object result, Parser parser, IScriptExtent errorExtent) { // This code could be added to LanguagePrimitives.ConvertTo if (arg != null && arg.GetType() == type) { result = arg; return true; } if (!LanguagePrimitives.TryConvertTo(arg, type, out result)) { parser.ReportError(errorExtent, () => ParserStrings.CannotConvertValue, ToStringCodeMethods.Type(type)); return false; } return true; } private static CustomAttributeBuilder GetAttributeBuilder(Parser parser, AttributeAst attributeAst, AttributeTargets attributeTargets) { var attributeType = attributeAst.TypeName.GetReflectionAttributeType(); Diagnostics.Assert(attributeType != null, "Semantic checks should have verified attribute type exists"); Diagnostics.Assert( attributeType.GetTypeInfo().GetCustomAttribute<AttributeUsageAttribute>(true) == null || (attributeType.GetTypeInfo().GetCustomAttribute<AttributeUsageAttribute>(true).ValidOn & attributeTargets) != 0, "Semantic checks should have verified attribute usage"); var positionalArgs = new object[attributeAst.PositionalArguments.Count]; var cvv = new ConstantValueVisitor { AttributeArgument = false }; for (var i = 0; i < attributeAst.PositionalArguments.Count; i++) { var posArg = attributeAst.PositionalArguments[i]; positionalArgs[i] = posArg.Accept(cvv); } var ctorInfos = attributeType.GetConstructors(); var newConstructors = DotNetAdapter.GetMethodInformationArray(ctorInfos); string errorId = null; string errorMsg = null; bool expandParamsOnBest; bool callNonVirtually; var positionalArgCount = positionalArgs.Length; var bestMethod = Adapter.FindBestMethod(newConstructors, null, positionalArgs, ref errorId, ref errorMsg, out expandParamsOnBest, out callNonVirtually); if (bestMethod == null) { parser.ReportError(new ParseError(attributeAst.Extent, errorId, string.Format(CultureInfo.InvariantCulture, errorMsg, attributeType.Name, attributeAst.PositionalArguments.Count))); return null; } var constructorInfo = (ConstructorInfo)bestMethod.method; var parameterInfo = constructorInfo.GetParameters(); var ctorArgs = new object[parameterInfo.Length]; object arg; for (var argIndex = 0; argIndex < parameterInfo.Length; ++argIndex) { var resultType = parameterInfo[argIndex].ParameterType; // The extension method 'CustomAttributeExtensions.GetCustomAttributes(ParameterInfo, Type, Boolean)' has inconsistent // behavior on its return value in both FullCLR and CoreCLR. According to MSDN, if the attribute cannot be found, it // should return an empty collection. However, it returns null in some rare cases [when the parameter isn't backed by // actual metadata]. // This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling // against CoreCLR. So we need to add a null check until this is fixed in CLR. var paramArrayAttrs = parameterInfo[argIndex].GetCustomAttributes(typeof(ParamArrayAttribute), true); if (paramArrayAttrs != null && paramArrayAttrs.Any() && expandParamsOnBest) { var elementType = parameterInfo[argIndex].ParameterType.GetElementType(); var paramsArray = Array.CreateInstance(elementType, positionalArgCount - argIndex); ctorArgs[argIndex] = paramsArray; for (var i = 0; i < paramsArray.Length; ++i, ++argIndex) { if (!TryConvertArg(positionalArgs[argIndex], elementType, out arg, parser, attributeAst.PositionalArguments[argIndex].Extent)) { return null; } paramsArray.SetValue(arg, i); } break; } if (!TryConvertArg(positionalArgs[argIndex], resultType, out arg, parser, attributeAst.PositionalArguments[argIndex].Extent)) { return null; } ctorArgs[argIndex] = arg; } if (attributeAst.NamedArguments.Count == 0) { return new CustomAttributeBuilder(constructorInfo, ctorArgs); } var propertyInfoList = new List<PropertyInfo>(); var propertyArgs = new List<object>(); var fieldInfoList = new List<FieldInfo>(); var fieldArgs = new List<object>(); foreach (var namedArg in attributeAst.NamedArguments) { var name = namedArg.ArgumentName; var members = attributeType.GetMember(name, MemberTypes.Field | MemberTypes.Property, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy); Diagnostics.Assert(members.Length == 1 && (members[0] is PropertyInfo || members[0] is FieldInfo), "Semantic checks should have ensured names attribute argument exists"); arg = namedArg.Argument.Accept(cvv); var propertyInfo = members[0] as PropertyInfo; if (propertyInfo != null) { Diagnostics.Assert(propertyInfo.GetSetMethod() != null, "Semantic checks ensures property is settable"); if (!TryConvertArg(arg, propertyInfo.PropertyType, out arg, parser, namedArg.Argument.Extent)) { return null; } propertyInfoList.Add(propertyInfo); propertyArgs.Add(arg); continue; } var fieldInfo = (FieldInfo)members[0]; Diagnostics.Assert(!fieldInfo.IsInitOnly && !fieldInfo.IsLiteral, "Semantic checks ensures field is settable"); if (!TryConvertArg(arg, fieldInfo.FieldType, out arg, parser, namedArg.Argument.Extent)) { return null; } fieldInfoList.Add(fieldInfo); fieldArgs.Add(arg); } return new CustomAttributeBuilder(constructorInfo, ctorArgs, propertyInfoList.ToArray(), propertyArgs.ToArray(), fieldInfoList.ToArray(), fieldArgs.ToArray()); } internal static void DefineCustomAttributes(TypeBuilder member, ReadOnlyCollection<AttributeAst> attributes, Parser parser, AttributeTargets attributeTargets) { if (attributes != null) { foreach (var attr in attributes) { var cabuilder = GetAttributeBuilder(parser, attr, attributeTargets); if (cabuilder != null) { member.SetCustomAttribute(cabuilder); } } } } internal static void DefineCustomAttributes(PropertyBuilder member, ReadOnlyCollection<AttributeAst> attributes, Parser parser, AttributeTargets attributeTargets) { if (attributes != null) { foreach (var attr in attributes) { var cabuilder = GetAttributeBuilder(parser, attr, attributeTargets); if (cabuilder != null) { member.SetCustomAttribute(cabuilder); } } } } internal static void DefineCustomAttributes(ConstructorBuilder member, ReadOnlyCollection<AttributeAst> attributes, Parser parser, AttributeTargets attributeTargets) { if (attributes != null) { foreach (var attr in attributes) { var cabuilder = GetAttributeBuilder(parser, attr, attributeTargets); if (cabuilder != null) { member.SetCustomAttribute(cabuilder); } } } } internal static void DefineCustomAttributes(MethodBuilder member, ReadOnlyCollection<AttributeAst> attributes, Parser parser, AttributeTargets attributeTargets) { if (attributes != null) { foreach (var attr in attributes) { var cabuilder = GetAttributeBuilder(parser, attr, attributeTargets); if (cabuilder != null) { member.SetCustomAttribute(cabuilder); } } } } internal static void DefineCustomAttributes(EnumBuilder member, ReadOnlyCollection<AttributeAst> attributes, Parser parser, AttributeTargets attributeTargets) { if (attributes != null) { foreach (var attr in attributes) { var cabuilder = GetAttributeBuilder(parser, attr, attributeTargets); if (cabuilder != null) { member.SetCustomAttribute(cabuilder); } } } } private class DefineTypeHelper { private readonly Parser _parser; internal readonly TypeDefinitionAst _typeDefinitionAst; internal readonly TypeBuilder _typeBuilder; internal readonly FieldBuilder _sessionStateField; internal readonly FieldBuilder _sessionStateKeeperField; internal readonly ModuleBuilder _moduleBuilder; internal readonly TypeBuilder _staticHelpersTypeBuilder; private readonly Dictionary<string, PropertyMemberAst> _definedProperties; private readonly Dictionary<string, List<Tuple<FunctionMemberAst, Type[]>>> _definedMethods; internal readonly List<Tuple<string, object>> _fieldsToInitForMemberFunctions; private bool _baseClassHasDefaultCtor; /// <summary> /// If type has fatal errors we cannot construct .NET type from it. /// TypeBuilder.CreateTypeInfo() would throw exception. /// </summary> public bool HasFatalErrors { get; private set; } public DefineTypeHelper(Parser parser, ModuleBuilder module, TypeDefinitionAst typeDefinitionAst, string typeName) { _moduleBuilder = module; _parser = parser; _typeDefinitionAst = typeDefinitionAst; List<Type> interfaces; var baseClass = this.GetBaseTypes(parser, typeDefinitionAst, out interfaces); _typeBuilder = module.DefineType(typeName, Reflection.TypeAttributes.Class | Reflection.TypeAttributes.Public, baseClass, interfaces.ToArray()); _staticHelpersTypeBuilder = module.DefineType(string.Format(CultureInfo.InvariantCulture, "{0}_<staticHelpers>", typeName), Reflection.TypeAttributes.Class); DefineCustomAttributes(_typeBuilder, typeDefinitionAst.Attributes, _parser, AttributeTargets.Class); _typeDefinitionAst.Type = _typeBuilder.AsType(); _fieldsToInitForMemberFunctions = new List<Tuple<string, object>>(); _definedMethods = new Dictionary<string, List<Tuple<FunctionMemberAst, Type[]>>>(StringComparer.OrdinalIgnoreCase); _definedProperties = new Dictionary<string, PropertyMemberAst>(StringComparer.OrdinalIgnoreCase); _sessionStateField = _typeBuilder.DefineField(SessionStateFieldName, typeof(SessionStateInternal), FieldAttributes.Private); _sessionStateKeeperField = _staticHelpersTypeBuilder.DefineField(s_sessionStateKeeperFieldName, typeof(SessionStateKeeper), FieldAttributes.Assembly | FieldAttributes.Static); } /// <summary> /// Return base class type, never return null. /// </summary> /// <param name="parser"></param> /// <param name="typeDefinitionAst"></param> /// <param name="interfaces">return declared interfaces</param> /// <returns></returns> private Type GetBaseTypes(Parser parser, TypeDefinitionAst typeDefinitionAst, out List<Type> interfaces) { // Define base types and report errors. Type baseClass = null; interfaces = new List<Type>(); // Default base class is System.Object and it has a default ctor. _baseClassHasDefaultCtor = true; if (typeDefinitionAst.BaseTypes.Any()) { // base class var baseTypeAsts = typeDefinitionAst.BaseTypes; var firstBaseTypeAst = baseTypeAsts[0]; if (firstBaseTypeAst.TypeName.IsArray) { parser.ReportError(firstBaseTypeAst.Extent, () => ParserStrings.SubtypeArray, firstBaseTypeAst.TypeName.FullName); // fall to the default base type } else { baseClass = firstBaseTypeAst.TypeName.GetReflectionType(); if (baseClass == null) { parser.ReportError(firstBaseTypeAst.Extent, () => ParserStrings.TypeNotFound, firstBaseTypeAst.TypeName.FullName); // fall to the default base type } else { if (baseClass.GetTypeInfo().IsSealed) { parser.ReportError(firstBaseTypeAst.Extent, () => ParserStrings.SealedBaseClass, baseClass.Name); // ignore base type if it's sealed. baseClass = null; } else if (baseClass.GetTypeInfo().IsGenericType && !baseClass.IsConstructedGenericType) { parser.ReportError(firstBaseTypeAst.Extent, () => ParserStrings.SubtypeUnclosedGeneric, baseClass.Name); // ignore base type, we cannot inherit from unclosed generic. baseClass = null; } else if (baseClass.GetTypeInfo().IsInterface) { // First Ast can represent interface as well as BaseClass. interfaces.Add(baseClass); baseClass = null; } } } if (baseClass != null) { // All PS classes are TypeName instances. // For PS classes we cannot use reflection API, because type is not created yet. var baseTypeName = firstBaseTypeAst.TypeName as TypeName; if (baseTypeName != null) { _baseClassHasDefaultCtor = baseTypeName.HasDefaultCtor(); } else { _baseClassHasDefaultCtor = baseClass.HasDefaultCtor(); } } for (int i = 0; i < baseTypeAsts.Count; i++) { if (baseTypeAsts[i].TypeName.IsArray) { parser.ReportError(baseTypeAsts[i].Extent, () => ParserStrings.SubtypeArray, baseTypeAsts[i].TypeName.FullName); this.HasFatalErrors = true; } } for (int i = 1; i < baseTypeAsts.Count; i++) { if (baseTypeAsts[i].TypeName.IsArray) { parser.ReportError(baseTypeAsts[i].Extent, () => ParserStrings.SubtypeArray, baseTypeAsts[i].TypeName.FullName); } else { Type interfaceType = baseTypeAsts[i].TypeName.GetReflectionType(); if (interfaceType == null) { parser.ReportError(baseTypeAsts[i].Extent, () => ParserStrings.TypeNotFound, baseTypeAsts[i].TypeName.FullName); } else { if (interfaceType.GetTypeInfo().IsInterface) { interfaces.Add(interfaceType); } else { parser.ReportError(baseTypeAsts[i].Extent, () => ParserStrings.InterfaceNameExpected, interfaceType.Name); } } } } } return baseClass ?? typeof(object); } public void DefineMembers() { // If user didn't provide any instance ctors or static ctor we will generate default ctor or static ctor respectively. // We can avoid explicit default ctor and static ctor, if we don't have any properties to initialize. bool needStaticCtor = false; bool needDefaultCtor = false; bool hasAnyMethods = false; List<FunctionMemberAst> staticCtors = new List<FunctionMemberAst>(); List<FunctionMemberAst> instanceCtors = new List<FunctionMemberAst>(); foreach (var member in _typeDefinitionAst.Members) { var propertyMemberAst = member as PropertyMemberAst; if (propertyMemberAst != null) { DefineProperty(propertyMemberAst); if (propertyMemberAst.InitialValue != null) { if (propertyMemberAst.IsStatic) { needStaticCtor = true; } else { needDefaultCtor = true; } } } else { FunctionMemberAst method = member as FunctionMemberAst; Diagnostics.Assert(method != null, StringUtil.Format("Unexpected subtype of MemberAst '{0}'. Expect `{1}`", member.GetType().Name, typeof(FunctionMemberAst).GetType().Name)); if (method.IsConstructor) { if (method.IsStatic) { staticCtors.Add(method); } else { instanceCtors.Add(method); } } hasAnyMethods = true; DefineMethod(method); } } // inside ctor we put logic to capture session state from execution context, // we cannot delegate default ctor creation to _typeBuilder, if we have any methods. // If there are only static methods, we still want to capture context to allow static method calls on instances in the right context. if (hasAnyMethods) { needDefaultCtor = true; } if (needStaticCtor) { foreach (var ctor in staticCtors) { var parameters = ((IParameterMetadataProvider)ctor.Body).Parameters; // We report error for static ctors with parameters, even with default values. // We don't take them into account. if (parameters == null || parameters.Count == 0) { needStaticCtor = false; } } } if (needDefaultCtor) { needDefaultCtor = !instanceCtors.Any(); } //// Now we can decide to create explicit default ctors or report error. if (needStaticCtor) { var staticCtorAst = new CompilerGeneratedMemberFunctionAst(PositionUtilities.EmptyExtent, _typeDefinitionAst, SpecialMemberFunctionType.StaticConstructor); DefineConstructor(staticCtorAst, null, true, Reflection.MethodAttributes.Private | Reflection.MethodAttributes.Static, Type.EmptyTypes); } if (_baseClassHasDefaultCtor) { if (needDefaultCtor) { var defaultCtorAst = new CompilerGeneratedMemberFunctionAst(PositionUtilities.EmptyExtent, _typeDefinitionAst, SpecialMemberFunctionType.DefaultConstructor); DefineConstructor(defaultCtorAst, null, true, Reflection.MethodAttributes.Public, Type.EmptyTypes); } } else { if (!instanceCtors.Any()) { _parser.ReportError(_typeDefinitionAst.Extent, () => ParserStrings.BaseClassNoDefaultCtor, _typeBuilder.BaseType.Name); this.HasFatalErrors = true; } } } private void DefineProperty(PropertyMemberAst propertyMemberAst) { if (_definedProperties.ContainsKey(propertyMemberAst.Name)) { _parser.ReportError(propertyMemberAst.Extent, () => ParserStrings.MemberAlreadyDefined, propertyMemberAst.Name); return; } _definedProperties.Add(propertyMemberAst.Name, propertyMemberAst); Type type; if (propertyMemberAst.PropertyType == null) { type = typeof(object); } else { type = propertyMemberAst.PropertyType.TypeName.GetReflectionType(); Diagnostics.Assert(type != null, "Semantic checks should have ensure type can't be null"); } PropertyBuilder property = this.EmitPropertyIl(propertyMemberAst, type); // Define custom attributes on the property, not on the backingField DefineCustomAttributes(property, propertyMemberAst.Attributes, _parser, AttributeTargets.Field | AttributeTargets.Property); } private PropertyBuilder EmitPropertyIl(PropertyMemberAst propertyMemberAst, Type type) { // backing field is always private. var backingFieldAttributes = FieldAttributes.Private; // The property set and property get methods require a special set of attributes. var getSetAttributes = Reflection.MethodAttributes.SpecialName | Reflection.MethodAttributes.HideBySig; getSetAttributes |= propertyMemberAst.IsPublic ? Reflection.MethodAttributes.Public : Reflection.MethodAttributes.Private; if (propertyMemberAst.IsStatic) { backingFieldAttributes |= FieldAttributes.Static; getSetAttributes |= Reflection.MethodAttributes.Static; } // C# naming convention for backing fields. string backingFieldName = String.Format(CultureInfo.InvariantCulture, "<{0}>k__BackingField", propertyMemberAst.Name); var backingField = _typeBuilder.DefineField(backingFieldName, type, backingFieldAttributes); bool hasValidateAttributes = false; if (propertyMemberAst.Attributes != null) { for (int i = 0; i < propertyMemberAst.Attributes.Count; i++) { Type attributeType = propertyMemberAst.Attributes[i].TypeName.GetReflectionAttributeType(); if (attributeType != null && attributeType.IsSubclassOf(typeof(ValidateArgumentsAttribute))) { hasValidateAttributes = true; break; } } } // The last argument of DefineProperty is null, because the property has no parameters. PropertyBuilder property = _typeBuilder.DefineProperty(propertyMemberAst.Name, Reflection.PropertyAttributes.None, type, null); // Define the "get" accessor method. MethodBuilder getMethod = _typeBuilder.DefineMethod(String.Concat("get_", propertyMemberAst.Name), getSetAttributes, type, Type.EmptyTypes); ILGenerator getIlGen = getMethod.GetILGenerator(); if (propertyMemberAst.IsStatic) { // static getIlGen.Emit(OpCodes.Ldsfld, backingField); getIlGen.Emit(OpCodes.Ret); } else { // instance getIlGen.Emit(OpCodes.Ldarg_0); getIlGen.Emit(OpCodes.Ldfld, backingField); getIlGen.Emit(OpCodes.Ret); } // Define the "set" accessor method. MethodBuilder setMethod = _typeBuilder.DefineMethod(String.Concat("set_", propertyMemberAst.Name), getSetAttributes, null, new Type[] { type }); ILGenerator setIlGen = setMethod.GetILGenerator(); if (hasValidateAttributes) { var typeToLoad = _typeBuilder.AsType(); setIlGen.Emit(OpCodes.Ldtoken, typeToLoad); setIlGen.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle")); // load current Type on stack setIlGen.Emit(OpCodes.Ldstr, propertyMemberAst.Name); // load name of Property setIlGen.Emit(propertyMemberAst.IsStatic ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1); // load set value if (type.GetTypeInfo().IsValueType) { setIlGen.Emit(OpCodes.Box, type); } setIlGen.Emit(OpCodes.Call, CachedReflectionInfo.ClassOps_ValidateSetProperty); } if (propertyMemberAst.IsStatic) { setIlGen.Emit(OpCodes.Ldarg_0); setIlGen.Emit(OpCodes.Stsfld, backingField); } else { setIlGen.Emit(OpCodes.Ldarg_0); setIlGen.Emit(OpCodes.Ldarg_1); setIlGen.Emit(OpCodes.Stfld, backingField); } setIlGen.Emit(OpCodes.Ret); // Map the two methods created above to our PropertyBuilder to // their corresponding behaviors, "get" and "set" respectively. property.SetGetMethod(getMethod); property.SetSetMethod(setMethod); if (propertyMemberAst.IsHidden) { property.SetCustomAttribute(s_hiddenCustomAttributeBuilder); } return property; } private bool CheckForDuplicateOverload(FunctionMemberAst functionMemberAst, Type[] newParameters) { List<Tuple<FunctionMemberAst, Type[]>> overloads; if (!_definedMethods.TryGetValue(functionMemberAst.Name, out overloads)) { overloads = new List<Tuple<FunctionMemberAst, Type[]>>(); _definedMethods.Add(functionMemberAst.Name, overloads); } else { foreach (var overload in overloads) { var overloadParameters = overload.Item2; // This test won't be correct when defaults are supported if (newParameters.Length != overloadParameters.Length) { continue; } var sameSignature = true; for (int i = 0; i < newParameters.Length; i++) { if (newParameters[i] != overloadParameters[i]) { sameSignature = false; break; } } if (sameSignature) { // If both are both static/instance, it's an error. // Otherwise, signatures can match only for the constructor. if (overload.Item1.IsStatic == functionMemberAst.IsStatic || !functionMemberAst.IsConstructor) { _parser.ReportError(functionMemberAst.NameExtent ?? functionMemberAst.Extent, () => ParserStrings.MemberAlreadyDefined, functionMemberAst.Name); return true; } } } } overloads.Add(Tuple.Create(functionMemberAst, newParameters)); return false; } private Type[] GetParameterTypes(FunctionMemberAst functionMemberAst) { var parameters = ((IParameterMetadataProvider)functionMemberAst).Parameters; if (parameters == null) { return PSTypeExtensions.EmptyTypes; } bool anyErrors = false; var result = new Type[parameters.Count]; for (var i = 0; i < parameters.Count; i++) { var typeConstraint = parameters[i].Attributes.OfType<TypeConstraintAst>().FirstOrDefault(); var paramType = (typeConstraint != null) ? typeConstraint.TypeName.GetReflectionType() : typeof(object); if (paramType == null) { _parser.ReportError(typeConstraint.Extent, () => ParserStrings.TypeNotFound, typeConstraint.TypeName.FullName); anyErrors = true; } else if (paramType == typeof(void) || paramType.GetTypeInfo().IsGenericTypeDefinition) { _parser.ReportError(typeConstraint.Extent, () => ParserStrings.TypeNotAllowedForParameter, typeConstraint.TypeName.FullName); anyErrors = true; } result[i] = paramType; } return anyErrors ? null : result; } private bool MethodExistsOnBaseClassAndFinal(string methodName, Type[] parameterTypes) { TypeInfo baseType = _typeBuilder.BaseType.GetTypeInfo(); // If baseType is PS class, then method will be virtual, once we define it. if (baseType is TypeBuilder) { return false; } var mi = baseType.AsType().GetMethod(methodName, parameterTypes); return mi != null && mi.IsFinal; } private void DefineMethod(FunctionMemberAst functionMemberAst) { var parameterTypes = GetParameterTypes(functionMemberAst); if (parameterTypes == null) { // There must have been an error, just return return; } if (CheckForDuplicateOverload(functionMemberAst, parameterTypes)) { return; } if (functionMemberAst.IsConstructor) { var methodAttributes = Reflection.MethodAttributes.Public; if (functionMemberAst.IsStatic) { var parameters = functionMemberAst.Parameters; if (parameters.Count > 0) { _parser.ReportError(Parser.ExtentOf(parameters.First(), parameters.Last()), () => ParserStrings.StaticConstructorCantHaveParameters); return; } methodAttributes |= Reflection.MethodAttributes.Static; } DefineConstructor(functionMemberAst, functionMemberAst.Attributes, functionMemberAst.IsHidden, methodAttributes, parameterTypes); return; } var attributes = functionMemberAst.IsPublic ? Reflection.MethodAttributes.Public : Reflection.MethodAttributes.Private; if (functionMemberAst.IsStatic) { attributes |= Reflection.MethodAttributes.Static; } else { if (this.MethodExistsOnBaseClassAndFinal(functionMemberAst.Name, parameterTypes)) { attributes |= Reflection.MethodAttributes.HideBySig; attributes |= Reflection.MethodAttributes.NewSlot; } attributes |= Reflection.MethodAttributes.Virtual; } var returnType = functionMemberAst.GetReturnType(); if (returnType == null) { _parser.ReportError(functionMemberAst.ReturnType.Extent, () => ParserStrings.TypeNotFound, functionMemberAst.ReturnType.TypeName.FullName); return; } var method = _typeBuilder.DefineMethod(functionMemberAst.Name, attributes, returnType, parameterTypes); DefineCustomAttributes(method, functionMemberAst.Attributes, _parser, AttributeTargets.Method); if (functionMemberAst.IsHidden) { method.SetCustomAttribute(s_hiddenCustomAttributeBuilder); } var ilGenerator = method.GetILGenerator(); DefineMethodBody(functionMemberAst, ilGenerator, GetMetaDataName(method.Name, parameterTypes.Count()), functionMemberAst.IsStatic, parameterTypes, returnType, (i, n) => method.DefineParameter(i, ParameterAttributes.None, n)); } private void DefineConstructor(IParameterMetadataProvider ipmp, ReadOnlyCollection<AttributeAst> attributeAsts, bool isHidden, Reflection.MethodAttributes methodAttributes, Type[] parameterTypes) { bool isStatic = (methodAttributes & Reflection.MethodAttributes.Static) != 0; var ctor = isStatic ? _typeBuilder.DefineTypeInitializer() : _typeBuilder.DefineConstructor(methodAttributes, CallingConventions.Standard, parameterTypes); DefineCustomAttributes(ctor, attributeAsts, _parser, AttributeTargets.Constructor); if (isHidden) { ctor.SetCustomAttribute(s_hiddenCustomAttributeBuilder); } var ilGenerator = ctor.GetILGenerator(); if (!isStatic) { ilGenerator.Emit(OpCodes.Ldarg_0); // load 'this' on stack for Stfld call ilGenerator.Emit(OpCodes.Ldnull); ilGenerator.Emit(OpCodes.Ldfld, _sessionStateKeeperField); ilGenerator.EmitCall(OpCodes.Call, s_sessionStateKeeper_GetSessionState, null); // load 'sessionState' on stack for Stfld call ilGenerator.Emit(OpCodes.Stfld, _sessionStateField); } DefineMethodBody(ipmp, ilGenerator, GetMetaDataName(ctor.Name, parameterTypes.Count()), isStatic, parameterTypes, typeof(void), (i, n) => ctor.DefineParameter(i, ParameterAttributes.None, n)); } private string GetMetaDataName(string name, int numberOfParameters) { int currentId = Interlocked.Increment(ref s_globalCounter); string metaDataName = name + "_" + numberOfParameters + "_" + currentId; return metaDataName; } private void DefineMethodBody( IParameterMetadataProvider ipmp, ILGenerator ilGenerator, string metadataToken, bool isStatic, Type[] parameterTypes, Type returnType, Action<int, string> parameterNameSetter) { var wrapperFieldName = string.Format(CultureInfo.InvariantCulture, "<{0}>", metadataToken); var scriptBlockWrapperField = _staticHelpersTypeBuilder.DefineField(wrapperFieldName, typeof(ScriptBlockMemberMethodWrapper), FieldAttributes.Assembly | FieldAttributes.Static); ilGenerator.Emit(OpCodes.Ldsfld, scriptBlockWrapperField); if (isStatic) { ilGenerator.Emit(OpCodes.Ldnull); // pass null (no this) ilGenerator.Emit(OpCodes.Ldnull); // pass null (no sessionStateInternal) } else { EmitLdarg(ilGenerator, 0); // pass this ilGenerator.Emit(OpCodes.Ldarg_0); // pass 'this' for Ldfld call ilGenerator.Emit(OpCodes.Ldfld, _sessionStateField); // pass sessionStateInternal } int parameterCount = parameterTypes.Length; if (parameterCount > 0) { var parameters = ipmp.Parameters; var local = ilGenerator.DeclareLocal(typeof(object[])); EmitLdc(ilGenerator, parameterCount); // Create an array to hold all ilGenerator.Emit(OpCodes.Newarr, typeof(object)); // of the parameters ilGenerator.Emit(OpCodes.Stloc, local); // Save array for repeated use int j = isStatic ? 0 : 1; for (int i = 0; i < parameterCount; i++, j++) { ilGenerator.Emit(OpCodes.Ldloc, local); // load array EmitLdc(ilGenerator, i); // index to save at EmitLdarg(ilGenerator, j); // load argument (skipping this) if (parameterTypes[i].GetTypeInfo().IsValueType) // value types must be boxed { ilGenerator.Emit(OpCodes.Box, parameterTypes[i]); } ilGenerator.Emit(OpCodes.Stelem_Ref); // save the argument in the array // Set the parameter name, mostly for Get-Member // Parameters are indexed beginning with the number 1 for the first parameter parameterNameSetter(i + 1, parameters[i].Name.VariablePath.UserPath); } ilGenerator.Emit(OpCodes.Ldloc, local); // load array } else { ilGenerator.Emit(OpCodes.Ldsfld, typeof(ScriptBlockMemberMethodWrapper).GetField("_emptyArgumentArray", BindingFlags.Static | BindingFlags.Public)); } MethodInfo invokeHelper; if (returnType == typeof(void)) { invokeHelper = typeof(ScriptBlockMemberMethodWrapper).GetMethod("InvokeHelper", BindingFlags.Instance | BindingFlags.Public); } else { invokeHelper = typeof(ScriptBlockMemberMethodWrapper).GetMethod("InvokeHelperT", BindingFlags.Instance | BindingFlags.Public).MakeGenericMethod(returnType); } ilGenerator.Emit(OpCodes.Tailcall); ilGenerator.EmitCall(OpCodes.Call, invokeHelper, null); ilGenerator.Emit(OpCodes.Ret); var methodWrapper = new ScriptBlockMemberMethodWrapper(ipmp); _fieldsToInitForMemberFunctions.Add(Tuple.Create(wrapperFieldName, (object)methodWrapper)); } } private class DefineEnumHelper { private readonly Parser _parser; private readonly TypeDefinitionAst _enumDefinitionAst; private readonly ModuleBuilder _moduleBuilder; private readonly string _typeName; internal DefineEnumHelper(Parser parser, ModuleBuilder module, TypeDefinitionAst enumDefinitionAst, string typeName) { _parser = parser; _enumDefinitionAst = enumDefinitionAst; _moduleBuilder = module; _typeName = typeName; } internal static List<DefineEnumHelper> Sort(List<DefineEnumHelper> defineEnumHelpers, Parser parser) { // This function does a topological sort of the enums to be defined. This is needed so we // can allow one enum member to use the value of another w/o needing to worry about the order // they are declared in. For example: // // enum E1 { e1 = [E2]::e2 } // enum E2 { e2 = 42 } // // We also want to report an error for recursive expressions, e.g. // // enum E1 { e1 = [E2]::e2 } // enum E2 { e2 = [E1]::e1 } // // Note that this code is not as permissive as it could be, e.g. we could (but do not) allow: // // enum E1 { e1 = [E2]::e2 } // enum E2 { // e2 = 42 // e2a = [E1]::e1 // } // // In this case, there is no cycle in the constant values despite E1 referencing E2 and vice versa. // // The basic algorithm is to create a graph where the edges represent a dependency, using this example: // // enum E1 { e1 = [E2]::e2 } // enum E2 { e2 = 42 } // // We have an edge E1->E2. E2 has no dependencies. if (defineEnumHelpers.Count == 1) { return defineEnumHelpers; } // There won't be many nodes in our graph, so we just use a dictionary with a list of edges instead // of something cleaner. var graph = new Dictionary<TypeDefinitionAst, Tuple<DefineEnumHelper, List<TypeDefinitionAst>>>(); // Add all of our nodes to the graph foreach (var helper in defineEnumHelpers) { graph.Add(helper._enumDefinitionAst, Tuple.Create(helper, new List<TypeDefinitionAst>())); } // Now find any edges. foreach (var helper in defineEnumHelpers) { foreach (var enumerator in helper._enumDefinitionAst.Members) { var initExpr = ((PropertyMemberAst)enumerator).InitialValue; if (initExpr == null) { // No initializer, so no dependency (this is incorrect assumption if // we wanted to be more general like C#.) continue; } // The expression may have multiple member expressions, e.g. [E]::e1 + [E]::e2 foreach (var memberExpr in initExpr.FindAll(ast => ast is MemberExpressionAst, false)) { var typeExpr = ((MemberExpressionAst)memberExpr).Expression as TypeExpressionAst; if (typeExpr != null) { // We only want to add edges for enums being defined in the current scope. // We detect this by seeing if the ast is in our graph or not. var typeName = typeExpr.TypeName as TypeName; if (typeName != null && typeName._typeDefinitionAst != null && typeName._typeDefinitionAst != helper._enumDefinitionAst // Don't add self edges && graph.ContainsKey(typeName._typeDefinitionAst)) { var edgeList = graph[helper._enumDefinitionAst].Item2; if (!edgeList.Contains(typeName._typeDefinitionAst)) // Only add 1 edge per enum { edgeList.Add(typeName._typeDefinitionAst); } } } } } } // Our graph is built. The ready list will hold nodes that don't depend on anything not already // in the result list. We start with a list of nodes with no edges (no dependencies). var result = new List<DefineEnumHelper>(defineEnumHelpers.Count); var readyList = new List<DefineEnumHelper>(defineEnumHelpers.Count); readyList.AddRange(from value in graph.Values where value.Item2.Count == 0 select value.Item1); while (readyList.Count > 0) { var node = readyList[readyList.Count - 1]; readyList.RemoveAt(readyList.Count - 1); result.Add(node); // Remove all edges to this node as it is in our result list now. foreach (var value in graph.Values) { value.Item2.Remove(node._enumDefinitionAst); // If we removed the last edge, we can put this node on the ready list (assuming it // wasn't already there or in our result list.) if (value.Item2.Count == 0 && !result.Contains(value.Item1) && !readyList.Contains(value.Item1)) { readyList.Add(value.Item1); } } } if (result.Count < defineEnumHelpers.Count) { // There was a cycle, report an error on each enum. foreach (var helper in defineEnumHelpers) { if (!result.Contains(helper)) { parser.ReportError(helper._enumDefinitionAst.Extent, () => ParserStrings.CycleInEnumInitializers); } } } else { Diagnostics.Assert(result.Count == defineEnumHelpers.Count, "Logic error if we have more outgoing results than incoming"); } return result; } internal void DefineEnum() { var definedEnumerators = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var enumBuilder = _moduleBuilder.DefineEnum(_typeName, Reflection.TypeAttributes.Public, typeof(int)); DefineCustomAttributes(enumBuilder, _enumDefinitionAst.Attributes, _parser, AttributeTargets.Enum); int value = 0; bool valueTooBig = false; foreach (var member in _enumDefinitionAst.Members) { var enumerator = (PropertyMemberAst)member; if (enumerator.InitialValue != null) { object constValue; if (IsConstantValueVisitor.IsConstant(enumerator.InitialValue, out constValue, false, false)) { if (constValue is int) { value = (int)constValue; } else { if (!LanguagePrimitives.TryConvertTo(constValue, out value)) { if (constValue != null && LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(constValue.GetType()))) { _parser.ReportError(enumerator.InitialValue.Extent, () => ParserStrings.EnumeratorValueTooLarge); } else { _parser.ReportError(enumerator.InitialValue.Extent, () => ParserStrings.CannotConvertValue, ToStringCodeMethods.Type(typeof(int))); } } } } else { _parser.ReportError(enumerator.InitialValue.Extent, () => ParserStrings.EnumeratorValueMustBeConstant); } } else if (valueTooBig) { _parser.ReportError(enumerator.Extent, () => ParserStrings.EnumeratorValueTooLarge); } if (definedEnumerators.Contains(enumerator.Name)) { _parser.ReportError(enumerator.Extent, () => ParserStrings.MemberAlreadyDefined, enumerator.Name); } else { definedEnumerators.Add(enumerator.Name); enumBuilder.DefineLiteral(enumerator.Name, value); if (value < int.MaxValue) { value += 1; valueTooBig = false; } else { valueTooBig = true; } } } _enumDefinitionAst.Type = enumBuilder.CreateTypeInfo().AsType(); } } private static IEnumerable<CustomAttributeBuilder> GetAssemblyAttributeBuilders() { yield return new CustomAttributeBuilder(typeof(DynamicClassImplementationAssemblyAttribute).GetConstructor(Type.EmptyTypes), s_emptyArgArray); } internal static Assembly DefineTypes(Parser parser, Ast rootAst, TypeDefinitionAst[] typeDefinitions) { Diagnostics.Assert(rootAst.Parent == null, "Caller should only define types from the root ast"); var definedTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase); // First character is a special mark that allows us to cheaply ignore dynamic generated assemblies in ClrFacede.GetAssemblies() // Two replaces at the end are for not-allowed characters. They are replaced by similar-looking chars. string assemblyName = ClrFacade.FIRST_CHAR_PSASSEMBLY_MARK + (string.IsNullOrWhiteSpace(rootAst.Extent.File) ? "powershell" : rootAst.Extent.File .Replace('\\', (char)0x29f9) .Replace('/', (char)0x29f9) .Replace(':', (char)0x0589)); var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.RunAndCollect, GetAssemblyAttributeBuilders()); var module = assembly.DefineDynamicModule(assemblyName); var defineTypeHelpers = new List<DefineTypeHelper>(); var defineEnumHelpers = new List<DefineEnumHelper>(); foreach (var typeDefinitionAst in typeDefinitions) { var typeName = GetClassNameInAssembly(typeDefinitionAst); if (!definedTypes.Contains(typeName)) { definedTypes.Add(typeName); if ((typeDefinitionAst.TypeAttributes & TypeAttributes.Class) == TypeAttributes.Class) { defineTypeHelpers.Add(new DefineTypeHelper(parser, module, typeDefinitionAst, typeName)); } else if ((typeDefinitionAst.TypeAttributes & TypeAttributes.Enum) == TypeAttributes.Enum) { defineEnumHelpers.Add(new DefineEnumHelper(parser, module, typeDefinitionAst, typeName)); } } } // Define enums before classes so members of classes can use these enum types. defineEnumHelpers = DefineEnumHelper.Sort(defineEnumHelpers, parser); foreach (var helper in defineEnumHelpers) { helper.DefineEnum(); } foreach (var helper in defineTypeHelpers) { helper.DefineMembers(); } foreach (var helper in defineTypeHelpers) { Diagnostics.Assert(helper._typeDefinitionAst.Type.GetTypeInfo() is TypeBuilder, "Type should be the TypeBuilder"); bool runtimeTypeAssigned = false; if (!helper.HasFatalErrors) { try { var type = helper._typeBuilder.CreateTypeInfo().AsType(); helper._typeDefinitionAst.Type = type; runtimeTypeAssigned = true; var helperType = helper._staticHelpersTypeBuilder.CreateTypeInfo().AsType(); if (helper._fieldsToInitForMemberFunctions != null) { foreach (var tuple in helper._fieldsToInitForMemberFunctions) { helperType.GetField(tuple.Item1, BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, tuple.Item2); } } helperType.GetField(s_sessionStateKeeperFieldName, BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, new SessionStateKeeper()); } catch (TypeLoadException e) { // This is a cheap way to get error messages about non-implemented abstract/interface methods (and maybe some other errors). // We use .NET API to perform this check during type creation. // // Presumably this catch could go away when we will not create Type at parse time. // Error checking should be moved/added to semantic checks. parser.ReportError(helper._typeDefinitionAst.Extent, () => ParserStrings.TypeCreationError, helper._typeBuilder.Name, e.Message); } } if (!runtimeTypeAssigned) { // Clean up ast helper._typeDefinitionAst.Type = null; } } return assembly; } private static string GetClassNameInAssembly(TypeDefinitionAst typeDefinitionAst) { // Only allocate a list if necessary - in the most common case, we don't need it. List<string> nameParts = null; var parent = typeDefinitionAst.Parent; while (parent.Parent != null) { if (parent is IParameterMetadataProvider) { nameParts = nameParts ?? new List<string>(); var fnDefn = parent.Parent as FunctionDefinitionAst; if (fnDefn != null) { parent = fnDefn; nameParts.Add(fnDefn.Name); } else { nameParts.Add("<" + parent.Extent.Text.GetHashCode().ToString("x", CultureInfo.InvariantCulture) + ">"); } } parent = parent.Parent; } if (nameParts == null) { return typeDefinitionAst.Name; } nameParts.Reverse(); nameParts.Add(typeDefinitionAst.Name); return string.Join(".", nameParts); } private static OpCode[] s_ldc = { OpCodes.Ldc_I4_0, OpCodes.Ldc_I4_1, OpCodes.Ldc_I4_2, OpCodes.Ldc_I4_3, OpCodes.Ldc_I4_4, OpCodes.Ldc_I4_5, OpCodes.Ldc_I4_6, OpCodes.Ldc_I4_7, OpCodes.Ldc_I4_8 }; private static void EmitLdc(ILGenerator emitter, int c) { if (c < s_ldc.Length) { emitter.Emit(s_ldc[c]); } else { emitter.Emit(OpCodes.Ldc_I4, c); } } private static OpCode[] s_ldarg = { OpCodes.Ldarg_0, OpCodes.Ldarg_1, OpCodes.Ldarg_2, OpCodes.Ldarg_3 }; private static void EmitLdarg(ILGenerator emitter, int c) { if (c < s_ldarg.Length) { emitter.Emit(s_ldarg[c]); } else { emitter.Emit(OpCodes.Ldarg, c); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Dynamic.Utils; namespace System.Linq.Expressions { /// <summary> /// Specifies what kind of jump this <see cref="GotoExpression"/> represents. /// </summary> public enum GotoExpressionKind { /// <summary> /// A <see cref="GotoExpression"/> that represents a jump to some location. /// </summary> Goto, /// <summary> /// A <see cref="GotoExpression"/> that represents a return statement. /// </summary> Return, /// <summary> /// A <see cref="GotoExpression"/> that represents a break statement. /// </summary> Break, /// <summary> /// A <see cref="GotoExpression"/> that represents a continue statement. /// </summary> Continue, } /// <summary> /// Represents an unconditional jump. This includes return statements, break and continue statements, and other jumps. /// </summary> [DebuggerTypeProxy(typeof(Expression.GotoExpressionProxy))] public sealed class GotoExpression : Expression { private readonly GotoExpressionKind _kind; private readonly Expression _value; private readonly LabelTarget _target; private readonly Type _type; internal GotoExpression(GotoExpressionKind kind, LabelTarget target, Expression value, Type type) { _kind = kind; _value = value; _target = target; _type = type; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return _type; } } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Goto; } } /// <summary> /// The value passed to the target, or null if the target is of type /// System.Void. /// </summary> public Expression Value { get { return _value; } } /// <summary> /// The target label where this node jumps to. /// </summary> public LabelTarget Target { get { return _target; } } /// <summary> /// The kind of the goto. For information purposes only. /// </summary> public GotoExpressionKind Kind { get { return _kind; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitGoto(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="target">The <see cref="Target" /> property of the result.</param> /// <param name="value">The <see cref="Value" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public GotoExpression Update(LabelTarget target, Expression value) { if (target == Target && value == Value) { return this; } return Expression.MakeGoto(Kind, target, value, Type); } } public partial class Expression { /// <summary> /// Creates a <see cref="GotoExpression"/> representing a break statement. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Break(LabelTarget target) { return MakeGoto(GotoExpressionKind.Break, target, null, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a break statement. The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Break(LabelTarget target, Expression value) { return MakeGoto(GotoExpressionKind.Break, target, value, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a break statement with the specified type. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>. /// </returns> public static GotoExpression Break(LabelTarget target, Type type) { return MakeGoto(GotoExpressionKind.Break, target, null, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a break statement with the specified type. /// The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Break(LabelTarget target, Expression value, Type type) { return MakeGoto(GotoExpressionKind.Break, target, value, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a continue statement. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Continue(LabelTarget target) { return MakeGoto(GotoExpressionKind.Continue, target, null, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a continue statement with the specified type. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Continue(LabelTarget target, Type type) { return MakeGoto(GotoExpressionKind.Continue, target, null, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a return statement. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Return, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Return(LabelTarget target) { return MakeGoto(GotoExpressionKind.Return, target, null, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a return statement with the specified type. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Return, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Return(LabelTarget target, Type type) { return MakeGoto(GotoExpressionKind.Return, target, null, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a return statement. The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Return(LabelTarget target, Expression value) { return MakeGoto(GotoExpressionKind.Return, target, value, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a return statement with the specified type. /// The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Return(LabelTarget target, Expression value, Type type) { return MakeGoto(GotoExpressionKind.Return, target, value, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a goto. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto, /// the <see cref="P:GotoExpression.Target"/> property set to the specified value, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Goto(LabelTarget target) { return MakeGoto(GotoExpressionKind.Goto, target, null, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a goto with the specified type. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto, /// the <see cref="P:GotoExpression.Target"/> property set to the specified value, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Goto(LabelTarget target, Type type) { return MakeGoto(GotoExpressionKind.Goto, target, null, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a goto. The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Goto(LabelTarget target, Expression value) { return MakeGoto(GotoExpressionKind.Goto, target, value, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a goto with the specified type. /// The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Goto(LabelTarget target, Expression value, Type type) { return MakeGoto(GotoExpressionKind.Goto, target, value, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a jump of the specified <see cref="GotoExpressionKind"/>. /// The value passed to the label upon jumping can also be specified. /// </summary> /// <param name="kind">The <see cref="GotoExpressionKind"/> of the <see cref="GotoExpression"/>.</param> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to <paramref name="kind"/>, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression MakeGoto(GotoExpressionKind kind, LabelTarget target, Expression value, Type type) { ValidateGoto(target, ref value, nameof(target), nameof(value), type); return new GotoExpression(kind, target, value, type); } private static void ValidateGoto(LabelTarget target, ref Expression value, string targetParameter, string valueParameter, Type type) { ContractUtils.RequiresNotNull(target, targetParameter); if (value == null) { if (target.Type != typeof(void)) throw Error.LabelMustBeVoidOrHaveExpression(nameof(target)); if (type != null) { TypeUtils.ValidateType(type, nameof(type)); if (type.IsByRef) { throw Error.TypeMustNotBeByRef(nameof(type)); } if (type.IsPointer) { throw Error.TypeMustNotBePointer(nameof(type)); } } } else { ValidateGotoType(target.Type, ref value, valueParameter); } } // Standard argument validation, taken from ValidateArgumentTypes private static void ValidateGotoType(Type expectedType, ref Expression value, string paramName) { RequiresCanRead(value, paramName); if (expectedType != typeof(void)) { if (!TypeUtils.AreReferenceAssignable(expectedType, value.Type)) { // C# auto-quotes return values, so we'll do that here if (!TryQuote(expectedType, ref value)) { throw Error.ExpressionTypeDoesNotMatchLabel(value.Type, expectedType); } } } } } }
#define USE_INTERPOLATION // // By Anomalous Underdog, 2011 // // Based on code made by Forest Johnson (Yoggy) and xyber // using UnityEngine; using System.Collections; using System.Collections.Generic; public class MeleeWeaponTrail : MonoBehaviour { [SerializeField] bool _emit = true; public bool Emit { set{_emit = value;} } bool _use = true; public bool Use { set{_use = value;} } [SerializeField] float _emitTime = 0.0f; [SerializeField] Material _material; [SerializeField] float _lifeTime = 1.0f; [SerializeField] Color[] _colors; [SerializeField] float[] _sizes; [SerializeField] float _minVertexDistance = 0.1f; [SerializeField] float _maxVertexDistance = 10.0f; float _minVertexDistanceSqr = 0.0f; float _maxVertexDistanceSqr = 0.0f; [SerializeField] float _maxAngle = 3.00f; [SerializeField] bool _autoDestruct = false; #if USE_INTERPOLATION [SerializeField] int subdivisions = 4; #endif [SerializeField] Transform _base; [SerializeField] Transform _tip; List<Point> _points = new List<Point>(); #if USE_INTERPOLATION List<Point> _smoothedPoints = new List<Point>(); #endif GameObject _trailObject; Mesh _trailMesh; Vector3 _lastPosition; [System.Serializable] public class Point { public float timeCreated = 0.0f; public Vector3 basePosition; public Vector3 tipPosition; } void Start() { _lastPosition = transform.position; _trailObject = new GameObject("Trail"); _trailObject.transform.parent = null; _trailObject.transform.position = Vector3.zero; _trailObject.transform.rotation = Quaternion.identity; _trailObject.transform.localScale = Vector3.one; _trailObject.AddComponent(typeof(MeshFilter)); _trailObject.AddComponent(typeof(MeshRenderer)); _trailObject.renderer.material = _material; _trailMesh = new Mesh(); _trailMesh.name = name + "TrailMesh"; _trailObject.GetComponent<MeshFilter>().mesh = _trailMesh; _minVertexDistanceSqr = _minVertexDistance * _minVertexDistance; _maxVertexDistanceSqr = _maxVertexDistance * _maxVertexDistance; } void OnDisable() { Destroy(_trailObject); } void Update() { if (!_use) { return; } if (_emit && _emitTime != 0) { _emitTime -= Time.deltaTime; if (_emitTime == 0) _emitTime = -1; if (_emitTime < 0) _emit = false; } if (!_emit && _points.Count == 0 && _autoDestruct) { Destroy(_trailObject); Destroy(gameObject); } // early out if there is no camera if (!Camera.main) return; // if we have moved enough, create a new vertex and make sure we rebuild the mesh float theDistanceSqr = (_lastPosition - transform.position).sqrMagnitude; if (_emit) { if (theDistanceSqr > _minVertexDistanceSqr) { bool make = false; if (_points.Count < 3) { make = true; } else { //Vector3 l1 = _points[_points.Count - 2].basePosition - _points[_points.Count - 3].basePosition; //Vector3 l2 = _points[_points.Count - 1].basePosition - _points[_points.Count - 2].basePosition; Vector3 l1 = _points[_points.Count - 2].tipPosition - _points[_points.Count - 3].tipPosition; Vector3 l2 = _points[_points.Count - 1].tipPosition - _points[_points.Count - 2].tipPosition; if (Vector3.Angle(l1, l2) > _maxAngle || theDistanceSqr > _maxVertexDistanceSqr) make = true; } if (make) { Point p = new Point(); p.basePosition = _base.position; p.tipPosition = _tip.position; p.timeCreated = Time.time; _points.Add(p); _lastPosition = transform.position; #if USE_INTERPOLATION if (_points.Count == 1) { _smoothedPoints.Add(p); } else if (_points.Count > 1) { // add 1+subdivisions for every possible pair in the _points for (int n = 0; n < 1+subdivisions; ++n) _smoothedPoints.Add(p); } // we use 4 control points for the smoothing if (_points.Count >= 4) { Vector3[] tipPoints = new Vector3[4]; tipPoints[0] = _points[_points.Count - 4].tipPosition; tipPoints[1] = _points[_points.Count - 3].tipPosition; tipPoints[2] = _points[_points.Count - 2].tipPosition; tipPoints[3] = _points[_points.Count - 1].tipPosition; //IEnumerable<Vector3> smoothTip = Interpolate.NewBezier(Interpolate.Ease(Interpolate.EaseType.Linear), tipPoints, subdivisions); IEnumerable<Vector3> smoothTip = Interpolate.NewCatmullRom(tipPoints, subdivisions, false); Vector3[] basePoints = new Vector3[4]; basePoints[0] = _points[_points.Count - 4].basePosition; basePoints[1] = _points[_points.Count - 3].basePosition; basePoints[2] = _points[_points.Count - 2].basePosition; basePoints[3] = _points[_points.Count - 1].basePosition; //IEnumerable<Vector3> smoothBase = Interpolate.NewBezier(Interpolate.Ease(Interpolate.EaseType.Linear), basePoints, subdivisions); IEnumerable<Vector3> smoothBase = Interpolate.NewCatmullRom(basePoints, subdivisions, false); List<Vector3> smoothTipList = new List<Vector3>(smoothTip); List<Vector3> smoothBaseList = new List<Vector3>(smoothBase); float firstTime = _points[_points.Count - 4].timeCreated; float secondTime = _points[_points.Count - 1].timeCreated; //Debug.Log(" smoothTipList.Count: " + smoothTipList.Count); for (int n = 0; n < smoothTipList.Count; ++n) { int idx = _smoothedPoints.Count - (smoothTipList.Count-n); // there are moments when the _smoothedPoints are lesser // than what is required, when elements from it are removed if (idx > -1 && idx < _smoothedPoints.Count) { Point sp = new Point(); sp.basePosition = smoothBaseList[n]; sp.tipPosition = smoothTipList[n]; sp.timeCreated = Mathf.Lerp(firstTime, secondTime, (float)n/smoothTipList.Count); _smoothedPoints[idx] = sp; } //else //{ // Debug.LogError(idx + "/" + _smoothedPoints.Count); //} } } #endif } else { _points[_points.Count - 1].basePosition = _base.position; _points[_points.Count - 1].tipPosition = _tip.position; //_points[_points.Count - 1].timeCreated = Time.time; #if USE_INTERPOLATION _smoothedPoints[_smoothedPoints.Count - 1].basePosition = _base.position; _smoothedPoints[_smoothedPoints.Count - 1].tipPosition = _tip.position; #endif } } else { if (_points.Count > 0) { _points[_points.Count - 1].basePosition = _base.position; _points[_points.Count - 1].tipPosition = _tip.position; //_points[_points.Count - 1].timeCreated = Time.time; } #if USE_INTERPOLATION if (_smoothedPoints.Count > 0) { _smoothedPoints[_smoothedPoints.Count - 1].basePosition = _base.position; _smoothedPoints[_smoothedPoints.Count - 1].tipPosition = _tip.position; } #endif } } RemoveOldPoints(_points); if (_points.Count == 0) { _trailMesh.Clear(); } #if USE_INTERPOLATION RemoveOldPoints(_smoothedPoints); if (_smoothedPoints.Count == 0) { _trailMesh.Clear(); } #endif #if USE_INTERPOLATION List<Point> pointsToUse = _smoothedPoints; #else List<Point> pointsToUse = _points; #endif if (pointsToUse.Count > 1) { Vector3[] newVertices = new Vector3[pointsToUse.Count * 2]; Vector2[] newUV = new Vector2[pointsToUse.Count * 2]; int[] newTriangles = new int[(pointsToUse.Count - 1) * 6]; Color[] newColors = new Color[pointsToUse.Count * 2]; for (int n = 0; n < pointsToUse.Count; ++n) { Point p = pointsToUse[n]; float time = (Time.time - p.timeCreated) / _lifeTime; Color color = Color.Lerp(Color.white, Color.clear, time); if (_colors != null && _colors.Length > 0) { float colorTime = time * (_colors.Length - 1); float min = Mathf.Floor(colorTime); float max = Mathf.Clamp(Mathf.Ceil(colorTime), 1, _colors.Length - 1); float lerp = Mathf.InverseLerp(min, max, colorTime); if (min >= _colors.Length) min = _colors.Length - 1; if (min < 0) min = 0; if (max >= _colors.Length) max = _colors.Length - 1; if (max < 0) max = 0; color = Color.Lerp(_colors[(int)min], _colors[(int)max], lerp); } float size = 0f; if (_sizes != null && _sizes.Length > 0) { float sizeTime = time * (_sizes.Length - 1); float min = Mathf.Floor(sizeTime); float max = Mathf.Clamp(Mathf.Ceil(sizeTime), 1, _sizes.Length - 1); float lerp = Mathf.InverseLerp(min, max, sizeTime); if (min >= _sizes.Length) min = _sizes.Length - 1; if (min < 0) min = 0; if (max >= _sizes.Length) max = _sizes.Length - 1; if (max < 0) max = 0; size = Mathf.Lerp(_sizes[(int)min], _sizes[(int)max], lerp); } Vector3 lineDirection = p.tipPosition - p.basePosition; newVertices[n * 2] = p.basePosition - (lineDirection * (size * 0.5f)); newVertices[(n * 2) + 1] = p.tipPosition + (lineDirection * (size * 0.5f)); newColors[n * 2] = newColors[(n * 2) + 1] = color; float uvRatio = (float)n/pointsToUse.Count; newUV[n * 2] = new Vector2(uvRatio, 0); newUV[(n * 2) + 1] = new Vector2(uvRatio, 1); if (n > 0) { newTriangles[(n - 1) * 6] = (n * 2) - 2; newTriangles[((n - 1) * 6) + 1] = (n * 2) - 1; newTriangles[((n - 1) * 6) + 2] = n * 2; newTriangles[((n - 1) * 6) + 3] = (n * 2) + 1; newTriangles[((n - 1) * 6) + 4] = n * 2; newTriangles[((n - 1) * 6) + 5] = (n * 2) - 1; } } _trailMesh.Clear(); _trailMesh.vertices = newVertices; _trailMesh.colors = newColors; _trailMesh.uv = newUV; _trailMesh.triangles = newTriangles; } } void RemoveOldPoints(List<Point> pointList) { List<Point> remove = new List<Point>(); foreach (Point p in pointList) { // cull old points first if (Time.time - p.timeCreated > _lifeTime) { remove.Add(p); } } foreach (Point p in remove) { pointList.Remove(p); } } }
// ============================================================================ // FileName: SIPMonitorFilter.cs // // Description: // Logs proxy events so that the proxy can be monitored and events watched/logged. // // Author(s): // Aaron Clauson // // History: // 01 May 2006 Aaron Clauson Created. // 14 Nov 2008 Aaron Clauson Renamed from ProxyMonitorFilter to SIPonitorFilter. // // License: // This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php // // Copyright (c) 2010 Aaron Clauson (aaron@sipsorcery.com), SIPSorcery Ltd, London, UK (www.sipsorcery.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that // the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of SIP Sorcery PTY LTD. // 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; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; using System.Threading; using SIPSorcery.SIP; using SIPSorcery.SIP.App; using SIPSorcery.Sys; using log4net; #if UNITTEST using NUnit.Framework; #endif namespace SIPSorcery.SIP.App { public class SIPMonitorFilter { public const string WILDCARD = "*"; public const string DEFAULT_REGEX = ".*"; public const int DEFAULT_FILEDURATION_MINUTES = 1440; // 1 Day. public const int MAX_FILEDURATION_MINUTES = 4320; // 3 Days. public const string BASETYPE_FILTER_KEY = "basetype"; // can be machine or control. public const string EVENTTYPE_FILTER_KEY = "event"; public const string MACHINE_EVENTTYPE_FILTER_KEY = "machineevent"; public const string IPADDRESS_FILTER_KEY = "ipaddr"; public const string IPADDRESSLONG_FILTER_KEY = "ipaddress"; public const string USERNAME_FILTER_KEY = "user"; public const string SIPREQUEST_FILTER_KEY = "request"; public const string SERVERADDRESS_FILTER_KEY = "ipserver"; public const string SERVERTYPE_FILTER_KEY = "server"; public const string REGEX_FILTER_KEY = "regex"; public const string SIPEVENT_DIALOG_KEY = "dialog"; // To subscribe for machine events related to dialogs. public const string SIPEVENT_PRESENCE_KEY = "presence"; // To subscribe for machine events related to presence. public const string MACHINE_BASE_TYPE = "machine"; public const string CONSOLE_BASE_TYPE = "console"; public const string EVENTTYPE_FULL_VALUE = "full"; // Full SIP messages. public const string EVENTTYPE_SYSTEM_VALUE = "system"; public const string EVENTTYPE_TROUBLE_VALUE = "trouble"; public const string SIPREQUEST_INVITE_VALUE = "invite"; public const string SIPREQUEST_REGISTER_VALUE = "register"; public const string SIPREQUEST_NOTIFY_VALUE = "notify"; public const string FILELOG_REQUEST_KEY = "file"; public const string FILELOG_MINUTESDURATION_KEY = "duration"; public string BaseType = CONSOLE_BASE_TYPE; public string IPAddress = WILDCARD; public string ServerIPAddress = WILDCARD; public string Username = null; public string SIPRequestFilter = WILDCARD; public string EventFilterDescr = null; public int EventTypeId = 0; public List<int> MachineEventTypeIds = null; public int ServerTypeId = 0; public string RegexFilter = DEFAULT_REGEX; public string FileLogname = null; public int FileLogDuration = DEFAULT_FILEDURATION_MINUTES; public SIPURI SIPEventDialogURI; public SIPURI SIPEventPresenceURI; public SIPMonitorFilter(string filter) { if (!filter.IsNullOrBlank()) { string[] filterItems = Regex.Split(filter, @"\s+and\s+"); if (filterItems != null && filterItems.Length > 0) { foreach (string filterItem in filterItems) { string[] filterPair = filterItem.Trim().Split(' '); if (filterPair != null && filterPair.Length == 2) { string filterName = filterPair[0]; string filterValue = filterPair[1]; if (filterName == BASETYPE_FILTER_KEY) { BaseType = filterValue; } else if (filterName == EVENTTYPE_FILTER_KEY) { if (filterValue != null && Regex.Match(filterValue, @"\d{1,2}").Success) { EventTypeId = Convert.ToInt32(filterValue); } else { EventFilterDescr = filterValue; } } else if (filterName == MACHINE_EVENTTYPE_FILTER_KEY) { if (!filterValue.IsNullOrBlank()) { MachineEventTypeIds = new List<int>(); string[] ids = filterValue.Split(','); foreach (string id in ids) { int eventId = 0; if (Int32.TryParse(id, out eventId)) { MachineEventTypeIds.Add(eventId); } } } } else if (filterName == SERVERADDRESS_FILTER_KEY) { ServerIPAddress = filterValue; } else if (filterName == IPADDRESS_FILTER_KEY || filterName == IPADDRESSLONG_FILTER_KEY) { IPAddress = filterValue; } else if (filterName == USERNAME_FILTER_KEY) { Username = filterValue; } else if (filterName == SIPREQUEST_FILTER_KEY) { SIPRequestFilter = filterValue; } else if (filterName == SERVERTYPE_FILTER_KEY) { if (filterValue != null && Regex.Match(filterValue, @"\d{1,2}").Success) { ServerTypeId = Convert.ToInt32(filterValue); // Help the user out and set a wildcard type on the event if none has been selected. if (EventFilterDescr == null && EventTypeId == 0) { EventFilterDescr = WILDCARD; } } } else if (filterName == FILELOG_REQUEST_KEY) { if (filterValue != null) { FileLogname = filterValue; } } else if (filterName == FILELOG_MINUTESDURATION_KEY) { if (filterValue != null && Regex.Match(filterValue, @"\d").Success) { FileLogDuration = Convert.ToInt32(filterValue); if (FileLogDuration > MAX_FILEDURATION_MINUTES) { FileLogDuration = MAX_FILEDURATION_MINUTES; } } } else if (filterName == REGEX_FILTER_KEY) { if (filterValue != null) { RegexFilter = filterValue; } } else if (filterName == SIPEVENT_DIALOG_KEY) { BaseType = MACHINE_BASE_TYPE; SIPEventDialogURI = SIPURI.ParseSIPURI(filterValue); } else if (filterName == SIPEVENT_PRESENCE_KEY) { BaseType = MACHINE_BASE_TYPE; SIPEventPresenceURI = SIPURI.ParseSIPURI(filterValue); } else { throw new ApplicationException("Filter " + filterName + " was not recognised."); } } else { throw new ApplicationException("Invalid item in filter: " + filterItem.Trim() + "."); } } } else { throw new ApplicationException("Invalid filter format: " + filter + "."); } } } public bool ShowEvent(SIPMonitorEventTypesEnum eventType, SIPEndPoint serverEndPoint) { if (EventTypeId != 0) { if ((int)eventType == EventTypeId) { return true; } else { return false; } } else { if (EventFilterDescr == EVENTTYPE_FULL_VALUE && eventType == SIPMonitorEventTypesEnum.FullSIPTrace) { // if (serverEndPoint != null && serverEndPoint.SocketEndPoint.Address.ToString() == "127.0.0.1") { // return false; // } //else { return true; // } } else if (EventFilterDescr == EVENTTYPE_SYSTEM_VALUE) { // Assume EVENTTYPE_ALL_VALUE. if (eventType == SIPMonitorEventTypesEnum.Monitor || eventType == SIPMonitorEventTypesEnum.HealthCheck || eventType == SIPMonitorEventTypesEnum.ParseSIPMessage || eventType == SIPMonitorEventTypesEnum.SIPMessageArrivalStats) { return true; } else { return false; } } else if (EventFilterDescr == EVENTTYPE_TROUBLE_VALUE) { // Assume EVENTTYPE_ALL_VALUE. if (eventType == SIPMonitorEventTypesEnum.Error || eventType == SIPMonitorEventTypesEnum.Warn || eventType == SIPMonitorEventTypesEnum.BadSIPMessage) { return true; } else { return false; } } else { // Assume EVENTTYPE_ALL_VALUE if nothing has been specified by the user, however do not display the full SIP trace messages. if (EventFilterDescr == WILDCARD && eventType != SIPMonitorEventTypesEnum.FullSIPTrace && eventType != SIPMonitorEventTypesEnum.UserSpecificSIPTrace) { return true; } else { return false; } } } } public bool ShowMachineEvent(SIPMonitorMachineEventTypesEnum eventType) { if (MachineEventTypeIds != null && MachineEventTypeIds.Count > 0) { foreach (int eventId in MachineEventTypeIds) { if ((int)eventType == eventId) { return true; } } return false; } if (eventType == SIPMonitorMachineEventTypesEnum.SIPDialogueTransfer) { // These events are only returned if explicitly requested. return false; } else { return true; } } public bool ShowServer(SIPMonitorServerTypesEnum eventServer) { if (ServerTypeId != 0) { if ((int)eventServer == ServerTypeId) { return true; } else { return false; } } return true; } public bool ShowServerIPAddress(string serverIPAddress) { if (ServerIPAddress == WILDCARD || serverIPAddress == null) { return true; } else { return serverIPAddress.StartsWith(ServerIPAddress); } } public bool ShowIPAddress(string ipAddress) { if (IPAddress == WILDCARD) { return true; } else if (ipAddress == null || ipAddress.Trim().Length == 0) { return false; } else { return ipAddress.Contains(IPAddress); } } public bool ShowUsername(string username) { if (Username == WILDCARD) { return true; } else if (username.IsNullOrBlank()) { return false; } else { return username.ToUpper() == Username.ToUpper(); } } public bool ShowRegex(string message) { if (message == null || RegexFilter == DEFAULT_REGEX) { return true; } else { return Regex.Match(message, RegexFilter).Success; } } public string GetFilterDescription() { string eventStr = (EventTypeId == 0) ? EventFilterDescr : SIPMonitorEventTypes.GetProxyEventTypeForId(EventTypeId).ToString(); string serverStr = (ServerTypeId == 0) ? WILDCARD : SIPMonitorServerTypes.GetProxyServerTypeForId(ServerTypeId).ToString(); string filerDescription = "basetype=" + BaseType + ", ipaddress=" + IPAddress + ", user=" + Username + ", event=" + eventStr + ", request=" + SIPRequestFilter + ", serveripaddress=" + ServerIPAddress + ", server=" + serverStr + ", regex=" + RegexFilter + "."; return filerDescription; } /// <summary> /// Rules for displaying events. /// 1. The event type is checked to see if it matches. If no event type has been specified than all events EXCEPT FullSIPTrace are /// matched, /// 2. If the event type is FullSIPTrace then the messages can be filtered on the request type. If the request type is not set all /// SIP trace messages are matched otherwise only those pertaining to the request type specified, /// 3. The server type is checked, if it's not set all events are matched, /// 4. If the event has matched up until this point a decision is now made as to whether to display or reject it: /// a. If the IPAddress filter is set is checked, if it matches the event is displayed otherwise it's rejected, /// b. If the username AND server IP AND request type AND regex filters all match the vent is displayed otherwise rejected. /// </summary> /// <param name="proxyEvent"></param> /// <returns></returns> public bool ShowSIPMonitorEvent(SIPMonitorEvent proxyEvent) { if (proxyEvent is SIPMonitorMachineEvent) { #region Machine event filtering. if (BaseType == MACHINE_BASE_TYPE) { if (EventFilterDescr == WILDCARD) { return ShowUsername(proxyEvent.Username); } else { SIPMonitorMachineEvent machineEvent = proxyEvent as SIPMonitorMachineEvent; if ((machineEvent.MachineEventType == SIPMonitorMachineEventTypesEnum.SIPDialogueCreated || machineEvent.MachineEventType == SIPMonitorMachineEventTypesEnum.SIPDialogueRemoved || machineEvent.MachineEventType == SIPMonitorMachineEventTypesEnum.SIPDialogueUpdated || machineEvent.MachineEventType == SIPMonitorMachineEventTypesEnum.SIPDialogueTransfer) && SIPEventDialogURI != null) { if (SIPEventDialogURI.User == WILDCARD) { return ShowUsername(proxyEvent.Username) && ShowMachineEvent(machineEvent.MachineEventType); } else { return proxyEvent.Username == Username && machineEvent.ResourceURI != null && machineEvent.ResourceURI.User == SIPEventDialogURI.User && machineEvent.ResourceURI.Host == SIPEventDialogURI.Host; } } else if ((machineEvent.MachineEventType == SIPMonitorMachineEventTypesEnum.SIPRegistrarBindingRemoval || machineEvent.MachineEventType == SIPMonitorMachineEventTypesEnum.SIPRegistrarBindingUpdate) && SIPEventPresenceURI != null) { if (SIPEventPresenceURI.User == WILDCARD) { return ShowUsername(proxyEvent.Username); } else { return proxyEvent.Username == Username && machineEvent.ResourceURI != null && machineEvent.ResourceURI.User == SIPEventPresenceURI.User && machineEvent.ResourceURI.Host == SIPEventPresenceURI.Host; } } else if (SIPEventDialogURI == null && SIPEventPresenceURI == null) { return ShowUsername(proxyEvent.Username); } else { return false; } } } else { return false; } #endregion } else if (BaseType == MACHINE_BASE_TYPE && !(proxyEvent is SIPMonitorMachineEvent)) { return false; } else { SIPMonitorConsoleEvent consoleEvent = proxyEvent as SIPMonitorConsoleEvent; string serverAddress = (consoleEvent.ServerEndPoint != null) ? consoleEvent.ServerEndPoint.Address.ToString() : null; string remoteIPAddress = (consoleEvent.RemoteEndPoint != null) ? consoleEvent.RemoteEndPoint.Address.ToString() : null; string dstIPAddress = (consoleEvent.DestinationEndPoint != null) ? consoleEvent.DestinationEndPoint.Address.ToString() : null; if (SIPRequestFilter != WILDCARD && consoleEvent.Message != null && consoleEvent.EventType == SIPMonitorEventTypesEnum.FullSIPTrace) { if (ShowEvent(consoleEvent.EventType, consoleEvent.ServerEndPoint) && ShowServer(consoleEvent.ServerType)) { if (SIPRequestFilter == SIPREQUEST_INVITE_VALUE) { // Do a regex to pick out ACKs, BYEs, CANCELs, INVITEs and REFERs. if (Regex.Match(consoleEvent.Message, "(ACK|BYE|CANCEL|INVITE|REFER) +?sips?:", RegexOptions.IgnoreCase).Success || Regex.Match(consoleEvent.Message, @"CSeq: \d+ (ACK|BYE|CANCEL|INVITE|REFER)(\r|\n)", RegexOptions.IgnoreCase).Success) { return ShowRegex(consoleEvent.Message) && (ShowIPAddress(remoteIPAddress) || ShowIPAddress(dstIPAddress)); } } else if (SIPRequestFilter == SIPREQUEST_REGISTER_VALUE) { // Do a regex to pick out REGISTERs. if (Regex.Match(consoleEvent.Message, "REGISTER +?sips?:", RegexOptions.IgnoreCase).Success || Regex.Match(consoleEvent.Message, @"CSeq: \d+ REGISTER(\r|\n)", RegexOptions.IgnoreCase).Success) { return ShowRegex(consoleEvent.Message) && (ShowIPAddress(remoteIPAddress) || ShowIPAddress(dstIPAddress)); } } else if (SIPRequestFilter == SIPREQUEST_NOTIFY_VALUE) { // Do a regex to pick out NOTIFYs and SUBSCRIBEs. if (Regex.Match(consoleEvent.Message, "(NOTIFY|SUBSCRIBE) +?sips?:", RegexOptions.IgnoreCase).Success || Regex.Match(consoleEvent.Message, @"CSeq: \d+ (NOTIFY|SUBSCRIBE)(\r|\n)", RegexOptions.IgnoreCase).Success) { return ShowRegex(consoleEvent.Message) && (ShowIPAddress(remoteIPAddress) || ShowIPAddress(dstIPAddress)); } } return false; } } if (ShowEvent(consoleEvent.EventType, consoleEvent.ServerEndPoint)) { bool showIPAddress = ShowIPAddress(remoteIPAddress) || ShowIPAddress(dstIPAddress); bool showUsername = ShowUsername(consoleEvent.Username); bool showServerIP = ShowServerIPAddress(serverAddress); bool showRegex = ShowRegex(consoleEvent.Message); bool showServer = ShowServer(consoleEvent.ServerType); if (showUsername && showServerIP && showRegex && showIPAddress && showServer) { return true; } } return false; } } #region Unit testing. #if UNITTEST [TestFixture] public class ProxyMonitorFilterUnitTest { private static string m_CRLF = SIPConstants.CRLF; [TestFixtureSetUp] public void Init() {} [TestFixtureTearDown] public void Dispose() {} [Test] public void CreateFilterUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); SIPMonitorFilter filter = new SIPMonitorFilter("user test and event full"); Console.WriteLine(filter.GetFilterDescription()); Assert.IsTrue(filter != null, "The filter was not correctly instantiated."); Assert.AreEqual(filter.Username, "test", "The filter username was not correctly set."); Assert.AreEqual(filter.EventFilterDescr, "full", "The filter event full was not correctly set."); } [Test] public void RequestRejectionUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); SIPMonitorFilter filter = new SIPMonitorFilter("user test and event full and request invite "); Console.WriteLine(filter.GetFilterDescription()); Assert.IsTrue(filter != null, "The filter was not correctly instantiated."); Assert.AreEqual(filter.Username, "test", "The filter username was not correctly set."); Assert.AreEqual(filter.EventFilterDescr, "full", "The filter event full was not correctly set."); Assert.AreEqual(filter.SIPRequestFilter, "invite", "The sip request filter was not correctly set."); string registerRequest = "REGISTER sip:213.200.94.181 SIP/2.0" + m_CRLF + "Via: SIP/2.0/UDP 192.168.1.32:10254;branch=z9hG4bK-d87543-eb7c9f44883c5955-1--d87543-;rport;received=89.100.104.191" + m_CRLF + "To: aaronxten <sip:aaronxten@213.200.94.181>" + m_CRLF + "From: aaronxten <sip:aaronxten@213.200.94.181>;tag=774d2561" + m_CRLF + "Call-ID: MTBhNGZjZmQ2OTc3MWU5MTZjNWUxMDYxOTk1MjdmYzk." + m_CRLF + "CSeq: 2 REGISTER" + m_CRLF + "Contact: <sip:aaronxten@192.168.1.32:10254;rinstance=6d2bbd8014ca7a76>;expires=0" + m_CRLF + "Max-Forwards: 69" + m_CRLF + "User-Agent: X-Lite release 1006e stamp 34025" + m_CRLF + "Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY, MESSAGE, SUBSCRIBE, INFO" + m_CRLF + m_CRLF; SIPMonitorEvent monitorEvent = new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, registerRequest, "test"); bool showEventResult = filter.ShowSIPMonitorEvent(monitorEvent); Assert.IsFalse(showEventResult, "The filter should not have shown this event."); } [Test] public void RequestAcceptUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); SIPMonitorFilter filter = new SIPMonitorFilter("user test and event full and request invite "); Console.WriteLine(filter.GetFilterDescription()); Assert.IsTrue(filter != null, "The filter was not correctly instantiated."); Assert.AreEqual(filter.Username, "test", "The filter username was not correctly set."); Assert.AreEqual(filter.EventFilterDescr, "full", "The filter event full was not correctly set."); Assert.AreEqual(filter.SIPRequestFilter, "invite", "The sip request filter was not correctly set."); string registerRequest = "INVITE sip:213.200.94.181 SIP/2.0" + m_CRLF + "Via: SIP/2.0/UDP 192.168.1.32:10254;branch=z9hG4bK-d87543-eb7c9f44883c5955-1--d87543-;rport;received=89.100.104.191" + m_CRLF + "To: aaronxten <sip:aaronxten@213.200.94.181>" + m_CRLF + "From: test <sip:test@213.200.94.181>;tag=774d2561" + m_CRLF + "Call-ID: MTBhNGZjZmQ2OTc3MWU5MTZjNWUxMDYxOTk1MjdmYzk." + m_CRLF + "CSeq: 2 REGISTER" + m_CRLF + "Contact: <sip:aaronxten@192.168.1.32:10254;rinstance=6d2bbd8014ca7a76>;expires=0" + m_CRLF + "Max-Forwards: 69" + m_CRLF + "User-Agent: X-Lite release 1006e stamp 34025" + m_CRLF + "Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY, MESSAGE, SUBSCRIBE, INFO" + m_CRLF + m_CRLF; SIPMonitorEvent monitorEvent = new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, registerRequest, "test"); bool showEventResult = filter.ShowSIPMonitorEvent(monitorEvent); Assert.IsTrue(showEventResult, "The filter should have shown this event."); } [Test] public void ShowIPAddressUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); SIPMonitorFilter filter = new SIPMonitorFilter("ipaddress 10.0.0.1 and event full"); Console.WriteLine(filter.GetFilterDescription()); Assert.IsTrue(filter != null, "The filter was not correctly instantiated."); Assert.AreEqual(filter.IPAddress, "10.0.0.1", "The filter ip address was not correctly set."); SIPMonitorEvent monitorEvent = new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, "blah blah", String.Empty, null, SIPEndPoint.ParseSIPEndPoint("10.0.0.1")); bool showEventResult = filter.ShowSIPMonitorEvent(monitorEvent); Assert.IsTrue(showEventResult, "The filter should have shown this event."); } [Test] public void ShowInternalIPAddressUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); SIPMonitorFilter filter = new SIPMonitorFilter("ipaddress 127.0.0.1 and event fullinternal"); Console.WriteLine(filter.GetFilterDescription()); Assert.IsTrue(filter != null, "The filter was not correctly instantiated."); Assert.AreEqual(filter.IPAddress, "127.0.0.1", "The filter ip address was not correctly set."); SIPMonitorEvent monitorEvent = new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, "blah blah", String.Empty, null, SIPEndPoint.ParseSIPEndPoint("127.0.0.1")); bool showEventResult = filter.ShowSIPMonitorEvent(monitorEvent); Assert.IsTrue(showEventResult, "The filter should have shown this event."); } [Test] public void BlockIPAddressUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); SIPMonitorFilter filter = new SIPMonitorFilter("ipaddress 127.0.0.1 and event full"); Console.WriteLine(filter.GetFilterDescription()); Assert.IsTrue(filter != null, "The filter was not correctly instantiated."); Assert.AreEqual(filter.IPAddress, "127.0.0.1", "The filter ip address was not correctly set."); SIPMonitorEvent monitorEvent = new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, "blah blah", String.Empty, SIPEndPoint.ParseSIPEndPoint("127.0.0.2"), null); bool showEventResult = filter.ShowSIPMonitorEvent(monitorEvent); Assert.IsFalse(showEventResult, "The filter should not have shown this event."); } [Test] public void FullTraceSIPSwitchUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); SIPMonitorFilter filter = new SIPMonitorFilter("event full and regex :test@"); Console.WriteLine(filter.GetFilterDescription()); Assert.IsTrue(filter != null, "The filter was not correctly instantiated."); //Assert.AreEqual(filter.Username, "test", "The filter username was not correctly set."); Assert.AreEqual(filter.EventFilterDescr, "full", "The filter event full was not correctly set."); Assert.AreEqual(filter.RegexFilter, ":test@", "The regex was not correctly set."); string inviteRequest = "INVITE sip:213.200.94.181 SIP/2.0" + m_CRLF + "Via: SIP/2.0/UDP 192.168.1.32:10254;branch=z9hG4bK-d87543-eb7c9f44883c5955-1--d87543-;rport;received=89.100.104.191" + m_CRLF + "To: aaronxten <sip:aaronxten@213.200.94.181>" + m_CRLF + "From: test <sip:test@213.200.94.181>;tag=774d2561" + m_CRLF + "Call-ID: MTBhNGZjZmQ2OTc3MWU5MTZjNWUxMDYxOTk1MjdmYzk." + m_CRLF + "CSeq: 2 REGISTER" + m_CRLF + "Contact: <sip:aaronxten@192.168.1.32:10254;rinstance=6d2bbd8014ca7a76>;expires=0" + m_CRLF + "Max-Forwards: 69" + m_CRLF + "User-Agent: X-Lite release 1006e stamp 34025" + m_CRLF + "Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY, MESSAGE, SUBSCRIBE, INFO" + m_CRLF + m_CRLF; SIPMonitorEvent monitorEvent = new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, inviteRequest, null); bool showEventResult = filter.ShowSIPMonitorEvent(monitorEvent); Assert.IsTrue(showEventResult, "The filter should have shown this event."); } [Test] public void UsernameWithAndFilterUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); SIPMonitorFilter filter = new SIPMonitorFilter("user testandtest and event full"); Console.WriteLine(filter.GetFilterDescription()); Assert.IsTrue(filter != null, "The filter was not correctly instantiated."); Assert.AreEqual(filter.Username, "testandtest", "The filter username was not correctly set."); Assert.AreEqual(filter.EventFilterDescr, "full", "The filter event full was not correctly set."); } } #endif #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using FluentAssertions.Common; using FluentAssertions.Extensions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.AspNetCore.Authentication; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.SoftDeletion { public sealed class SoftDeletionTests : IClassFixture<IntegrationTestContext<TestableStartup<SoftDeletionDbContext>, SoftDeletionDbContext>> { private static readonly DateTimeOffset SoftDeletionTime = 1.January(2001).ToDateTimeOffset(); private readonly IntegrationTestContext<TestableStartup<SoftDeletionDbContext>, SoftDeletionDbContext> _testContext; private readonly SoftDeletionFakers _fakers = new(); public SoftDeletionTests(IntegrationTestContext<TestableStartup<SoftDeletionDbContext>, SoftDeletionDbContext> testContext) { _testContext = testContext; testContext.UseController<CompaniesController>(); testContext.UseController<DepartmentsController>(); testContext.ConfigureServicesAfterStartup(services => { services.AddSingleton<ISystemClock>(new FrozenSystemClock { UtcNow = 1.January(2005).ToDateTimeOffset() }); services.AddResourceService<SoftDeletionAwareResourceService<Company>>(); services.AddResourceService<SoftDeletionAwareResourceService<Department>>(); }); } [Fact] public async Task Get_primary_resources_excludes_soft_deleted() { // Arrange List<Department> departments = _fakers.Department.Generate(2); departments[0].SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Department>(); dbContext.Departments.AddRange(departments); await dbContext.SaveChangesAsync(); }); const string route = "/departments"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(departments[1].StringId); } [Fact] public async Task Filter_on_primary_resources_excludes_soft_deleted() { // Arrange List<Department> departments = _fakers.Department.Generate(3); departments[0].Name = "Support"; departments[1].Name = "Sales"; departments[1].SoftDeletedAt = SoftDeletionTime; departments[2].Name = "Marketing"; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Department>(); dbContext.Departments.AddRange(departments); await dbContext.SaveChangesAsync(); }); const string route = "/departments?filter=startsWith(name,'S')"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(departments[0].StringId); } [Fact] public async Task Get_primary_resources_with_include_excludes_soft_deleted() { // Arrange List<Company> companies = _fakers.Company.Generate(2); companies[0].SoftDeletedAt = SoftDeletionTime; companies[0].Departments = _fakers.Department.Generate(1); companies[1].Departments = _fakers.Department.Generate(2); companies[1].Departments.ElementAt(1).SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Company>(); dbContext.Companies.AddRange(companies); await dbContext.SaveChangesAsync(); }); const string route = "/companies?include=departments"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Type.Should().Be("companies"); responseDocument.Data.ManyValue[0].Id.Should().Be(companies[1].StringId); responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Type.Should().Be("departments"); responseDocument.Included[0].Id.Should().Be(companies[1].Departments.ElementAt(0).StringId); } [Fact] public async Task Cannot_get_soft_deleted_primary_resource_by_ID() { // Arrange Department department = _fakers.Department.Generate(); department.SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Departments.Add(department); await dbContext.SaveChangesAsync(); }); string route = $"/departments/{department.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'departments' with ID '{department.StringId}' does not exist."); } [Fact] public async Task Cannot_get_secondary_resources_for_soft_deleted_parent() { // Arrange Company company = _fakers.Company.Generate(); company.SoftDeletedAt = SoftDeletionTime; company.Departments = _fakers.Department.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Companies.Add(company); await dbContext.SaveChangesAsync(); }); string route = $"/companies/{company.StringId}/departments"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'companies' with ID '{company.StringId}' does not exist."); } [Fact] public async Task Get_secondary_resources_excludes_soft_deleted() { // Arrange Company company = _fakers.Company.Generate(); company.Departments = _fakers.Department.Generate(2); company.Departments.ElementAt(0).SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Companies.Add(company); await dbContext.SaveChangesAsync(); }); string route = $"/companies/{company.StringId}/departments"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(company.Departments.ElementAt(1).StringId); } [Fact] public async Task Cannot_get_secondary_resource_for_soft_deleted_parent() { // Arrange Department department = _fakers.Department.Generate(); department.SoftDeletedAt = SoftDeletionTime; department.Company = _fakers.Company.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Departments.Add(department); await dbContext.SaveChangesAsync(); }); string route = $"/departments/{department.StringId}/company"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'departments' with ID '{department.StringId}' does not exist."); } [Fact] public async Task Cannot_get_soft_deleted_secondary_resource() { // Arrange Department department = _fakers.Department.Generate(); department.Company = _fakers.Company.Generate(); department.Company.SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Departments.Add(department); await dbContext.SaveChangesAsync(); }); string route = $"/departments/{department.StringId}/company"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.Value.Should().BeNull(); } [Fact] public async Task Cannot_get_ToMany_relationship_for_soft_deleted_parent() { // Arrange Company company = _fakers.Company.Generate(); company.SoftDeletedAt = SoftDeletionTime; company.Departments = _fakers.Department.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Companies.Add(company); await dbContext.SaveChangesAsync(); }); string route = $"/companies/{company.StringId}/relationships/departments"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'companies' with ID '{company.StringId}' does not exist."); } [Fact] public async Task Get_ToMany_relationship_excludes_soft_deleted() { // Arrange Company company = _fakers.Company.Generate(); company.Departments = _fakers.Department.Generate(2); company.Departments.ElementAt(0).SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Companies.Add(company); await dbContext.SaveChangesAsync(); }); string route = $"/companies/{company.StringId}/relationships/departments"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(company.Departments.ElementAt(1).StringId); } [Fact] public async Task Cannot_get_ToOne_relationship_for_soft_deleted_parent() { // Arrange Department department = _fakers.Department.Generate(); department.SoftDeletedAt = SoftDeletionTime; department.Company = _fakers.Company.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Departments.Add(department); await dbContext.SaveChangesAsync(); }); string route = $"/departments/{department.StringId}/relationships/company"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'departments' with ID '{department.StringId}' does not exist."); } [Fact] public async Task Get_ToOne_relationship_excludes_soft_deleted() { // Arrange Department department = _fakers.Department.Generate(); department.Company = _fakers.Company.Generate(); department.Company.SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Departments.Add(department); await dbContext.SaveChangesAsync(); }); string route = $"/departments/{department.StringId}/relationships/company"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.Value.Should().BeNull(); } [Fact] public async Task Cannot_create_resource_with_ToMany_relationship_to_soft_deleted() { // Arrange Department existingDepartment = _fakers.Department.Generate(); existingDepartment.SoftDeletedAt = SoftDeletionTime; string newCompanyName = _fakers.Company.Generate().Name; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Departments.Add(existingDepartment); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "companies", attributes = new { name = newCompanyName }, relationships = new { departments = new { data = new[] { new { type = "departments", id = existingDepartment.StringId } } } } } }; const string route = "/companies"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should() .Be($"Related resource of type 'departments' with ID '{existingDepartment.StringId}' in relationship 'departments' does not exist."); } [Fact] public async Task Cannot_create_resource_with_ToOne_relationship_to_soft_deleted() { // Arrange Company existingCompany = _fakers.Company.Generate(); existingCompany.SoftDeletedAt = SoftDeletionTime; string newDepartmentName = _fakers.Department.Generate().Name; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Companies.Add(existingCompany); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "departments", attributes = new { name = newDepartmentName }, relationships = new { company = new { data = new { type = "companies", id = existingCompany.StringId } } } } }; const string route = "/departments"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be($"Related resource of type 'companies' with ID '{existingCompany.StringId}' in relationship 'company' does not exist."); } [Fact] public async Task Cannot_update_soft_deleted_resource() { // Arrange Company existingCompany = _fakers.Company.Generate(); existingCompany.SoftDeletedAt = SoftDeletionTime; string newCompanyName = _fakers.Company.Generate().Name; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Companies.Add(existingCompany); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "companies", id = existingCompany.StringId, attributes = new { name = newCompanyName } } }; string route = $"/companies/{existingCompany.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'companies' with ID '{existingCompany.StringId}' does not exist."); } [Fact] public async Task Cannot_update_resource_with_ToMany_relationship_to_soft_deleted() { // Arrange Company existingCompany = _fakers.Company.Generate(); Department existingDepartment = _fakers.Department.Generate(); existingDepartment.SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingCompany, existingDepartment); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "companies", id = existingCompany.StringId, relationships = new { departments = new { data = new[] { new { type = "departments", id = existingDepartment.StringId } } } } } }; string route = $"/companies/{existingCompany.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should() .Be($"Related resource of type 'departments' with ID '{existingDepartment.StringId}' in relationship 'departments' does not exist."); } [Fact] public async Task Cannot_update_resource_with_ToOne_relationship_to_soft_deleted() { // Arrange Department existingDepartment = _fakers.Department.Generate(); Company existingCompany = _fakers.Company.Generate(); existingCompany.SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingDepartment, existingCompany); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "departments", id = existingDepartment.StringId, relationships = new { company = new { data = new { type = "companies", id = existingCompany.StringId } } } } }; string route = $"/departments/{existingDepartment.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be($"Related resource of type 'companies' with ID '{existingCompany.StringId}' in relationship 'company' does not exist."); } [Fact] public async Task Cannot_update_ToMany_relationship_for_soft_deleted_parent() { // Arrange Company existingCompany = _fakers.Company.Generate(); existingCompany.SoftDeletedAt = SoftDeletionTime; existingCompany.Departments = _fakers.Department.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Companies.Add(existingCompany); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = Array.Empty<object>() }; string route = $"/companies/{existingCompany.StringId}/relationships/departments"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'companies' with ID '{existingCompany.StringId}' does not exist."); } [Fact] public async Task Cannot_update_ToMany_relationship_to_soft_deleted() { // Arrange Company existingCompany = _fakers.Company.Generate(); Department existingDepartment = _fakers.Department.Generate(); existingDepartment.SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingCompany, existingDepartment); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "departments", id = existingDepartment.StringId } } }; string route = $"/companies/{existingCompany.StringId}/relationships/departments"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should() .Be($"Related resource of type 'departments' with ID '{existingDepartment.StringId}' in relationship 'departments' does not exist."); } [Fact] public async Task Cannot_update_ToOne_relationship_for_soft_deleted_parent() { // Arrange Department existingDepartment = _fakers.Department.Generate(); existingDepartment.SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Departments.Add(existingDepartment); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = (object)null }; string route = $"/departments/{existingDepartment.StringId}/relationships/company"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'departments' with ID '{existingDepartment.StringId}' does not exist."); } [Fact] public async Task Cannot_update_ToOne_relationship_to_soft_deleted() { // Arrange Department existingDepartment = _fakers.Department.Generate(); Company existingCompany = _fakers.Company.Generate(); existingCompany.SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingDepartment, existingCompany); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "companies", id = existingCompany.StringId } }; string route = $"/departments/{existingDepartment.StringId}/relationships/company"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be($"Related resource of type 'companies' with ID '{existingCompany.StringId}' in relationship 'company' does not exist."); } [Fact] public async Task Cannot_add_to_ToMany_relationship_for_soft_deleted_parent() { // Arrange Company existingCompany = _fakers.Company.Generate(); existingCompany.SoftDeletedAt = SoftDeletionTime; Department existingDepartment = _fakers.Department.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingCompany, existingDepartment); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "departments", id = existingDepartment.StringId } } }; string route = $"/companies/{existingCompany.StringId}/relationships/departments"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'companies' with ID '{existingCompany.StringId}' does not exist."); } [Fact] public async Task Cannot_add_to_ToMany_relationship_with_soft_deleted() { // Arrange Company existingCompany = _fakers.Company.Generate(); Department existingDepartment = _fakers.Department.Generate(); existingDepartment.SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingCompany, existingDepartment); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "departments", id = existingDepartment.StringId } } }; string route = $"/companies/{existingCompany.StringId}/relationships/departments"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should() .Be($"Related resource of type 'departments' with ID '{existingDepartment.StringId}' in relationship 'departments' does not exist."); } [Fact] public async Task Cannot_remove_from_ToMany_relationship_for_soft_deleted_parent() { // Arrange Company existingCompany = _fakers.Company.Generate(); existingCompany.SoftDeletedAt = SoftDeletionTime; existingCompany.Departments = _fakers.Department.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Companies.Add(existingCompany); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "departments", id = existingCompany.Departments.ElementAt(0).StringId } } }; string route = $"/companies/{existingCompany.StringId}/relationships/departments"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'companies' with ID '{existingCompany.StringId}' does not exist."); } [Fact] public async Task Cannot_remove_from_ToMany_relationship_with_soft_deleted() { // Arrange Company existingCompany = _fakers.Company.Generate(); existingCompany.Departments = _fakers.Department.Generate(1); existingCompany.Departments.ElementAt(0).SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Companies.Add(existingCompany); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "departments", id = existingCompany.Departments.ElementAt(0).StringId } } }; string route = $"/companies/{existingCompany.StringId}/relationships/departments"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be( $"Related resource of type 'departments' with ID '{existingCompany.Departments.ElementAt(0).StringId}' in relationship 'departments' does not exist."); } [Fact] public async Task Can_soft_delete_resource() { // Arrange Company existingCompany = _fakers.Company.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Companies.Add(existingCompany); await dbContext.SaveChangesAsync(); }); string route = $"/companies/{existingCompany.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Company companyInDatabase = await dbContext.Companies.IgnoreQueryFilters().FirstWithIdAsync(existingCompany.Id); companyInDatabase.Name.Should().Be(existingCompany.Name); companyInDatabase.SoftDeletedAt.Should().NotBeNull(); }); } [Fact] public async Task Cannot_delete_soft_deleted_resource() { // Arrange Department existingDepartment = _fakers.Department.Generate(); existingDepartment.SoftDeletedAt = SoftDeletionTime; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Departments.Add(existingDepartment); await dbContext.SaveChangesAsync(); }); string route = $"/departments/{existingDepartment.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'departments' with ID '{existingDepartment.StringId}' does not exist."); } } }
using System; using System.IO; using System.Net; using System.Runtime; using System.Threading; using System.Globalization; using System.Threading.Tasks; using Orleans.Runtime.Configuration; namespace Orleans.Runtime.Host { /// <summary> /// Allows programmatically hosting an Orleans silo in the curent app domain. /// </summary> public class SiloHost : MarshalByRefObject, IDisposable { /// <summary> Name of this silo. </summary> public string Name { get; set; } /// <summary> Type of this silo - either <c>Primary</c> or <c>Secondary</c>. </summary> public Silo.SiloType Type { get; set; } /// <summary> /// Configuration file used for this silo. /// Changing this after the silo has started (when <c>ConfigLoaded == true</c>) will have no effect. /// </summary> public string ConfigFileName { get; set; } /// <summary> /// Directory to use for the trace log file written by this silo. /// </summary> /// <remarks> /// <para> /// The values of <c>null</c> or <c>"None"</c> mean no log file will be written by Orleans Logger manager. /// </para> /// <para> /// When deciding The values of <c>null</c> or <c>"None"</c> mean no log file will be written by Orleans Logger manager. /// </para> /// </remarks> public string TraceFilePath { get; set; } /// <summary> Configuration data for the Orleans system. </summary> public ClusterConfiguration Config { get; set; } /// <summary> Configuration data for this silo. </summary> public NodeConfiguration NodeConfig { get; private set; } /// <summary> /// Silo Debug flag. /// If set to <c>true</c> then additional diagnostic info will be written during silo startup. /// </summary> public bool Debug { get; set; } /// <summary> /// Whether the silo config has been loaded and initializing it's runtime config. /// </summary> /// <remarks> /// Changes to silo config properties will be ignored after <c>ConfigLoaded == true</c>. /// </remarks> public bool ConfigLoaded { get; private set; } /// <summary> Deployment Id (if any) for the cluster this silo is running in. </summary> public string DeploymentId { get; set; } /// <summary> /// Verbose flag. /// If set to <c>true</c> then additional status and diagnostics info will be written during silo startup. /// </summary> public int Verbose { get; set; } /// <summary> Whether this silo started successfully and is currently running. </summary> public bool IsStarted { get; private set; } private TraceLogger logger; private Silo orleans; private EventWaitHandle startupEvent; private EventWaitHandle shutdownEvent; private bool disposed; /// <summary> /// Constructor /// </summary> /// <param name="siloName">Name of this silo.</param> public SiloHost(string siloName) { Name = siloName; Type = Silo.SiloType.Secondary; // Default IsStarted = false; } /// <summary> Constructor </summary> /// <param name="siloName">Name of this silo.</param> /// <param name="config">Silo config that will be used to initialize this silo.</param> public SiloHost(string siloName, ClusterConfiguration config) : this(siloName) { SetSiloConfig(config); } /// <summary> Constructor </summary> /// <param name="siloName">Name of this silo.</param> /// <param name="configFile">Silo config file that will be used to initialize this silo.</param> public SiloHost(string siloName, FileInfo configFile) : this(siloName) { ConfigFileName = configFile.FullName; var config = new ClusterConfiguration(); config.LoadFromFile(ConfigFileName); SetSiloConfig(config); } /// <summary> /// Initialize this silo. /// </summary> public void InitializeOrleansSilo() { #if DEBUG AssemblyLoaderUtils.EnableAssemblyLoadTracing(); #endif try { if (!ConfigLoaded) LoadOrleansConfig(); orleans = new Silo(Name, Type, Config); } catch (Exception exc) { ReportStartupError(exc); orleans = null; } } /// <summary> /// Uninitialize this silo. /// </summary> public void UnInitializeOrleansSilo() { Utils.SafeExecute(UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler); Utils.SafeExecute(TraceLogger.UnInitialize); } /// <summary> /// Start this silo. /// </summary> /// <returns></returns> public bool StartOrleansSilo(bool catchExceptions = true) { try { if (string.IsNullOrEmpty(Thread.CurrentThread.Name)) Thread.CurrentThread.Name = this.GetType().Name; if (orleans != null) { var shutdownEventName = Config.Defaults.SiloShutdownEventName ?? Name + "-Shutdown"; logger.Info(ErrorCode.SiloShutdownEventName, "Silo shutdown event name: {0}", shutdownEventName); bool createdNew; shutdownEvent = new EventWaitHandle(false, EventResetMode.ManualReset, shutdownEventName, out createdNew); if (!createdNew) { logger.Info(ErrorCode.SiloShutdownEventOpened, "Opened existing shutdown event. Setting the event {0}", shutdownEventName); } else { logger.Info(ErrorCode.SiloShutdownEventCreated, "Created and set shutdown event {0}", shutdownEventName); } // Start silo orleans.Start(); // Wait for the shutdown event, and trigger a graceful shutdown if we receive it. var shutdownThread = new Thread(o => { shutdownEvent.WaitOne(); logger.Info(ErrorCode.SiloShutdownEventReceived, "Received a shutdown event. Starting graceful shutdown."); orleans.Shutdown(); }); shutdownThread.IsBackground = true; shutdownThread.Start(); var startupEventName = Name; logger.Info(ErrorCode.SiloStartupEventName, "Silo startup event name: {0}", startupEventName); startupEvent = new EventWaitHandle(true, EventResetMode.ManualReset, startupEventName, out createdNew); if (!createdNew) { logger.Info(ErrorCode.SiloStartupEventOpened, "Opened existing startup event. Setting the event {0}", startupEventName); startupEvent.Set(); } else { logger.Info(ErrorCode.SiloStartupEventCreated, "Created and set startup event {0}", startupEventName); } logger.Info(ErrorCode.SiloStarted, "Silo {0} started successfully", Name); IsStarted = true; } else { throw new InvalidOperationException("Cannot start silo " + this.Name + " due to prior initialization error"); } } catch (Exception exc) { if (catchExceptions) { ReportStartupError(exc); orleans = null; IsStarted = false; return false; } else throw; } return true; } /// <summary> /// Stop this silo. /// </summary> public void StopOrleansSilo() { IsStarted = false; if (orleans != null) orleans.Stop(); } /// <summary> /// Gracefully shutdown this silo. /// </summary> public void ShutdownOrleansSilo() { IsStarted = false; if (orleans != null) orleans.Shutdown(); } /// <summary> /// Wait for this silo to shutdown. /// </summary> /// <remarks> /// Note: This method call will block execution of current thread, /// and will not return control back to the caller until the silo is shutdown. /// </remarks> public void WaitForOrleansSiloShutdown() { WaitForOrleansSiloShutdownImpl(); } /// <summary> /// Wait for this silo to shutdown or to be stopped with provided cancellation token. /// </summary> /// <param name="cancellationToken">Cancellation token.</param> /// <remarks> /// Note: This method call will block execution of current thread, /// and will not return control back to the caller until the silo is shutdown or /// an external request for cancellation has been issued. /// </remarks> public void WaitForOrleansSiloShutdown(CancellationToken cancellationToken) { WaitForOrleansSiloShutdownImpl(cancellationToken); } /// <summary> /// Set the DeploymentId for this silo, /// as well as the connection string to use the silo system data, /// such as the cluster membership table.. /// </summary> /// <param name="deploymentId">DeploymentId this silo is part of.</param> /// <param name="connectionString">Azure connection string to use the silo system data.</param> public void SetDeploymentId(string deploymentId, string connectionString) { logger.Info(ErrorCode.SiloSetDeploymentId, "Setting Deployment Id to {0} and data connection string to {1}", deploymentId, ConfigUtilities.RedactConnectionStringInfo(connectionString)); Config.Globals.DeploymentId = deploymentId; Config.Globals.DataConnectionString = connectionString; } /// <summary> /// Set the main endpoint address for this silo, /// plus the silo generation value to be used to distinguish this silo instance /// from any previous silo instances previously running on this endpoint. /// </summary> /// <param name="endpoint">IP address and port of the main inter-silo socket connection.</param> /// <param name="generation">Generation number for this silo.</param> public void SetSiloEndpoint(IPEndPoint endpoint, int generation) { logger.Info(ErrorCode.SiloSetSiloEndpoint, "Setting silo endpoint address to {0}:{1}", endpoint, generation); NodeConfig.HostNameOrIPAddress = endpoint.Address.ToString(); NodeConfig.Port = endpoint.Port; NodeConfig.Generation = generation; } /// <summary> /// Set the gateway proxy endpoint address for this silo. /// </summary> /// <param name="endpoint">IP address of the gateway socket connection.</param> public void SetProxyEndpoint(IPEndPoint endpoint) { logger.Info(ErrorCode.SiloSetProxyEndpoint, "Setting silo proxy endpoint address to {0}", endpoint); NodeConfig.ProxyGatewayEndpoint = endpoint; } /// <summary> /// Set the seed node endpoint address to be used by silo. /// </summary> /// <param name="endpoint">IP address of the inter-silo connection socket on the seed node silo.</param> public void SetSeedNodeEndpoint(IPEndPoint endpoint) { logger.Info(ErrorCode.SiloSetSeedNode, "Adding seed node address={0} port={1}", endpoint.Address, endpoint.Port); Config.Globals.SeedNodes.Clear(); Config.Globals.SeedNodes.Add(endpoint); } /// <summary> /// Set the set of seed node endpoint addresses to be used by silo. /// </summary> /// <param name="endpoints">IP addresses of the inter-silo connection socket on the seed node silos.</param> public void SetSeedNodeEndpoints(IPEndPoint[] endpoints) { // Add all silos as seed nodes Config.Globals.SeedNodes.Clear(); foreach (IPEndPoint endpoint in endpoints) { logger.Info(ErrorCode.SiloAddSeedNode, "Adding seed node address={0} port={1}", endpoint.Address, endpoint.Port); Config.Globals.SeedNodes.Add(endpoint); } } /// <summary> /// Set the endpoint addresses for the Primary silo (if any). /// This silo may be Primary, in which case this address should match /// this silo's inter-silo connection socket address. /// </summary> /// <param name="endpoint">The IP address for the inter-silo connection socket on the Primary silo.</param> public void SetPrimaryNodeEndpoint(IPEndPoint endpoint) { logger.Info(ErrorCode.SiloSetPrimaryNode, "Setting primary node address={0} port={1}", endpoint.Address, endpoint.Port); Config.PrimaryNode = endpoint; } /// <summary> /// Set the type of this silo. Default is Secondary. /// </summary> /// <param name="siloType">Type of this silo.</param> public void SetSiloType(Silo.SiloType siloType) { logger.Info(ErrorCode.SiloSetSiloType, "Setting silo type {0}", siloType); Type = siloType; } /// <summary> /// Set the membership liveness type to be used by this silo. /// </summary> /// <param name="livenessType">Liveness type for this silo</param> public void SetSiloLivenessType(GlobalConfiguration.LivenessProviderType livenessType) { logger.Info(ErrorCode.SetSiloLivenessType, "Setting silo Liveness Provider Type={0}", livenessType); Config.Globals.LivenessType = livenessType; } /// <summary> /// Set the reminder service type to be used by this silo. /// </summary> /// <param name="reminderType">Reminder service type for this silo</param> public void SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType reminderType) { logger.Info(ErrorCode.SetSiloLivenessType, "Setting silo Reminder Service Provider Type={0}", reminderType); Config.Globals.SetReminderServiceType(reminderType); } /// <summary> /// Set expected deployment size. /// </summary> /// <param name="size">The expected deployment size.</param> public void SetExpectedClusterSize(int size) { logger.Info(ErrorCode.SetSiloLivenessType, "Setting Expected Cluster Size to={0}", size); Config.Globals.ExpectedClusterSize = size; } /// <summary> /// Report an error during silo startup. /// </summary> /// <remarks> /// Information on the silo startup issue will be logged to any attached Loggers, /// then a timestamped StartupError text file will be written to /// the current working directory (if possible). /// </remarks> /// <param name="exc">Exception which caused the silo startup issue.</param> public void ReportStartupError(Exception exc) { if (string.IsNullOrWhiteSpace(Name)) Name = "Silo"; var errMsg = "ERROR starting Orleans silo name=" + Name + " Exception=" + TraceLogger.PrintException(exc); if (logger != null) logger.Error(ErrorCode.Runtime_Error_100105, errMsg, exc); // Dump Startup error to a log file var now = DateTime.UtcNow; const string dateFormat = "yyyy-MM-dd-HH.mm.ss.fffZ"; var dateString = now.ToString(dateFormat, CultureInfo.InvariantCulture); var startupLog = Name + "-StartupError-" + dateString + ".txt"; try { File.AppendAllText(startupLog, dateString + "Z" + Environment.NewLine + errMsg); } catch (Exception exc2) { if (logger != null) logger.Error(ErrorCode.Runtime_Error_100106, "Error writing log file " + startupLog, exc2); } TraceLogger.Flush(); } /// <summary> /// Search for and load the config file for this silo. /// </summary> public void LoadOrleansConfig() { if (ConfigLoaded) return; var config = Config ?? new ClusterConfiguration(); try { if (ConfigFileName == null) config.StandardLoad(); else config.LoadFromFile(ConfigFileName); } catch (Exception ex) { throw new AggregateException("Error loading Config file: " + ex.Message, ex); } SetSiloConfig(config); } /// <summary> /// Allows silo config to be programmatically set. /// </summary> /// <param name="config">Configuration data for this silo and cluster.</param> private void SetSiloConfig(ClusterConfiguration config) { Config = config; if (Verbose > 0) Config.Defaults.DefaultTraceLevel = (Severity.Verbose - 1 + Verbose); if (!String.IsNullOrEmpty(DeploymentId)) Config.Globals.DeploymentId = DeploymentId; if (string.IsNullOrWhiteSpace(Name)) throw new ArgumentException("SiloName not defined - cannot initialize config"); NodeConfig = Config.GetOrCreateNodeConfigurationForSilo(Name); Type = NodeConfig.IsPrimaryNode ? Silo.SiloType.Primary : Silo.SiloType.Secondary; if (TraceFilePath != null) { var traceFileName = NodeConfig.TraceFileName; if (traceFileName != null && !Path.IsPathRooted(traceFileName)) NodeConfig.TraceFileName = TraceFilePath + "\\" + traceFileName; } ConfigLoaded = true; InitializeLogger(NodeConfig); } private void InitializeLogger(NodeConfiguration nodeCfg) { TraceLogger.Initialize(nodeCfg); logger = TraceLogger.GetLogger("OrleansSiloHost", TraceLogger.LoggerType.Runtime); } /// <summary> /// Helper to wait for this silo to shutdown or to be stopped via a cancellation token. /// </summary> /// <param name="cancellationToken">Optional cancellation token.</param> /// <remarks> /// Note: This method call will block execution of current thread, /// and will not return control back to the caller until the silo is shutdown or /// an external request for cancellation has been issued. /// </remarks> private void WaitForOrleansSiloShutdownImpl(CancellationToken? cancellationToken = null) { if (!IsStarted) throw new InvalidOperationException("Cannot wait for silo " + this.Name + " since it was not started successfully previously."); if (startupEvent != null) startupEvent.Reset(); else throw new InvalidOperationException("Cannot wait for silo " + this.Name + " due to prior initialization error"); if (orleans != null) { // Intercept cancellation to initiate silo stop if (cancellationToken.HasValue) cancellationToken.Value.Register(HandleExternalCancellation); orleans.SiloTerminatedEvent.WaitOne(); } else throw new InvalidOperationException("Cannot wait for silo " + this.Name + " due to prior initialization error"); } /// <summary> /// Handle the silo stop request coming from an external cancellation token. /// </summary> private void HandleExternalCancellation() { // Try to perform gracefull shutdown of Silo when we a cancellation request has been made logger.Info(ErrorCode.SiloStopping, "External cancellation triggered, starting to shutdown silo."); ShutdownOrleansSilo(); } /// <summary> /// Called when this silo is being Disposed by .NET runtime. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> Perform the Dispose / cleanup operation. </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { if (startupEvent != null) { startupEvent.Dispose(); startupEvent = null; } this.IsStarted = false; } } disposed = true; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Data; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using System.Text; using Npgsql; namespace OpenSim.Data.PGSQL { public class PGSQLGenericTableHandler<T> : PGSqlFramework where T : class, new() { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_ConnectionString; protected PGSQLManager m_database; //used for parameter type translation protected Dictionary<string, FieldInfo> m_Fields = new Dictionary<string, FieldInfo>(); protected Dictionary<string, string> m_FieldTypes = new Dictionary<string, string>(); protected List<string> m_ColumnNames = null; protected string m_Realm; protected FieldInfo m_DataField = null; protected virtual Assembly Assembly { get { return GetType().Assembly; } } public PGSQLGenericTableHandler(string connectionString, string realm, string storeName) : base(connectionString) { m_Realm = realm; m_ConnectionString = connectionString; if (storeName != String.Empty) { using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) { conn.Open(); Migration m = new Migration(conn, GetType().Assembly, storeName); m.Update(); } } m_database = new PGSQLManager(m_ConnectionString); Type t = typeof(T); FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); LoadFieldTypes(); if (fields.Length == 0) return; foreach (FieldInfo f in fields) { if (f.Name != "Data") m_Fields[f.Name] = f; else m_DataField = f; } } private void LoadFieldTypes() { m_FieldTypes = new Dictionary<string, string>(); string query = string.Format(@"select column_name,data_type from INFORMATION_SCHEMA.COLUMNS where table_name = lower('{0}'); ", m_Realm); using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) { conn.Open(); using (NpgsqlDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { // query produces 0 to many rows of single column, so always add the first item in each row m_FieldTypes.Add((string)rdr[0], (string)rdr[1]); } } } } private void CheckColumnNames(NpgsqlDataReader reader) { if (m_ColumnNames != null) return; m_ColumnNames = new List<string>(); DataTable schemaTable = reader.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) { if (row["ColumnName"] != null && (!m_Fields.ContainsKey(row["ColumnName"].ToString()))) m_ColumnNames.Add(row["ColumnName"].ToString()); } } // TODO GET CONSTRAINTS FROM POSTGRESQL private List<string> GetConstraints() { List<string> constraints = new List<string>(); string query = string.Format(@"select a.attname as column_name from pg_class t, pg_class i, pg_index ix, pg_attribute a where t.oid = ix.indrelid and i.oid = ix.indexrelid and a.attrelid = t.oid and a.attnum = ANY(ix.indkey) and t.relkind = 'r' and ix.indisunique = true and t.relname = lower('{0}') ;", m_Realm); using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) { conn.Open(); using (NpgsqlDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { // query produces 0 to many rows of single column, so always add the first item in each row constraints.Add((string)rdr[0]); } } return constraints; } } public virtual T[] Get(string field, string key) { return Get(new string[] { field }, new string[] { key }); } public virtual T[] Get(string[] fields, string[] keys) { if (fields.Length != keys.Length) return new T[0]; List<string> terms = new List<string>(); using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand()) { for (int i = 0; i < fields.Length; i++) { if ( m_FieldTypes.ContainsKey(fields[i]) ) cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]])); else cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i])); terms.Add(" \"" + fields[i] + "\" = :" + fields[i]); } string where = String.Join(" AND ", terms.ToArray()); string query = String.Format("SELECT * FROM {0} WHERE {1}", m_Realm, where); cmd.Connection = conn; cmd.CommandText = query; conn.Open(); return DoQuery(cmd); } } protected T[] DoQuery(NpgsqlCommand cmd) { List<T> result = new List<T>(); if (cmd.Connection == null) { cmd.Connection = new NpgsqlConnection(m_connectionString); } if (cmd.Connection.State == ConnectionState.Closed) { cmd.Connection.Open(); } using (NpgsqlDataReader reader = cmd.ExecuteReader()) { if (reader == null) return new T[0]; CheckColumnNames(reader); while (reader.Read()) { T row = new T(); foreach (string name in m_Fields.Keys) { if (m_Fields[name].GetValue(row) is bool) { int v = Convert.ToInt32(reader[name]); m_Fields[name].SetValue(row, v != 0 ? true : false); } else if (m_Fields[name].GetValue(row) is UUID) { UUID uuid = UUID.Zero; UUID.TryParse(reader[name].ToString(), out uuid); m_Fields[name].SetValue(row, uuid); } else if (m_Fields[name].GetValue(row) is int) { int v = Convert.ToInt32(reader[name]); m_Fields[name].SetValue(row, v); } else { m_Fields[name].SetValue(row, reader[name]); } } if (m_DataField != null) { Dictionary<string, string> data = new Dictionary<string, string>(); foreach (string col in m_ColumnNames) { data[col] = reader[col].ToString(); if (data[col] == null) data[col] = String.Empty; } m_DataField.SetValue(row, data); } result.Add(row); } return result.ToArray(); } } public virtual T[] Get(string where) { using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand()) { string query = String.Format("SELECT * FROM {0} WHERE {1}", m_Realm, where); cmd.Connection = conn; cmd.CommandText = query; //m_log.WarnFormat("[PGSQLGenericTable]: SELECT {0} WHERE {1}", m_Realm, where); conn.Open(); return DoQuery(cmd); } } public virtual T[] Get(string where, NpgsqlParameter parameter) { using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand()) { string query = String.Format("SELECT * FROM {0} WHERE {1}", m_Realm, where); cmd.Connection = conn; cmd.CommandText = query; //m_log.WarnFormat("[PGSQLGenericTable]: SELECT {0} WHERE {1}", m_Realm, where); cmd.Parameters.Add(parameter); conn.Open(); return DoQuery(cmd); } } public virtual bool Store(T row) { List<string> constraintFields = GetConstraints(); List<KeyValuePair<string, string>> constraints = new List<KeyValuePair<string, string>>(); using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand()) { StringBuilder query = new StringBuilder(); List<String> names = new List<String>(); List<String> values = new List<String>(); foreach (FieldInfo fi in m_Fields.Values) { names.Add(fi.Name); values.Add(":" + fi.Name); // Temporarily return more information about what field is unexpectedly null for // http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the // InventoryTransferModule or we may be required to substitute a DBNull here. if (fi.GetValue(row) == null) throw new NullReferenceException( string.Format( "[PGSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null", fi.Name, row)); if (constraintFields.Count > 0 && constraintFields.Contains(fi.Name)) { constraints.Add(new KeyValuePair<string, string>(fi.Name, fi.GetValue(row).ToString() )); } if (m_FieldTypes.ContainsKey(fi.Name)) cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row), m_FieldTypes[fi.Name])); else cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row))); } if (m_DataField != null) { Dictionary<string, string> data = (Dictionary<string, string>)m_DataField.GetValue(row); foreach (KeyValuePair<string, string> kvp in data) { if (constraintFields.Count > 0 && constraintFields.Contains(kvp.Key)) { constraints.Add(new KeyValuePair<string, string>(kvp.Key, kvp.Key)); } names.Add(kvp.Key); values.Add(":" + kvp.Key); if (m_FieldTypes.ContainsKey(kvp.Key)) cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value, m_FieldTypes[kvp.Key])); else cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value)); } } query.AppendFormat("UPDATE {0} SET ", m_Realm); int i = 0; for (i = 0; i < names.Count - 1; i++) { query.AppendFormat("\"{0}\" = {1}, ", names[i], values[i]); } query.AppendFormat("\"{0}\" = {1} ", names[i], values[i]); if (constraints.Count > 0) { List<string> terms = new List<string>(); for (int j = 0; j < constraints.Count; j++) { terms.Add(String.Format(" \"{0}\" = :{0}", constraints[j].Key)); } string where = String.Join(" AND ", terms.ToArray()); query.AppendFormat(" WHERE {0} ", where); } cmd.Connection = conn; cmd.CommandText = query.ToString(); conn.Open(); if (cmd.ExecuteNonQuery() > 0) { //m_log.WarnFormat("[PGSQLGenericTable]: Updating {0}", m_Realm); return true; } else { // assume record has not yet been inserted query = new StringBuilder(); query.AppendFormat("INSERT INTO {0} (\"", m_Realm); query.Append(String.Join("\",\"", names.ToArray())); query.Append("\") values (" + String.Join(",", values.ToArray()) + ")"); cmd.Connection = conn; cmd.CommandText = query.ToString(); // m_log.WarnFormat("[PGSQLGenericTable]: Inserting into {0} sql {1}", m_Realm, cmd.CommandText); if (conn.State != ConnectionState.Open) conn.Open(); if (cmd.ExecuteNonQuery() > 0) return true; } return false; } } public virtual bool Delete(string field, string key) { return Delete(new string[] { field }, new string[] { key }); } public virtual bool Delete(string[] fields, string[] keys) { if (fields.Length != keys.Length) return false; List<string> terms = new List<string>(); using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand()) { for (int i = 0; i < fields.Length; i++) { if (m_FieldTypes.ContainsKey(fields[i])) cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]])); else cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i])); terms.Add(" \"" + fields[i] + "\" = :" + fields[i]); } string where = String.Join(" AND ", terms.ToArray()); string query = String.Format("DELETE FROM {0} WHERE {1}", m_Realm, where); cmd.Connection = conn; cmd.CommandText = query; conn.Open(); if (cmd.ExecuteNonQuery() > 0) { //m_log.Warn("[PGSQLGenericTable]: " + deleteCommand); return true; } return false; } } public long GetCount(string field, string key) { return GetCount(new string[] { field }, new string[] { key }); } public long GetCount(string[] fields, string[] keys) { if (fields.Length != keys.Length) return 0; List<string> terms = new List<string>(); using (NpgsqlCommand cmd = new NpgsqlCommand()) { for (int i = 0; i < fields.Length; i++) { cmd.Parameters.AddWithValue(fields[i], keys[i]); terms.Add("\"" + fields[i] + "\" = :" + fields[i]); } string where = String.Join(" and ", terms.ToArray()); string query = String.Format("select count(*) from {0} where {1}", m_Realm, where); cmd.CommandText = query; Object result = DoQueryScalar(cmd); return Convert.ToInt64(result); } } public long GetCount(string where) { using (NpgsqlCommand cmd = new NpgsqlCommand()) { string query = String.Format("select count(*) from {0} where {1}", m_Realm, where); cmd.CommandText = query; object result = DoQueryScalar(cmd); return Convert.ToInt64(result); } } public object DoQueryScalar(NpgsqlCommand cmd) { using (NpgsqlConnection dbcon = new NpgsqlConnection(m_ConnectionString)) { dbcon.Open(); cmd.Connection = dbcon; return cmd.ExecuteScalar(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; #if USE_MDT_EVENTSOURCE using Microsoft.Diagnostics.Tracing; #else using System.Diagnostics.Tracing; #endif using Xunit; #if USE_ETW using Microsoft.Diagnostics.Tracing.Session; #endif using System.Diagnostics; namespace BasicEventSourceTests { internal enum Color { Red, Blue, Green }; internal enum ColorUInt32 : uint { Red, Blue, Green }; internal enum ColorByte : byte { Red, Blue, Green }; internal enum ColorSByte : sbyte { Red, Blue, Green }; internal enum ColorInt16 : short { Red, Blue, Green }; internal enum ColorUInt16 : ushort { Red, Blue, Green }; internal enum ColorInt64 : long { Red, Blue, Green }; internal enum ColorUInt64 : ulong { Red, Blue, Green }; public class TestsWrite { #if USE_ETW // Specifies whether the process is elevated or not. private static readonly Lazy<bool> s_isElevated = new Lazy<bool>(() => AdminHelpers.IsProcessElevated()); private static bool IsProcessElevated => s_isElevated.Value; #endif // USE_ETW [EventData] private struct PartB_UserInfo { public string UserName { get; set; } } /// <summary> /// Tests the EventSource.Write[T] method (can only use the self-describing mechanism). /// Tests the EventListener code path /// </summary> [Fact] [ActiveIssue("dotnet/corefx #19455", TargetFrameworkMonikers.NetFramework)] public void Test_Write_T_EventListener() { using (var listener = new EventListenerListener()) { Test_Write_T(listener); } } /// <summary> /// Tests the EventSource.Write[T] method (can only use the self-describing mechanism). /// Tests the EventListener code path using events instead of virtual callbacks. /// </summary> [Fact] [ActiveIssue("dotnet/corefx #19455", TargetFrameworkMonikers.NetFramework)] public void Test_Write_T_EventListener_UseEvents() { Test_Write_T(new EventListenerListener(true)); } #if USE_ETW /// <summary> /// Tests the EventSource.Write[T] method (can only use the self-describing mechanism). /// Tests the ETW code path /// </summary> [ConditionalFact(nameof(IsProcessElevated))] public void Test_Write_T_ETW() { using (var listener = new EtwListener()) { Test_Write_T(listener); } } #endif //USE_ETW /// <summary> /// Te /// </summary> /// <param name="listener"></param> private void Test_Write_T(Listener listener) { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var logger = new EventSource("EventSourceName")) { var tests = new List<SubTest>(); /*************************************************************************/ tests.Add(new SubTest("Write/Basic/String", delegate () { logger.Write("Greeting", new { msg = "Hello, world!" }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Greeting", evt.EventName); Assert.Equal(evt.PayloadValue(0, "msg"), "Hello, world!"); })); /*************************************************************************/ decimal myMoney = 300; tests.Add(new SubTest("Write/Basic/decimal", delegate () { logger.Write("Decimal", new { money = myMoney }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Decimal", evt.EventName); var eventMoney = evt.PayloadValue(0, "money"); // TOD FIX ME - Fix TraceEvent to return decimal instead of double. //Assert.Equal((decimal)eventMoney, (decimal)300); })); /*************************************************************************/ DateTime now = DateTime.Now; tests.Add(new SubTest("Write/Basic/DateTime", delegate () { logger.Write("DateTime", new { nowTime = now }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("DateTime", evt.EventName); var eventNow = evt.PayloadValue(0, "nowTime"); Assert.Equal(eventNow, now); })); /*************************************************************************/ byte[] byteArray = { 0, 1, 2, 3 }; tests.Add(new SubTest("Write/Basic/byte[]", delegate () { logger.Write("Bytes", new { bytes = byteArray }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Bytes", evt.EventName); var eventArray = evt.PayloadValue(0, "bytes"); Array.Equals(eventArray, byteArray); })); /*************************************************************************/ tests.Add(new SubTest("Write/Basic/PartBOnly", delegate () { // log just a PartB logger.Write("UserInfo", new EventSourceOptions { Keywords = EventKeywords.None }, new { _1 = new PartB_UserInfo { UserName = "Someone Else" } }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("UserInfo", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary<string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal(structValueAsDictionary["UserName"], "Someone Else"); })); /*************************************************************************/ tests.Add(new SubTest("Write/Basic/PartBAndC", delegate () { // log a PartB and a PartC logger.Write("Duration", new EventSourceOptions { Keywords = EventKeywords.None }, new { _1 = new PartB_UserInfo { UserName = "Myself" }, msec = 10 }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Duration", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary<string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal(structValueAsDictionary["UserName"], "Myself"); Assert.Equal(evt.PayloadValue(1, "msec"), 10); })); /*************************************************************************/ /*************************** ENUM TESTING *******************************/ /*************************************************************************/ /*************************************************************************/ GenerateEnumTest<Color>(ref tests, logger, Color.Green); GenerateEnumTest<ColorUInt32>(ref tests, logger, ColorUInt32.Green); GenerateEnumTest<ColorByte>(ref tests, logger, ColorByte.Green); GenerateEnumTest<ColorSByte>(ref tests, logger, ColorSByte.Green); GenerateEnumTest<ColorInt16>(ref tests, logger, ColorInt16.Green); GenerateEnumTest<ColorUInt16>(ref tests, logger, ColorUInt16.Green); GenerateEnumTest<ColorInt64>(ref tests, logger, ColorInt64.Green); GenerateEnumTest<ColorUInt64>(ref tests, logger, ColorUInt64.Green); /*************************************************************************/ /*************************** ARRAY TESTING *******************************/ /*************************************************************************/ /*************************************************************************/ GenerateArrayTest<Boolean>(ref tests, logger, new Boolean[] { false, true, false }); GenerateArrayTest<byte>(ref tests, logger, new byte[] { 1, 10, 100 }); GenerateArrayTest<sbyte>(ref tests, logger, new sbyte[] { 1, 10, 100 }); GenerateArrayTest<Int16>(ref tests, logger, new Int16[] { 1, 10, 100 }); GenerateArrayTest<UInt16>(ref tests, logger, new UInt16[] { 1, 10, 100 }); GenerateArrayTest<Int32>(ref tests, logger, new Int32[] { 1, 10, 100 }); GenerateArrayTest<UInt32>(ref tests, logger, new UInt32[] { 1, 10, 100 }); GenerateArrayTest<Int64>(ref tests, logger, new Int64[] { 1, 10, 100 }); GenerateArrayTest<UInt64>(ref tests, logger, new UInt64[] { 1, 10, 100 }); GenerateArrayTest<Char>(ref tests, logger, new Char[] { 'a', 'c', 'b' }); GenerateArrayTest<Double>(ref tests, logger, new Double[] { 1, 10, 100 }); GenerateArrayTest<Single>(ref tests, logger, new Single[] { 1, 10, 100 }); GenerateArrayTest<IntPtr>(ref tests, logger, new IntPtr[] { (IntPtr)1, (IntPtr)10, (IntPtr)100 }); GenerateArrayTest<UIntPtr>(ref tests, logger, new UIntPtr[] { (UIntPtr)1, (UIntPtr)10, (UIntPtr)100 }); GenerateArrayTest<Guid>(ref tests, logger, new Guid[] { Guid.Empty, new Guid("121a11ee-3bcb-49cc-b425-f4906fb14f72") }); /*************************************************************************/ /*********************** DICTIONARY TESTING ******************************/ /*************************************************************************/ var dict = new Dictionary<string, string>() { { "elem1", "10" }, { "elem2", "20" } }; var dictInt = new Dictionary<string, int>() { { "elem1", 10 }, { "elem2", 20 } }; /*************************************************************************/ tests.Add(new SubTest("Write/Dict/EventWithStringDict_C", delegate() { // log a dictionary logger.Write("EventWithStringDict_C", new { myDict = dict, s = "end" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithStringDict_C", evt.EventName); var keyValues = evt.PayloadValue(0, "myDict"); IDictionary<string, object> vDict = GetDictionaryFromKeyValueArray(keyValues); Assert.Equal(vDict["elem1"], "10"); Assert.Equal(vDict["elem2"], "20"); Assert.Equal(evt.PayloadValue(1, "s"), "end"); })); /*************************************************************************/ tests.Add(new SubTest("Write/Dict/EventWithStringDict_BC", delegate() { // log a PartB and a dictionary as a PartC logger.Write("EventWithStringDict_BC", new { PartB_UserInfo = new { UserName = "Me", LogTime = "Now" }, PartC_Dict = dict, s = "end" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithStringDict_BC", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary<string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal(structValueAsDictionary["UserName"], "Me"); Assert.Equal(structValueAsDictionary["LogTime"], "Now"); var keyValues = evt.PayloadValue(1, "PartC_Dict"); var vDict = GetDictionaryFromKeyValueArray(keyValues); Assert.NotNull(dict); Assert.Equal(vDict["elem1"], "10"); // string values. Assert.Equal(vDict["elem2"], "20"); Assert.Equal(evt.PayloadValue(2, "s"), "end"); })); /*************************************************************************/ tests.Add(new SubTest("Write/Dict/EventWithIntDict_BC", delegate() { // log a Dict<string, int> as a PartC logger.Write("EventWithIntDict_BC", new { PartB_UserInfo = new { UserName = "Me", LogTime = "Now" }, PartC_Dict = dictInt, s = "end" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithIntDict_BC", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary<string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal(structValueAsDictionary["UserName"], "Me"); Assert.Equal(structValueAsDictionary["LogTime"], "Now"); var keyValues = evt.PayloadValue(1, "PartC_Dict"); var vDict = GetDictionaryFromKeyValueArray(keyValues); Assert.NotNull(vDict); Assert.Equal(vDict["elem1"], 10); // Notice they are integers, not strings. Assert.Equal(vDict["elem2"], 20); Assert.Equal(evt.PayloadValue(2, "s"), "end"); })); /*************************************************************************/ /**************************** Empty Event TESTING ************************/ /*************************************************************************/ tests.Add(new SubTest("Write/Basic/Message", delegate () { logger.Write("EmptyEvent"); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EmptyEvent", evt.EventName); })); /*************************************************************************/ /**************************** EventSourceOptions TESTING *****************/ /*************************************************************************/ EventSourceOptions options = new EventSourceOptions(); options.Level = EventLevel.LogAlways; options.Keywords = EventKeywords.All; options.Opcode = EventOpcode.Info; options.Tags = EventTags.None; tests.Add(new SubTest("Write/Basic/MessageOptions", delegate () { logger.Write("EmptyEvent", options); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EmptyEvent", evt.EventName); })); tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios", delegate () { logger.Write("OptionsEvent", options, new { OptionsEvent = "test options!" }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("OptionsEvent", evt.EventName); Assert.Equal(evt.PayloadValue(0, "OptionsEvent"), "test options!"); })); tests.Add(new SubTest("Write/Basic/WriteOfTWithRefOptios", delegate () { var v = new { OptionsEvent = "test ref options!" }; logger.Write("RefOptionsEvent", ref options, ref v); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("RefOptionsEvent", evt.EventName); Assert.Equal(evt.PayloadValue(0, "OptionsEvent"), "test ref options!"); })); tests.Add(new SubTest("Write/Basic/WriteOfTWithNullString", delegate () { string nullString = null; logger.Write("NullStringEvent", new { a = (string)null, b = nullString }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("NullStringEvent", evt.EventName); Assert.Equal(evt.PayloadValue(0, "a"), ""); Assert.Equal(evt.PayloadValue(1, "b"), ""); })); Guid activityId = new Guid("00000000-0000-0000-0000-000000000001"); Guid relActivityId = new Guid("00000000-0000-0000-0000-000000000002"); tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios", delegate () { var v = new { ActivityMsg = "test activity!" }; logger.Write("ActivityEvent", ref options, ref activityId, ref relActivityId, ref v); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("ActivityEvent", evt.EventName); Assert.Equal(evt.PayloadValue(0, "ActivityMsg"), "test activity!"); })); // If you only wish to run one or several of the tests you can filter them here by // Uncommenting the following line. // tests = tests.FindAll(test => Regex.IsMatch(test.Name, "Write/Basic/EventII")); // Here is where we actually run tests. First test the ETW path EventTestHarness.RunTests(tests, listener, logger); } TestUtilities.CheckNoEventSourcesRunning("Stop"); } /// <summary> /// This is not a user error but it is something unusual. /// You can use the Write API in a EventSource that was did not /// Declare SelfDescribingSerialization. In that case THOSE /// events MUST use SelfDescribing serialization. /// </summary> [Fact] [ActiveIssue("dotnet/corefx #18806", TargetFrameworkMonikers.NetFramework)] [ActiveIssue("https://github.com/dotnet/corefx/issues/27106")] public void Test_Write_T_In_Manifest_Serialization() { using (var eventListener = new EventListenerListener()) { #if USE_ETW EtwListener etwListener = null; #endif try { var listenerGenerators = new List<Func<Listener>>(); listenerGenerators.Add(() => eventListener); #if USE_ETW if(IsProcessElevated) { etwListener = new EtwListener(); listenerGenerators.Add(() => etwListener); } #endif // USE_ETW foreach (Func<Listener> listenerGenerator in listenerGenerators) { var events = new List<Event>(); using (var listener = listenerGenerator()) { Debug.WriteLine("Testing Listener " + listener); // Create an eventSource with manifest based serialization using (var logger = new SdtEventSources.EventSourceTest()) { listener.OnEvent = delegate (Event data) { events.Add(data); }; listener.EventSourceSynchronousEnable(logger); // Use the Write<T> API. This is OK logger.Write("MyTestEvent", new { arg1 = 3, arg2 = "hi" }); } } Assert.Equal(events.Count, 1); Event _event = events[0]; Assert.Equal("MyTestEvent", _event.EventName); Assert.Equal(3, (int)_event.PayloadValue(0, "arg1")); Assert.Equal("hi", (string)_event.PayloadValue(1, "arg2")); } } finally { #if USE_ETW if(etwListener != null) { etwListener.Dispose(); } #endif // USE_ETW } } } private void GenerateEnumTest<T>(ref List<SubTest> tests, EventSource logger, T enumValue) { string subTestName = enumValue.GetType().ToString(); tests.Add(new SubTest("Write/Enum/EnumEvent" + subTestName, delegate () { T c = enumValue; // log an array logger.Write("EnumEvent" + subTestName, new { b = "start", v = c, s = "end" }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EnumEvent" + subTestName, evt.EventName); Assert.Equal(evt.PayloadValue(0, "b"), "start"); if (evt.IsEtw) { var value = evt.PayloadValue(1, "v"); Assert.Equal(2, int.Parse(value.ToString())); // Green has the int value of 2. } else { Assert.Equal(evt.PayloadValue(1, "v"), enumValue); } Assert.Equal(evt.PayloadValue(2, "s"), "end"); })); } private void GenerateArrayTest<T>(ref List<SubTest> tests, EventSource logger, T[] array) { string typeName = array.GetType().GetElementType().ToString(); tests.Add(new SubTest("Write/Array/" + typeName, delegate () { // log an array logger.Write("SomeEvent" + typeName, new { a = array, s = "end" }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("SomeEvent" + typeName, evt.EventName); var eventArray = evt.PayloadValue(0, "a"); Array.Equals(array, eventArray); Assert.Equal("end", evt.PayloadValue(1, "s")); })); } /// <summary> /// Convert an array of key value pairs (as ETW structs) into a dictionary with those values. /// </summary> /// <param name="structValue"></param> /// <returns></returns> private IDictionary<string, object> GetDictionaryFromKeyValueArray(object structValue) { var ret = new Dictionary<string, object>(); var asArray = structValue as object[]; Assert.NotNull(asArray); foreach (var item in asArray) { var keyValue = item as IDictionary<string, object>; Assert.Equal(keyValue.Count, 2); ret.Add((string)keyValue["Key"], keyValue["Value"]); } return ret; } } }
using System.Diagnostics; using System.Linq; using EFSqlTranslator.EFModels; using EFSqlTranslator.Translation; using EFSqlTranslator.Translation.DbObjects.SqliteObjects; using Xunit; namespace EFSqlTranslator.Tests.TranslatorTests { [CategoryReadMe( Index = 2, Title = "Translating Select", Description = @" In this section, we will show you multiple ways to select data. You can basically: 1. Translate an anonymous object by selecting columns from different table. 2. Do multiple Selects to get the final output. 3. Use relations in your Select method calls." )] public class SelectTranslationTests { [Fact] [TranslationReadMe( Index = 0, Title = "Select out only required columns" )] public void Test_Translate_Select_Columns() { using (var db = new TestingContext()) { var query = db.Posts .Where(p => p.User.UserName != null) .Select(p => new { p.Content, p.Title }); var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory()); var sql = script.ToString(); const string expected = @" select p0.Content, p0.Title from Posts p0 inner join Users u0 on p0.UserId = u0.UserId where u0.UserName is not null"; TestUtils.AssertStringEqual(expected, sql); } } [Fact] [TranslationReadMe( Index = 1, Title = "Select out required columns from related entity" )] public void Test_Translate_Select_Columns_With_Relations() { using (var db = new TestingContext()) { var query = db.Posts .Where(p => p.User.UserName != null) .Select(p => new { p.Content, p.Blog.User.UserName }); var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory()); var sql = script.ToString(); const string expected = @" select p0.Content, u1.UserName from Posts p0 inner join Users u0 on p0.UserId = u0.UserId left outer join Blogs b0 on p0.BlogId = b0.BlogId left outer join Users u1 on b0.UserId = u1.UserId where u0.UserName is not null"; TestUtils.AssertStringEqual(expected, sql); } } [Fact] [TranslationReadMe( Index = 0, Title = "Join on custom condition" )] public void Test_Translate_SelectRelations_TablesStartWithSameLetter() { using (var db = new TestingContext()) { var query = db.Routes.Select(x => new { x.RouteId, x.Domain.Name }); var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory()); var sql = script.ToString(); const string expected = @" select d0.pk_route_id as 'RouteId', d1.domain_name as 'Name' from db_route d0 left outer join db_domain d1 on d0.fk_domain_id = d1.pk_domain_id"; TestUtils.AssertStringEqual(expected, sql); } } [Fact] [TranslationReadMe( Index = 2, Title = "Translate up selection with columns and expression" )] public void Test_Translate_Select_Columns_With_Expressions() { using (var db = new TestingContext()) { var query = db.Posts .Where(p => p.Content != null) .Select(p => new { TitleContent = p.Title + "|" + p.Content, Num = p.BlogId / p.User.UserId }); var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory()); var sql = script.ToString(); const string expected = @" select (p0.Title + '|') + p0.Content as 'TitleContent', p0.BlogId / u0.UserId as 'Num' from Posts p0 inner join Users u0 on p0.UserId = u0.UserId where p0.Content is not null"; TestUtils.AssertStringEqual(expected, sql); } } [Fact] public void Test_Select_Ref_And_Columns() { using (var db = new TestingContext()) { var query = db.Posts .Where(p => p.Content != null) .Select(p => new { p.Blog, p.User.UserName }); var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory()); var sql = script.ToString(); const string expected = @" select b0.*, u0.UserName from Posts p0 left outer join Blogs b0 on p0.BlogId = b0.BlogId left outer join Users u0 on p0.UserId = u0.UserId where p0.Content is not null"; TestUtils.AssertStringEqual(expected, sql); } } [Fact] [TranslationReadMe( Index = 3, Title = "Multiple selections with selecting whole entity", Description = "This will become really useful when combining with Group By." )] public void Test_Multiple_Select_Calls() { using (var db = new TestingContext()) { var query = db.Posts .Where(p => p.Content != null) .Select(p => new { p.Blog, p.User.UserName }) .Select(p => new { p.Blog.Url, p.Blog.Name, p.UserName }); var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory()); var sql = script.ToString(); const string expected = @" select b0.Url, b0.Name, u0.UserName from Posts p0 left outer join Blogs b0 on p0.BlogId = b0.BlogId left outer join Users u0 on p0.UserId = u0.UserId where p0.Content is not null"; TestUtils.AssertStringEqual(expected, sql); } } [Fact] public void Test_Multiple_Select_Calls1() { using (var db = new TestingContext()) { var query = db.Posts .Where(p => p.Content != null) .Select(p => p.Blog) .Select(b => b.Url); var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory()); var sql = script.ToString(); const string expected = @" select b0.Url from Posts p0 left outer join Blogs b0 on p0.BlogId = b0.BlogId where p0.Content is not null"; Trace.WriteLine(sql); TestUtils.AssertStringEqual(expected, sql); } } [Fact] public void Test_Multiple_Select_Calls2() { using (var db = new TestingContext()) { var query = db.Posts .Where(p => p.Content != null) .Select(p => p.Blog) .Select(g => new { g.User, g.Url }) .Select(g => new { g.User.UserName, g.Url }); var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory()); var sql = script.ToString(); const string expected = @" select u0.UserName, sq0.Url from ( select b0.UserId as 'UserId_jk0', b0.Url from Posts p0 left outer join Blogs b0 on p0.BlogId = b0.BlogId where p0.Content is not null ) sq0 left outer join Users u0 on sq0.UserId_jk0 = u0.UserId"; TestUtils.AssertStringEqual(expected, sql); } } [Fact] public void Test_Multiple_Select_Calls_After_Grouping() { using (var db = new TestingContext()) { var query = db.Posts .Where(p => p.Content != null) .Select(p => new { p.Blog }) .GroupBy(g => new { g.Blog, g.Blog.Url }) .Select(p => new { p.Key.Blog, p.Key.Blog.User, p.Key.Url }) .Select(g => new { g.Blog.Name, g.User.UserName, g.Url }); var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory()); var sql = script.ToString(); const string expected = @" select sq0.Name, u0.UserName, sq0.Url from ( select b0.Url, b0.BlogId, b0.UserId as 'UserId_jk0', b0.Name from Posts p0 left outer join Blogs b0 on p0.BlogId = b0.BlogId where p0.Content is not null ) sq0 left outer join Users u0 on sq0.UserId_jk0 = u0.UserId group by sq0.BlogId, sq0.Url, u0.UserId, sq0.Name, u0.UserName"; TestUtils.AssertStringEqual(expected, sql); } } [Fact] public void Test_Multiple_Aggregatons() { using (var db = new TestingContext()) { var query = db.Blogs .Select(b => new { Cnt1 = b.Posts.Count(p => p.LikeCount > 10), Cnt2 = b.Posts.Count(p => p.LikeCount < 50) }); var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory()); var sql = script.ToString(); const string expected = @" select coalesce(sq0.count0, 0) as 'Cnt1', coalesce(sq0.count1, 0) as 'Cnt2' from Blogs b0 left outer join ( select p0.BlogId as 'BlogId_jk0', count(case when p0.LikeCount > 10 then 1 else null end) as 'count0', count(case when p0.LikeCount < 50 then 1 else null end) as 'count1' from Posts p0 group by p0.BlogId ) sq0 on b0.BlogId = sq0.BlogId_jk0"; TestUtils.AssertStringEqual(expected, sql); } } [Fact] public void Test_Select_NotBoolean() { using (var db = new TestingContext()) { var query = db.Comments .Select(c => new { Val = !c.IsDeleted }); var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory()); var sql = script.ToString(); const string expected = @" select case when c0.IsDeleted != 1 then 1 else 0 end as 'Val' from Comments c0"; TestUtils.AssertStringEqual(expected, sql); } } [Fact] public void Test_Select_Return_Single_Value() { using (var db = new TestingContext()) { var query = db.Blogs .Where(b => b.BlogId > 0) .Select(b => b.BlogId); var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory()); var sql = script.ToString(); const string expected = @" select b0.BlogId from Blogs b0 where b0.BlogId > 0"; TestUtils.AssertStringEqual(expected, sql); } } [Fact] public void Test_Select_Return_Single_Value_With_Aggregation2() { using (var db = new TestingContext()) { var query = db.Blogs .Where(b => b.BlogId > 0) .Select(b => b.Posts.Sum(p => p.PostId)); var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory()); var sql = script.ToString(); const string expected = @" select coalesce(sq0.sum0, 0) as 'coalesce0' from Blogs b0 left outer join ( select p0.BlogId as 'BlogId_jk0', sum(p0.PostId) * 1.0 as 'sum0' from Posts p0 group by p0.BlogId ) sq0 on b0.BlogId = sq0.BlogId_jk0 where b0.BlogId > 0"; TestUtils.AssertStringEqual(expected, sql); } } } }
using AutoDI; using System; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.DependencyInjection { public static class AutoDIServiceCollectionMixins { public static IServiceCollection AddAutoDIService(this IServiceCollection services, Type serviceType, Type implementationType, Lifetime lifetime) { if (services is null) throw new ArgumentNullException(nameof(services)); services.Add(new AutoDIServiceDescriptor(serviceType, implementationType, lifetime)); return services; } public static IServiceCollection AddAutoDIService(this IServiceCollection services, Type serviceType, Type implementationType, Func<IServiceProvider, object> implementationFactory, Lifetime lifetime) { if (services is null) throw new ArgumentNullException(nameof(services)); services.Add(new AutoDIServiceDescriptor(serviceType, implementationType, implementationFactory, lifetime)); return services; } public static IServiceCollection AddAutoDITransient(this IServiceCollection services, Type serviceType, Type implementationType) { return services.AddAutoDIService(serviceType, implementationType, Lifetime.Transient); } public static IServiceCollection AddAutoDITransient(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { return services.AddAutoDIService(serviceType, serviceType, implementationFactory, Lifetime.Transient); } public static IServiceCollection AddAutoDITransient<TService, TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { return services.AddAutoDIService(typeof(TService), typeof(TImplementation), Lifetime.Transient); } public static IServiceCollection AddAutoDITransient(this IServiceCollection services, Type serviceType) { return services.AddAutoDIService(serviceType, serviceType, Lifetime.Transient); } public static IServiceCollection AddAutoDITransient<TService>(this IServiceCollection services) where TService : class { return services.AddAutoDIService(typeof(TService), typeof(TService), Lifetime.Transient); } public static IServiceCollection AddAutoDITransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { return services.AddAutoDIService(typeof(TService), typeof(TService), implementationFactory, Lifetime.Transient); } public static IServiceCollection AddAutoDITransient<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { return services.AddAutoDIService(typeof(TService), typeof(TImplementation), implementationFactory, Lifetime.Transient); } public static IServiceCollection AddAutoDIWeakSingleton(this IServiceCollection services, Type serviceType, Type implementationType) { return services.AddAutoDIService(serviceType, implementationType, Lifetime.WeakSingleton); } public static IServiceCollection AddAutoDIWeakSingleton(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { return services.AddAutoDIService(serviceType, serviceType, implementationFactory, Lifetime.WeakSingleton); } public static IServiceCollection AddAutoDIWeakSingleton<TService, TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { return services.AddAutoDIService(typeof(TService), typeof(TImplementation), Lifetime.WeakSingleton); } public static IServiceCollection AddAutoDIWeakSingleton(this IServiceCollection services, Type serviceType) { return services.AddAutoDIService(serviceType, serviceType, Lifetime.WeakSingleton); } public static IServiceCollection AddAutoDIWeakSingleton<TService>(this IServiceCollection services) where TService : class { return services.AddAutoDIService(typeof(TService), typeof(TService), Lifetime.WeakSingleton); } public static IServiceCollection AddAutoDIWeakSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { return services.AddAutoDIService(typeof(TService), typeof(TService), implementationFactory, Lifetime.WeakSingleton); } public static IServiceCollection AddAutoDIWeakSingleton<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { return services.AddAutoDIService(typeof(TService), typeof(TImplementation), implementationFactory, Lifetime.WeakSingleton); } public static IServiceCollection AddAutoDIScoped(this IServiceCollection services, Type serviceType, Type implementationType) { return services.AddAutoDIService(serviceType, implementationType, Lifetime.Scoped); } public static IServiceCollection AddAutoDIScoped(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { return services.AddAutoDIService(serviceType, serviceType, implementationFactory, Lifetime.Scoped); } public static IServiceCollection AddAutoDIScoped<TService, TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { return services.AddAutoDIService(typeof(TService), typeof(TImplementation), Lifetime.Scoped); } public static IServiceCollection AddAutoDIScoped(this IServiceCollection services, Type serviceType) { return services.AddAutoDIService(serviceType, serviceType, Lifetime.Scoped); } public static IServiceCollection AddAutoDIScoped<TService>(this IServiceCollection services) where TService : class { return services.AddAutoDIService(typeof(TService), typeof(TService), Lifetime.Scoped); } public static IServiceCollection AddAutoDIScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { return services.AddAutoDIService(typeof(TService), typeof(TService), implementationFactory, Lifetime.Scoped); } public static IServiceCollection AddAutoDIScoped<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { return services.AddAutoDIService(typeof(TService), typeof(TImplementation), implementationFactory, Lifetime.Scoped); } public static IServiceCollection AddAutoDILazySingleton(this IServiceCollection services, Type serviceType, Type implementationType) { return services.AddAutoDIService(serviceType, implementationType, Lifetime.LazySingleton); } public static IServiceCollection AddAutoDILazySingleton(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { return services.AddAutoDIService(serviceType, serviceType, implementationFactory, Lifetime.LazySingleton); } public static IServiceCollection AddAutoDILazySingleton<TService, TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { return services.AddAutoDIService(typeof(TService), typeof(TImplementation), Lifetime.LazySingleton); } public static IServiceCollection AddAutoDILazySingleton(this IServiceCollection services, Type serviceType) { return services.AddAutoDIService(serviceType, serviceType, Lifetime.Singleton); } public static IServiceCollection AddAutoDILazySingleton<TService>(this IServiceCollection services) where TService : class { return services.AddAutoDIService(typeof(TService), typeof(TService), Lifetime.LazySingleton); } public static IServiceCollection AddAutoDILazySingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { return services.AddAutoDIService(typeof(TService), typeof(TService), implementationFactory, Lifetime.LazySingleton); } public static IServiceCollection AddAutoDILazySingleton<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { return services.AddAutoDIService(typeof(TService), typeof(TImplementation), implementationFactory, Lifetime.LazySingleton); } public static IServiceCollection AddAutoDISingleton(this IServiceCollection services, Type serviceType, Type implementationType) { return services.AddAutoDIService(serviceType, implementationType, Lifetime.Singleton); } public static IServiceCollection AddAutoDISingleton(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { return services.AddAutoDIService(serviceType, serviceType, implementationFactory, Lifetime.Singleton); } public static IServiceCollection AddAutoDISingleton<TService, TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { return services.AddAutoDIService(typeof(TService), typeof(TImplementation), Lifetime.Singleton); } public static IServiceCollection AddAutoDISingleton(this IServiceCollection services, Type serviceType) { return services.AddAutoDIService(serviceType, serviceType, Lifetime.Singleton); } public static IServiceCollection AddAutoDISingleton<TService>(this IServiceCollection services) where TService : class { return services.AddAutoDIService(typeof(TService), typeof(TService), Lifetime.Singleton); } public static IServiceCollection AddAutoDISingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { return services.AddAutoDIService(typeof(TService), typeof(TService), implementationFactory, Lifetime.Singleton); } public static IServiceCollection AddAutoDISingleton<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { return services.AddAutoDIService(typeof(TService), typeof(TImplementation), implementationFactory, Lifetime.Singleton); } public static IServiceCollection AddAutoDISingleton(this IServiceCollection services, Type serviceType, object implementationInstance) { return services.AddAutoDIService(serviceType, implementationInstance?.GetType(), provider => implementationInstance, Lifetime.Singleton); } public static IServiceCollection AddAutoDISingleton<TService>(this IServiceCollection services, TService implementationInstance) where TService : class { return services.AddAutoDIService(typeof(TService), implementationInstance?.GetType(), provider => implementationInstance, Lifetime.Singleton); } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Web; using Microsoft.Xrm.Portal.Configuration; using Microsoft.Xrm.Portal.Runtime; namespace Microsoft.Xrm.Portal.Web.Handlers { /// <summary> /// A handler for serving embedded resources. /// </summary> /// <remarks> /// The <see cref="HttpCachePolicy"/> cache policy can be adjusted by the following configuration. /// <code> /// <![CDATA[ /// <configuration> /// /// <configSections> /// <section name="microsoft.xrm.portal" type="Microsoft.Xrm.Portal.Configuration.PortalCrmSection, Microsoft.Xrm.Portal"/> /// </configSections> /// /// <microsoft.xrm.portal> /// <cachePolicy> /// <embeddedResource /// cacheExtension="" /// cacheability="Public" [NoCache | Private | Public | Server | ServerAndNoCache | ServerAndPrivate] /// expires="" /// maxAge="01:00:00" [HH:MM:SS] /// revalidation="" [AllCaches | ProxyCaches | None] /// slidingExpiration="" [false | true] /// validUntilExpires="" [false | true] /// varyByCustom="" /// varyByContentEncodings="gzip;deflate" /// varyByContentHeaders="" /// varyByParams="*" /// /> /// </cachePolicy> /// </microsoft.xrm.portal> /// /// </configuration> /// ]]> /// </code> /// </remarks> /// <seealso cref="PortalCrmConfigurationManager"/> /// <seealso cref="HttpCachePolicyElement"/> public sealed class EmbeddedResourceHttpHandler : IHttpHandler { private readonly IEnumerable<EmbeddedResourceAssemblyAttribute> _mappings; private readonly string[] _paths; public EmbeddedResourceHttpHandler() : this((string[])null) { } public EmbeddedResourceHttpHandler(params string[] paths) : this(Web.Utility.GetEmbeddedResourceMappingAttributes().ToList(), paths) { } public EmbeddedResourceHttpHandler(IEnumerable<EmbeddedResourceAssemblyAttribute> mappings, params string[] paths) { mappings.ThrowOnNull("mappings"); paths.ThrowOnNull("paths"); _mappings = mappings; _paths = paths; } public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { var paths = GetPaths(context); if (paths.Count() == 1) { Render(context, paths.Single()); } else { Render(context, paths); } } private IEnumerable<string> GetPaths(HttpContext context) { return _paths ?? context.Request["paths"].Split(','); } private void Render(HttpContext context, string virtualPath) { Assembly assembly; string resourceName; if (TryFindResource(virtualPath, out assembly, out resourceName)) { // compute and check the etag var ifNoneMatch = context.Request.Headers["If-None-Match"]; var eTag = Utility.ComputeETag(assembly, resourceName); if (ifNoneMatch == eTag) { context.Response.StatusCode = (int)HttpStatusCode.NotModified; return; } if (!string.IsNullOrWhiteSpace(eTag)) { context.Response.Cache.SetETag(eTag); } SetResponseParameters(context.Response); SetResponseParameters(context.Response, virtualPath, resourceName); RenderResource(assembly, resourceName, context.Response.OutputStream); } } private void Render(HttpContext context, IEnumerable<string> virtualPaths) { // gather the resources into memory var data = new MemoryStream(); foreach (var path in virtualPaths) { Assembly assembly; string resourceName; if (TryFindResource(path, out assembly, out resourceName)) { SetResponseParameters(context.Response, path, resourceName); RenderResource(assembly, resourceName, data); } } data.Position = 0; var ifNoneMatch = context.Request.Headers["If-None-Match"]; var eTag = Utility.ComputeETag(data); if (ifNoneMatch == eTag) { context.Response.StatusCode = (int)HttpStatusCode.NotModified; return; } if (!string.IsNullOrWhiteSpace(eTag)) { context.Response.Cache.SetETag(eTag); } SetResponseParameters(context.Response); data.Position = 0; RenderResource(data, context.Response.OutputStream); } private bool TryFindResource(string virtualPath, out Assembly assembly, out string resourceName) { var mapping = _mappings.Match(virtualPath); if (mapping != null) { // check if this file exists as an embedded resource var resources = mapping.FindResource(virtualPath); if (resources != null) { assembly = mapping.Assembly; resourceName = resources.ResourceName; return true; } } assembly = null; resourceName = null; return false; } private static void RenderResource(Assembly assembly, string resourceName, Stream output) { using (var stream = assembly.GetManifestResourceStream(resourceName)) { RenderResource(stream, output); } } private static void RenderResource(Stream input, Stream output) { var buffer = new byte[4096]; using (var reader = new BinaryReader(input)) { int bytesRead; do { bytesRead = reader.Read(buffer, 0, buffer.Length); output.Write(buffer, 0, bytesRead); } while (bytesRead == buffer.Length); } } private static void SetResponseParameters(HttpResponse response) { var section = PortalCrmConfigurationManager.GetPortalCrmSection(); var policy = section.CachePolicy.EmbeddedResource; Utility.SetResponseCachePolicy(policy, response, HttpCacheability.Public, defaultVaryByContentEncodings: "gzip;deflate"); } private static void SetResponseParameters(HttpResponse response, string virtualPath, string resourceName) { var extensionWithDot = Path.GetExtension(virtualPath); var extension = extensionWithDot != null ? extensionWithDot.TrimStart('.') : string.Empty; string contentType; if (!string.IsNullOrWhiteSpace(extension) && _mimeMap.TryGetValue(extension, out contentType)) { response.ContentType = contentType; } } #region IIS://localhost/MimeMap private static readonly Dictionary<string, string> _mimeMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "323", "text/h323" }, { "aaf", "application/octet-stream" }, { "aca", "application/octet-stream" }, { "accdb", "application/msaccess" }, { "accde", "application/msaccess" }, { "accdt", "application/msaccess" }, { "acx", "application/internet-property-stream" }, { "afm", "application/octet-stream" }, { "ai", "application/postscript" }, { "aif", "audio/x-aiff" }, { "aifc", "audio/aiff" }, { "aiff", "audio/aiff" }, { "application", "application/x-ms-application" }, { "art", "image/x-jg" }, { "asd", "application/octet-stream" }, { "asf", "video/x-ms-asf" }, { "asi", "application/octet-stream" }, { "asm", "text/plain" }, { "asr", "video/x-ms-asf" }, { "asx", "video/x-ms-asf" }, { "atom", "application/atom+xml" }, { "au", "audio/basic" }, { "avi", "video/x-msvideo" }, { "axs", "application/olescript" }, { "bas", "text/plain" }, { "bcpio", "application/x-bcpio" }, { "bin", "application/octet-stream" }, { "bmp", "image/bmp" }, { "c", "text/plain" }, { "cab", "application/octet-stream" }, { "calx", "application/vnd.ms-office.calx" }, { "cat", "application/vnd.ms-pki.seccat" }, { "cdf", "application/x-cdf" }, { "chm", "application/octet-stream" }, { "class", "application/x-java-applet" }, { "clp", "application/x-msclip" }, { "cmx", "image/x-cmx" }, { "cnf", "text/plain" }, { "cod", "image/cis-cod" }, { "cpio", "application/x-cpio" }, { "cpp", "text/plain" }, { "crd", "application/x-mscardfile" }, { "crl", "application/pkix-crl" }, { "crt", "application/x-x509-ca-cert" }, { "csh", "application/x-csh" }, { "css", "text/css" }, { "csv", "application/octet-stream" }, { "cur", "application/octet-stream" }, { "dcr", "application/x-director" }, { "deploy", "application/octet-stream" }, { "der", "application/x-x509-ca-cert" }, { "dib", "image/bmp" }, { "dir", "application/x-director" }, { "disco", "text/xml" }, { "dll", "application/x-msdownload" }, { "dll.config", "text/xml" }, { "dlm", "text/dlm" }, { "doc", "application/msword" }, { "docm", "application/vnd.ms-word.document.macroEnabled.12" }, { "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }, { "dot", "application/msword" }, { "dotm", "application/vnd.ms-word.template.macroEnabled.12" }, { "dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template" }, { "dsp", "application/octet-stream" }, { "dtd", "text/xml" }, { "dvi", "application/x-dvi" }, { "dwf", "drawing/x-dwf" }, { "dwp", "application/octet-stream" }, { "dxr", "application/x-director" }, { "eml", "message/rfc822" }, { "emz", "application/octet-stream" }, { "eot", "application/octet-stream" }, { "eps", "application/postscript" }, { "etx", "text/x-setext" }, { "evy", "application/envoy" }, { "exe", "application/octet-stream" }, { "exe.config", "text/xml" }, { "fdf", "application/vnd.fdf" }, { "fif", "application/fractals" }, { "fla", "application/octet-stream" }, { "flr", "x-world/x-vrml" }, { "flv", "video/x-flv" }, { "gif", "image/gif" }, { "gtar", "application/x-gtar" }, { "gz", "application/x-gzip" }, { "h", "text/plain" }, { "hdf", "application/x-hdf" }, { "hdml", "text/x-hdml" }, { "hhc", "application/x-oleobject" }, { "hhk", "application/octet-stream" }, { "hhp", "application/octet-stream" }, { "hlp", "application/winhlp" }, { "hqx", "application/mac-binhex40" }, { "hta", "application/hta" }, { "htc", "text/x-component" }, { "htm", "text/html" }, { "html", "text/html" }, { "htt", "text/webviewhtml" }, { "hxt", "text/html" }, { "ico", "image/x-icon" }, { "ics", "application/octet-stream" }, { "ief", "image/ief" }, { "iii", "application/x-iphone" }, { "inf", "application/octet-stream" }, { "ins", "application/x-internet-signup" }, { "isp", "application/x-internet-signup" }, { "IVF", "video/x-ivf" }, { "jar", "application/java-archive" }, { "java", "application/octet-stream" }, { "jck", "application/liquidmotion" }, { "jcz", "application/liquidmotion" }, { "jfif", "image/pjpeg" }, { "jpb", "application/octet-stream" }, { "jpe", "image/jpeg" }, { "jpeg", "image/jpeg" }, { "jpg", "image/jpeg" }, { "js", "application/x-javascript" }, { "jsx", "text/jscript" }, { "latex", "application/x-latex" }, { "lit", "application/x-ms-reader" }, { "lpk", "application/octet-stream" }, { "lsf", "video/x-la-asf" }, { "lsx", "video/x-la-asf" }, { "lzh", "application/octet-stream" }, { "m13", "application/x-msmediaview" }, { "m14", "application/x-msmediaview" }, { "m1v", "video/mpeg" }, { "m3u", "audio/x-mpegurl" }, { "man", "application/x-troff-man" }, { "manifest", "application/x-ms-manifest" }, { "map", "text/plain" }, { "mdb", "application/x-msaccess" }, { "mdp", "application/octet-stream" }, { "me", "application/x-troff-me" }, { "mht", "message/rfc822" }, { "mhtml", "message/rfc822" }, { "mid", "audio/mid" }, { "midi", "audio/mid" }, { "mix", "application/octet-stream" }, { "mmf", "application/x-smaf" }, { "mno", "text/xml" }, { "mny", "application/x-msmoney" }, { "mov", "video/quicktime" }, { "movie", "video/x-sgi-movie" }, { "mp2", "video/mpeg" }, { "mp3", "audio/mpeg" }, { "mpa", "video/mpeg" }, { "mpe", "video/mpeg" }, { "mpeg", "video/mpeg" }, { "mpg", "video/mpeg" }, { "mpp", "application/vnd.ms-project" }, { "mpv2", "video/mpeg" }, { "ms", "application/x-troff-ms" }, { "msi", "application/octet-stream" }, { "mso", "application/octet-stream" }, { "mvb", "application/x-msmediaview" }, { "mvc", "application/x-miva-compiled" }, { "nc", "application/x-netcdf" }, { "nsc", "video/x-ms-asf" }, { "nws", "message/rfc822" }, { "ocx", "application/octet-stream" }, { "oda", "application/oda" }, { "odc", "text/x-ms-odc" }, { "ods", "application/oleobject" }, { "one", "application/onenote" }, { "onea", "application/onenote" }, { "onetoc", "application/onenote" }, { "onetoc2", "application/onenote" }, { "onetmp", "application/onenote" }, { "onepkg", "application/onenote" }, { "osdx", "application/opensearchdescription+xml" }, { "p10", "application/pkcs10" }, { "p12", "application/x-pkcs12" }, { "p7b", "application/x-pkcs7-certificates" }, { "p7c", "application/pkcs7-mime" }, { "p7m", "application/pkcs7-mime" }, { "p7r", "application/x-pkcs7-certreqresp" }, { "p7s", "application/pkcs7-signature" }, { "pbm", "image/x-portable-bitmap" }, { "pcx", "application/octet-stream" }, { "pcz", "application/octet-stream" }, { "pdf", "application/pdf" }, { "pfb", "application/octet-stream" }, { "pfm", "application/octet-stream" }, { "pfx", "application/x-pkcs12" }, { "pgm", "image/x-portable-graymap" }, { "pko", "application/vnd.ms-pki.pko" }, { "pma", "application/x-perfmon" }, { "pmc", "application/x-perfmon" }, { "pml", "application/x-perfmon" }, { "pmr", "application/x-perfmon" }, { "pmw", "application/x-perfmon" }, { "png", "image/png" }, { "pnm", "image/x-portable-anymap" }, { "pnz", "image/png" }, { "pot", "application/vnd.ms-powerpoint" }, { "potm", "application/vnd.ms-powerpoint.template.macroEnabled.12" }, { "potx", "application/vnd.openxmlformats-officedocument.presentationml.template" }, { "ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12" }, { "ppm", "image/x-portable-pixmap" }, { "pps", "application/vnd.ms-powerpoint" }, { "ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12" }, { "ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow" }, { "ppt", "application/vnd.ms-powerpoint" }, { "pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12" }, { "pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" }, { "prf", "application/pics-rules" }, { "prm", "application/octet-stream" }, { "prx", "application/octet-stream" }, { "ps", "application/postscript" }, { "psd", "application/octet-stream" }, { "psm", "application/octet-stream" }, { "psp", "application/octet-stream" }, { "pub", "application/x-mspublisher" }, { "qt", "video/quicktime" }, { "qtl", "application/x-quicktimeplayer" }, { "qxd", "application/octet-stream" }, { "ra", "audio/x-pn-realaudio" }, { "ram", "audio/x-pn-realaudio" }, { "rar", "application/octet-stream" }, { "ras", "image/x-cmu-raster" }, { "rf", "image/vnd.rn-realflash" }, { "rgb", "image/x-rgb" }, { "rm", "application/vnd.rn-realmedia" }, { "rmi", "audio/mid" }, { "roff", "application/x-troff" }, { "rpm", "audio/x-pn-realaudio-plugin" }, { "rtf", "application/rtf" }, { "rtx", "text/richtext" }, { "scd", "application/x-msschedule" }, { "sct", "text/scriptlet" }, { "sea", "application/octet-stream" }, { "setpay", "application/set-payment-initiation" }, { "setreg", "application/set-registration-initiation" }, { "sgml", "text/sgml" }, { "sh", "application/x-sh" }, { "shar", "application/x-shar" }, { "sit", "application/x-stuffit" }, { "sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12" }, { "sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide" }, { "smd", "audio/x-smd" }, { "smi", "application/octet-stream" }, { "smx", "audio/x-smd" }, { "smz", "audio/x-smd" }, { "snd", "audio/basic" }, { "snp", "application/octet-stream" }, { "spc", "application/x-pkcs7-certificates" }, { "spl", "application/futuresplash" }, { "src", "application/x-wais-source" }, { "ssm", "application/streamingmedia" }, { "sst", "application/vnd.ms-pki.certstore" }, { "stl", "application/vnd.ms-pki.stl" }, { "sv4cpio", "application/x-sv4cpio" }, { "sv4crc", "application/x-sv4crc" }, { "swf", "application/x-shockwave-flash" }, { "t", "application/x-troff" }, { "tar", "application/x-tar" }, { "tcl", "application/x-tcl" }, { "tex", "application/x-tex" }, { "texi", "application/x-texinfo" }, { "texinfo", "application/x-texinfo" }, { "tgz", "application/x-compressed" }, { "thmx", "application/vnd.ms-officetheme" }, { "thn", "application/octet-stream" }, { "tif", "image/tiff" }, { "tiff", "image/tiff" }, { "toc", "application/octet-stream" }, { "tr", "application/x-troff" }, { "trm", "application/x-msterminal" }, { "tsv", "text/tab-separated-values" }, { "ttf", "application/octet-stream" }, { "txt", "text/plain" }, { "u32", "application/octet-stream" }, { "uls", "text/iuls" }, { "ustar", "application/x-ustar" }, { "vbs", "text/vbscript" }, { "vcf", "text/x-vcard" }, { "vcs", "text/plain" }, { "vdx", "application/vnd.ms-visio.viewer" }, { "vml", "text/xml" }, { "vsd", "application/vnd.visio" }, { "vss", "application/vnd.visio" }, { "vst", "application/vnd.visio" }, { "vsto", "application/x-ms-vsto" }, { "vsw", "application/vnd.visio" }, { "vsx", "application/vnd.visio" }, { "vtx", "application/vnd.visio" }, { "wav", "audio/wav" }, { "wax", "audio/x-ms-wax" }, { "wbmp", "image/vnd.wap.wbmp" }, { "wcm", "application/vnd.ms-works" }, { "wdb", "application/vnd.ms-works" }, { "wks", "application/vnd.ms-works" }, { "wm", "video/x-ms-wm" }, { "wma", "audio/x-ms-wma" }, { "wmd", "application/x-ms-wmd" }, { "wmf", "application/x-msmetafile" }, { "wml", "text/vnd.wap.wml" }, { "wmlc", "application/vnd.wap.wmlc" }, { "wmls", "text/vnd.wap.wmlscript" }, { "wmlsc", "application/vnd.wap.wmlscriptc" }, { "wmp", "video/x-ms-wmp" }, { "wmv", "video/x-ms-wmv" }, { "wmx", "video/x-ms-wmx" }, { "wmz", "application/x-ms-wmz" }, { "wps", "application/vnd.ms-works" }, { "wri", "application/x-mswrite" }, { "wrl", "x-world/x-vrml" }, { "wrz", "x-world/x-vrml" }, { "wsdl", "text/xml" }, { "wvx", "video/x-ms-wvx" }, { "x", "application/directx" }, { "xaf", "x-world/x-vrml" }, { "xaml", "application/xaml+xml" }, { "xap", "application/x-silverlight-app" }, { "xbap", "application/x-ms-xbap" }, { "xbm", "image/x-xbitmap" }, { "xdr", "text/plain" }, { "xla", "application/vnd.ms-excel" }, { "xlam", "application/vnd.ms-excel.addin.macroEnabled.12" }, { "xlc", "application/vnd.ms-excel" }, { "xlm", "application/vnd.ms-excel" }, { "xls", "application/vnd.ms-excel" }, { "xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12" }, { "xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12" }, { "xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }, { "xlt", "application/vnd.ms-excel" }, { "xltm", "application/vnd.ms-excel.template.macroEnabled.12" }, { "xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template" }, { "xlw", "application/vnd.ms-excel" }, { "xml", "text/xml" }, { "xof", "x-world/x-vrml" }, { "xpm", "image/x-xpixmap" }, { "xps", "application/vnd.ms-xpsdocument" }, { "xsd", "text/xml" }, { "xsf", "text/xml" }, { "xsl", "text/xml" }, { "xslt", "text/xml" }, { "xsn", "application/octet-stream" }, { "xtp", "application/octet-stream" }, { "xwd", "image/x-xwindowdump" }, { "z", "application/x-compress" }, { "zip", "application/x-zip-compressed" }, }; #endregion } }