context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Copyright (c) 2006-2016, openmetaverse.co * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.co nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using System.Collections; using OpenMetaverse.StructuredData; namespace OpenMetaverse.Tests { /// <summary> /// XmlSDTests is a suite of tests for libsl implementation of the SD XML format. /// /// </summary> [TestFixture] public class XmlSDTests { /// <summary> /// Test that the sample LLSD supplied by Linden Lab is properly deserialized. /// The LLSD string in the test is a pared down version of the sample on the blog. /// http://wiki.secondlife.com/wiki/LLSD /// </summary> [Test] public void DeserializeLLSDSample() { OSD theSD = null; OSDMap map = null; OSD tempSD = null; OSDUUID tempUUID = null; OSDString tempStr = null; OSDReal tempReal = null; String testSD = @"<?xml version='1.0' encoding='UTF-8'?> <llsd> <map> <key>region_id</key> <uuid>67153d5b-3659-afb4-8510-adda2c034649</uuid> <key>scale</key> <string>one minute</string> <key>simulator statistics</key> <map> <key>time dilation</key> <real>0.9878624</real> <key>sim fps</key> <real>44.38898</real> <key>agent updates per second</key> <real>nan</real> <key>total task count</key> <real>4</real> <key>active task count</key> <real>0</real> <key>pending uploads</key> <real>0.0001096525</real> </map> </map> </llsd>"; //Deserialize the string byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); //Confirm the contents Assert.IsNotNull(theSD); Assert.IsTrue(theSD is OSDMap); Assert.IsTrue(theSD.Type == OSDType.Map); map = (OSDMap)theSD; tempSD = map["region_id"]; Assert.IsNotNull(tempSD); Assert.IsTrue(tempSD is OSDUUID); Assert.IsTrue(tempSD.Type == OSDType.UUID); tempUUID = (OSDUUID)tempSD; Assert.AreEqual(new UUID("67153d5b-3659-afb4-8510-adda2c034649"), tempUUID.AsUUID()); tempSD = map["scale"]; Assert.IsNotNull(tempSD); Assert.IsTrue(tempSD is OSDString); Assert.IsTrue(tempSD.Type == OSDType.String); tempStr = (OSDString)tempSD; Assert.AreEqual("one minute", tempStr.AsString()); tempSD = map["simulator statistics"]; Assert.IsNotNull(tempSD); Assert.IsTrue(tempSD is OSDMap); Assert.IsTrue(tempSD.Type == OSDType.Map); map = (OSDMap)tempSD; tempSD = map["time dilation"]; Assert.IsNotNull(tempSD); Assert.IsTrue(tempSD is OSDReal); Assert.IsTrue(tempSD.Type == OSDType.Real); tempReal = (OSDReal)tempSD; Assert.AreEqual(0.9878624d, tempReal.AsReal()); //TODO - figure out any relevant rounding variability for 64 bit reals tempSD = map["sim fps"]; Assert.IsNotNull(tempSD); Assert.IsTrue(tempSD is OSDReal); Assert.IsTrue(tempSD.Type == OSDType.Real); tempReal = (OSDReal)tempSD; Assert.AreEqual(44.38898d, tempReal.AsReal()); tempSD = map["agent updates per second"]; Assert.IsNotNull(tempSD); Assert.IsTrue(tempSD is OSDReal); Assert.IsTrue(tempSD.Type == OSDType.Real); tempReal = (OSDReal)tempSD; Assert.AreEqual(Double.NaN, tempSD.AsReal()); tempSD = map["total task count"]; Assert.IsNotNull(tempSD); Assert.IsTrue(tempSD is OSDReal); Assert.IsTrue(tempSD.Type == OSDType.Real); tempReal = (OSDReal)tempSD; Assert.AreEqual(4.0d, tempReal.AsReal()); tempSD = map["active task count"]; Assert.IsNotNull(tempSD); Assert.IsTrue(tempSD is OSDReal); Assert.IsTrue(tempSD.Type == OSDType.Real); tempReal = (OSDReal)tempSD; Assert.AreEqual(0.0d, tempReal.AsReal()); tempSD = map["pending uploads"]; Assert.IsNotNull(tempSD); Assert.IsTrue(tempSD is OSDReal); Assert.IsTrue(tempSD.Type == OSDType.Real); tempReal = (OSDReal)tempSD; Assert.AreEqual(0.0001096525d, tempReal.AsReal()); } /// <summary> /// Test that various Real representations are parsed correctly. /// </summary> [Test] public void DeserializeReals() { OSD theSD = null; OSDArray array = null; OSDReal tempReal = null; String testSD = @"<?xml version='1.0' encoding='UTF-8'?> <llsd> <array> <real>44.38898</real> <real>nan</real> <real>4</real> <real>-13.333</real> <real/> </array> </llsd>"; //Deserialize the string byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); Assert.IsTrue(theSD is OSDArray); array = (OSDArray)theSD; Assert.AreEqual(OSDType.Real, array[0].Type); tempReal = (OSDReal)array[0]; Assert.AreEqual(44.38898d, tempReal.AsReal()); Assert.AreEqual(OSDType.Real, array[1].Type); tempReal = (OSDReal)array[1]; Assert.AreEqual(Double.NaN, tempReal.AsReal()); Assert.AreEqual(OSDType.Real, array[2].Type); tempReal = (OSDReal)array[2]; Assert.AreEqual(4.0d, tempReal.AsReal()); Assert.AreEqual(OSDType.Real, array[3].Type); tempReal = (OSDReal)array[3]; Assert.AreEqual(-13.333d, tempReal.AsReal()); Assert.AreEqual(OSDType.Real, array[4].Type); tempReal = (OSDReal)array[4]; Assert.AreEqual(0d, tempReal.AsReal()); } /// <summary> /// Test that various String representations are parsed correctly. /// </summary> [Test] public void DeserializeStrings() { OSD theSD = null; OSDArray array = null; OSDString tempStr = null; String testSD = @"<?xml version='1.0' encoding='UTF-8'?> <llsd> <array> <string>Kissling</string> <string>Attack ships on fire off the shoulder of Orion</string> <string>&lt; &gt; &amp; &apos; &quot;</string> <string/> </array> </llsd>"; //Deserialize the string byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); Assert.IsTrue(theSD is OSDArray); array = (OSDArray)theSD; Assert.AreEqual(OSDType.String, array[0].Type); tempStr = (OSDString)array[0]; Assert.AreEqual("Kissling", tempStr.AsString()); Assert.AreEqual(OSDType.String, array[1].Type); tempStr = (OSDString)array[1]; Assert.AreEqual("Attack ships on fire off the shoulder of Orion", tempStr.AsString()); Assert.AreEqual(OSDType.String, array[2].Type); tempStr = (OSDString)array[2]; Assert.AreEqual("< > & \' \"", tempStr.AsString()); Assert.AreEqual(OSDType.String, array[3].Type); tempStr = (OSDString)array[3]; Assert.AreEqual("", tempStr.AsString()); } /// <summary> /// Test that various Integer representations are parsed correctly. /// These tests currently only test for values within the range of a /// 32 bit signed integer, even though the SD specification says /// the type is a 64 bit signed integer, because LLSInteger is currently /// implemented using int, a.k.a. Int32. Not testing Int64 range until /// it's understood if there was a design reason for the Int32. /// </summary> [Test] public void DeserializeIntegers() { OSD theSD = null; OSDArray array = null; OSDInteger tempInt = null; String testSD = @"<?xml version='1.0' encoding='UTF-8'?> <llsd> <array> <integer>2147483647</integer> <integer>-2147483648</integer> <integer>0</integer> <integer>013</integer> <integer/> </array> </llsd>"; //Deserialize the string byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); Assert.IsTrue(theSD is OSDArray); array = (OSDArray)theSD; Assert.AreEqual(OSDType.Integer, array[0].Type); tempInt = (OSDInteger)array[0]; Assert.AreEqual(2147483647, tempInt.AsInteger()); Assert.AreEqual(OSDType.Integer, array[1].Type); tempInt = (OSDInteger)array[1]; Assert.AreEqual(-2147483648, tempInt.AsInteger()); Assert.AreEqual(OSDType.Integer, array[2].Type); tempInt = (OSDInteger)array[2]; Assert.AreEqual(0, tempInt.AsInteger()); Assert.AreEqual(OSDType.Integer, array[3].Type); tempInt = (OSDInteger)array[3]; Assert.AreEqual(13, tempInt.AsInteger()); Assert.AreEqual(OSDType.Integer, array[4].Type); tempInt = (OSDInteger)array[4]; Assert.AreEqual(0, tempInt.AsInteger()); } /// <summary> /// Test that various UUID representations are parsed correctly. /// </summary> [Test] public void DeserializeUUID() { OSD theSD = null; OSDArray array = null; OSDUUID tempUUID = null; String testSD = @"<?xml version='1.0' encoding='UTF-8'?> <llsd> <array> <uuid>d7f4aeca-88f1-42a1-b385-b9db18abb255</uuid> <uuid/> </array> </llsd>"; //Deserialize the string byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); Assert.IsTrue(theSD is OSDArray); array = (OSDArray)theSD; Assert.AreEqual(OSDType.UUID, array[0].Type); tempUUID = (OSDUUID)array[0]; Assert.AreEqual(new UUID("d7f4aeca-88f1-42a1-b385-b9db18abb255"), tempUUID.AsUUID()); Assert.AreEqual(OSDType.UUID, array[1].Type); tempUUID = (OSDUUID)array[1]; Assert.AreEqual(UUID.Zero, tempUUID.AsUUID()); } /// <summary> /// Test that various date representations are parsed correctly. /// </summary> [Test] public void DeserializeDates() { OSD theSD = null; OSDArray array = null; OSDDate tempDate = null; DateTime testDate; String testSD = @"<?xml version='1.0' encoding='UTF-8'?> <llsd> <array> <date>2006-02-01T14:29:53Z</date> <date>1999-01-01T00:00:00Z</date> <date/> </array> </llsd>"; //Deserialize the string byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); Assert.IsTrue(theSD is OSDArray); array = (OSDArray)theSD; Assert.AreEqual(OSDType.Date, array[0].Type); tempDate = (OSDDate)array[0]; DateTime.TryParse("2006-02-01T14:29:53Z", out testDate); Assert.AreEqual(testDate, tempDate.AsDate()); Assert.AreEqual(OSDType.Date, array[1].Type); tempDate = (OSDDate)array[1]; DateTime.TryParse("1999-01-01T00:00:00Z", out testDate); Assert.AreEqual(testDate, tempDate.AsDate()); Assert.AreEqual(OSDType.Date, array[2].Type); tempDate = (OSDDate)array[2]; Assert.AreEqual(Utils.Epoch, tempDate.AsDate()); } /// <summary> /// Test that various Boolean representations are parsed correctly. /// </summary> [Test] public void DeserializeBoolean() { OSD theSD = null; OSDArray array = null; OSDBoolean tempBool = null; String testSD = @"<?xml version='1.0' encoding='UTF-8'?> <llsd> <array> <boolean>1</boolean> <boolean>true</boolean> <boolean>0</boolean> <boolean>false</boolean> <boolean/> </array> </llsd>"; //Deserialize the string byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); Assert.IsTrue(theSD is OSDArray); array = (OSDArray)theSD; Assert.AreEqual(OSDType.Boolean, array[0].Type); tempBool = (OSDBoolean)array[0]; Assert.AreEqual(true, tempBool.AsBoolean()); Assert.AreEqual(OSDType.Boolean, array[1].Type); tempBool = (OSDBoolean)array[1]; Assert.AreEqual(true, tempBool.AsBoolean()); Assert.AreEqual(OSDType.Boolean, array[2].Type); tempBool = (OSDBoolean)array[2]; Assert.AreEqual(false, tempBool.AsBoolean()); Assert.AreEqual(OSDType.Boolean, array[3].Type); tempBool = (OSDBoolean)array[3]; Assert.AreEqual(false, tempBool.AsBoolean()); Assert.AreEqual(OSDType.Boolean, array[4].Type); tempBool = (OSDBoolean)array[4]; Assert.AreEqual(false, tempBool.AsBoolean()); } /// <summary> /// Test that binary elements are parsed correctly. /// </summary> [Test] public void DeserializeBinary() { OSD theSD = null; OSDArray array = null; OSDBinary tempBinary = null; String testSD = @"<?xml version='1.0' encoding='UTF-8'?> <llsd> <array> <binary encoding='base64'>cmFuZG9t</binary> <binary>dGhlIHF1aWNrIGJyb3duIGZveA==</binary> <binary/> </array> </llsd>"; //Deserialize the string byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); Assert.IsTrue(theSD is OSDArray); array = (OSDArray)theSD; Assert.AreEqual(OSDType.Binary, array[0].Type); tempBinary = (OSDBinary)array[0]; byte[] testData1 = {114, 97, 110, 100, 111, 109}; TestHelper.TestBinary(tempBinary, testData1); Assert.AreEqual(OSDType.Binary, array[1].Type); tempBinary = (OSDBinary)array[1]; byte[] testData2 = {116, 104, 101, 32, 113, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110, 32, 102, 111, 120}; TestHelper.TestBinary(tempBinary, testData2); Assert.AreEqual(OSDType.Binary, array[1].Type); tempBinary = (OSDBinary)array[2]; Assert.AreEqual(0, tempBinary.AsBinary().Length); } /// <summary> /// Test that undefened elements are parsed correctly. /// Currently this just checks that there is no error since undefined has no /// value and there is no SD child class for Undefined elements - the /// current implementation generates an instance of SD /// </summary> [Test] public void DeserializeUndef() { OSD theSD = null; String testSD = @"<?xml version='1.0' encoding='UTF-8'?> <llsd> <undef/> </llsd>"; //Deserialize the string byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); Assert.IsTrue(theSD is OSD); } /// <summary> /// Test that various URI representations are parsed correctly. /// </summary> [Test] public void DeserializeURI() { OSD theSD = null; OSDArray array = null; OSDUri tempURI = null; String testSD = @"<?xml version='1.0' encoding='UTF-8'?> <llsd> <array> <uri>http://sim956.agni.lindenlab.com:12035/runtime/agents</uri> <uri/> </array> </llsd>"; //Deserialize the string byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); Assert.IsTrue(theSD is OSDArray); array = (OSDArray)theSD; Assert.AreEqual(OSDType.URI, array[0].Type); tempURI = (OSDUri)array[0]; Uri testURI = new Uri(@"http://sim956.agni.lindenlab.com:12035/runtime/agents"); Assert.AreEqual(testURI, tempURI.AsUri()); Assert.AreEqual(OSDType.URI, array[1].Type); tempURI = (OSDUri)array[1]; Assert.AreEqual("", tempURI.AsUri().ToString()); } /// <summary> /// Test some nested containers. This is not a very deep or complicated SD graph /// but it should reveal basic nesting issues. /// </summary> [Test] public void DeserializeNestedContainers() { OSD theSD = null; OSDArray array = null; OSDMap map = null; OSD tempSD = null; String testSD = @"<?xml version='1.0' encoding='UTF-8'?> <llsd> <array> <map> <key>Map One</key> <map> <key>Array One</key> <array> <integer>1</integer> <integer>2</integer> </array> </map> </map> <array> <string>A</string> <string>B</string> <array> <integer>1</integer> <integer>4</integer> <integer>9</integer> </array> </array> </array> </llsd>"; //Deserialize the string byte[] bytes = Encoding.UTF8.GetBytes(testSD); theSD = OSDParser.DeserializeLLSDXml(bytes); Assert.IsTrue(theSD is OSDArray); array = (OSDArray)theSD; Assert.AreEqual(2, array.Count); //The first element of top level array, a map Assert.AreEqual(OSDType.Map, array[0].Type); map = (OSDMap)array[0]; //First nested map tempSD = map["Map One"]; Assert.IsNotNull(tempSD); Assert.AreEqual(OSDType.Map, tempSD.Type); map = (OSDMap)tempSD; //First nested array tempSD = map["Array One"]; Assert.IsNotNull(tempSD); Assert.AreEqual(OSDType.Array, tempSD.Type); array = (OSDArray)tempSD; Assert.AreEqual(2, array.Count); array = (OSDArray)theSD; //Second element of top level array, an array tempSD = array[1]; Assert.AreEqual(OSDType.Array, tempSD.Type); array = (OSDArray)tempSD; Assert.AreEqual(3, array.Count); //Nested array tempSD = array[2]; Assert.AreEqual(OSDType.Array, tempSD.Type); array = (OSDArray)tempSD; Assert.AreEqual(3, array.Count); } } internal static class TestHelper { /// <summary> /// Asserts that the contents of the SDBinary match the values and length /// of the supplied byte array /// </summary> /// <param name="inBinary"></param> /// <param name="inExpected"></param> internal static void TestBinary(OSDBinary inBinary, byte[] inExpected) { byte[] binary = inBinary.AsBinary(); Assert.AreEqual(inExpected.Length, binary.Length); for (int i = 0; i < inExpected.Length; i++) { if (inExpected[i] != binary[i]) { Assert.Fail("Expected " + inExpected[i].ToString() + " at position " + i.ToString() + " but saw " + binary[i].ToString()); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Threading; namespace System.Globalization { // // Data table for encoding classes. Used by System.Text.Encoding. // This class contains two hashtables to allow System.Text.Encoding // to retrieve the data item either by codepage value or by webName. // // Only statics, does not need to be marked with the serializable attribute internal static class EncodingTable { //This number is the size of the table in native. The value is retrieved by //calling the native GetNumEncodingItems(). private static int lastEncodingItem = GetNumEncodingItems() - 1; //This number is the size of the code page table. Its generated when we walk the table the first time. private static volatile int lastCodePageItem; // // This points to a native data table which maps an encoding name to the correct code page. // unsafe internal static InternalEncodingDataItem* encodingDataPtr = GetEncodingData(); // // This points to a native data table which stores the properties for the code page, and // the table is indexed by code page. // unsafe internal static InternalCodePageDataItem* codePageDataPtr = GetCodePageData(); // // This caches the mapping of an encoding name to a code page. // private static Hashtable hashByName = Hashtable.Synchronized(new Hashtable(StringComparer.OrdinalIgnoreCase)); // // THe caches the data item which is indexed by the code page value. // private static Hashtable hashByCodePage = Hashtable.Synchronized(new Hashtable()); // Find the data item by binary searching the table that we have in native. // nativeCompareOrdinalWC is an internal-only function. unsafe private static int internalGetCodePageFromName(String name) { int left = 0; int right = lastEncodingItem; int index; int result; //Binary search the array until we have only a couple of elements left and then //just walk those elements. while ((right - left) > 3) { index = ((right - left) / 2) + left; result = String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[index].webName); if (result == 0) { //We found the item, return the associated codepage. return (encodingDataPtr[index].codePage); } else if (result < 0) { //The name that we're looking for is less than our current index. right = index; } else { //The name that we're looking for is greater than our current index left = index; } } //Walk the remaining elements (it'll be 3 or fewer). for (; left <= right; left++) { if (String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[left].webName) == 0) { return (encodingDataPtr[left].codePage); } } // The encoding name is not valid. throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, SR.Argument_EncodingNotSupported, name), nameof(name)); } // Return a list of all EncodingInfo objects describing all of our encodings internal static unsafe EncodingInfo[] GetEncodings() { if (lastCodePageItem == 0) { int count; for (count = 0; codePageDataPtr[count].codePage != 0; count++) { // Count them } lastCodePageItem = count; } EncodingInfo[] arrayEncodingInfo = new EncodingInfo[lastCodePageItem]; int i; for (i = 0; i < lastCodePageItem; i++) { arrayEncodingInfo[i] = new EncodingInfo(codePageDataPtr[i].codePage, CodePageDataItem.CreateString(codePageDataPtr[i].Names, 0), SR.GetResourceString("Globalization_cp_" + codePageDataPtr[i].codePage)); } return arrayEncodingInfo; } /*=================================GetCodePageFromName========================== **Action: Given a encoding name, return the correct code page number for this encoding. **Returns: The code page for the encoding. **Arguments: ** name the name of the encoding **Exceptions: ** ArgumentNullException if name is null. ** internalGetCodePageFromName will throw ArgumentException if name is not a valid encoding name. ============================================================================*/ internal static int GetCodePageFromName(String name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } Object codePageObj; // // The name is case-insensitive, but ToLower isn't free. Check for // the code page in the given capitalization first. // codePageObj = hashByName[name]; if (codePageObj != null) { return ((int)codePageObj); } //Okay, we didn't find it in the hash table, try looking it up in the //unmanaged data. int codePage = internalGetCodePageFromName(name); hashByName[name] = codePage; return codePage; } unsafe internal static CodePageDataItem GetCodePageDataItem(int codepage) { CodePageDataItem dataItem; // We synchronize around dictionary gets/sets. There's still a possibility that two threads // will create a CodePageDataItem and the second will clobber the first in the dictionary. // However, that's acceptable because the contents are correct and we make no guarantees // other than that. //Look up the item in the hashtable. dataItem = (CodePageDataItem)hashByCodePage[codepage]; //If we found it, return it. if (dataItem != null) { return dataItem; } //If we didn't find it, try looking it up now. //If we find it, add it to the hashtable. //This is a linear search, but we probably won't be doing it very often. // int i = 0; int data; while ((data = codePageDataPtr[i].codePage) != 0) { if (data == codepage) { dataItem = new CodePageDataItem(i); hashByCodePage[codepage] = dataItem; return (dataItem); } i++; } //Nope, we didn't find it. return null; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern InternalEncodingDataItem* GetEncodingData(); // // Return the number of encoding data items. // [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int GetNumEncodingItems(); [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern InternalCodePageDataItem* GetCodePageData(); } /*=================================InternalEncodingDataItem========================== **Action: This is used to map a encoding name to a correct code page number. By doing this, ** we can get the properties of this encoding via the InternalCodePageDataItem. ** ** We use this structure to access native data exposed by the native side. ============================================================================*/ [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] internal unsafe struct InternalEncodingDataItem { internal sbyte* webName; internal UInt16 codePage; } /*=================================InternalCodePageDataItem========================== **Action: This is used to access the properties related to a code page. ** We use this structure to access native data exposed by the native side. ============================================================================*/ [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] internal unsafe struct InternalCodePageDataItem { internal UInt16 codePage; internal UInt16 uiFamilyCodePage; internal uint flags; internal sbyte* Names; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Sql { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ServersOperations operations. /// </summary> public partial interface IServersOperations { /// <summary> /// Creates or updates a firewall rule. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule. /// </param> /// <param name='parameters'> /// The required parameters for creating or updating a firewall rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ServerFirewallRule>> CreateOrUpdateFirewallRuleWithHttpMessagesAsync(string resourceGroupName, string serverName, string firewallRuleName, ServerFirewallRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a firewall rule. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteFirewallRuleWithHttpMessagesAsync(string resourceGroupName, string serverName, string firewallRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a firewall rule. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ServerFirewallRule>> GetFirewallRuleWithHttpMessagesAsync(string resourceGroupName, string serverName, string firewallRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns a list of firewall rules. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<ServerFirewallRule>>> ListFirewallRulesWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns a list of servers. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<Server>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a new server. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='parameters'> /// The required parameters for creating or updating a server. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Server>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, Server parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a SQL server. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a server. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Server>> GetByResourceGroupWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns a server. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<Server>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns server usages. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<ServerMetric>>> ListUsagesWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a database service objective. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='serviceObjectiveName'> /// The name of the service objective to retrieve. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ServiceObjective>> GetServiceObjectiveWithHttpMessagesAsync(string resourceGroupName, string serverName, string serviceObjectiveName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns database service objectives. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<ServiceObjective>>> ListServiceObjectivesWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // TargetRegistry.cs // // // A store of registered targets with a target block. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace System.Threading.Tasks.Dataflow.Internal { /// <summary>Stores targets registered with a source.</summary> /// <typeparam name="T">Specifies the type of data accepted by the targets.</typeparam> /// <remarks>This type is not thread-safe.</remarks> [DebuggerDisplay("Count={Count}")] [DebuggerTypeProxy(typeof(TargetRegistry<>.DebugView))] internal sealed class TargetRegistry<T> { /// <summary> /// Information about a registered target. This class represents a self-sufficient node in a linked list. /// </summary> internal sealed class LinkedTargetInfo { /// <summary>Initializes the LinkedTargetInfo.</summary> /// <param name="target">The target block reference for this entry.</param> /// <param name="linkOptions">The link options.</param> internal LinkedTargetInfo(ITargetBlock<T> target, DataflowLinkOptions linkOptions) { Debug.Assert(target != null, "The target that is supposed to be linked must not be null."); Debug.Assert(linkOptions != null, "The linkOptions must not be null."); Target = target; PropagateCompletion = linkOptions.PropagateCompletion; RemainingMessages = linkOptions.MaxMessages; } /// <summary>The target block reference for this entry.</summary> internal readonly ITargetBlock<T> Target; /// <summary>The value of the PropagateCompletion link option.</summary> internal readonly bool PropagateCompletion; /// <summary>Number of remaining messages to propagate. /// This counter is initialized to the MaxMessages option and /// gets decremented after each successful propagation.</summary> internal int RemainingMessages; /// <summary>The previous node in the list.</summary> internal LinkedTargetInfo Previous; /// <summary>The next node in the list.</summary> internal LinkedTargetInfo Next; } /// <summary>A reference to the owning source block.</summary> private readonly ISourceBlock<T> _owningSource; /// <summary>A mapping of targets to information about them.</summary> private readonly Dictionary<ITargetBlock<T>, LinkedTargetInfo> _targetInformation; /// <summary>The first node of an ordered list of targets. Messages should be offered to targets starting from First and following Next.</summary> private LinkedTargetInfo _firstTarget; /// <summary>The last node of the ordered list of targets. This field is used purely as a perf optimization to avoid traversing the list for each Add.</summary> private LinkedTargetInfo _lastTarget; /// <summary>Number of links with positive RemainingMessages counters. /// This is an optimization that allows us to skip dictionary lookup when this counter is 0.</summary> private int _linksWithRemainingMessages; /// <summary>Initializes the registry.</summary> internal TargetRegistry(ISourceBlock<T> owningSource) { Debug.Assert(owningSource != null, "The TargetRegistry instance must be owned by a source block."); _owningSource = owningSource; _targetInformation = new Dictionary<ITargetBlock<T>, LinkedTargetInfo>(); } /// <summary>Adds a target to the registry.</summary> /// <param name="target">The target to add.</param> /// <param name="linkOptions">The link options.</param> internal void Add(ref ITargetBlock<T> target, DataflowLinkOptions linkOptions) { Debug.Assert(target != null, "The target that is supposed to be linked must not be null."); Debug.Assert(linkOptions != null, "The link options must not be null."); LinkedTargetInfo targetInfo; // If the target already exists in the registry, replace it with a new NopLinkPropagator to maintain uniqueness if (_targetInformation.TryGetValue(target, out targetInfo)) target = new NopLinkPropagator(_owningSource, target); // Add the target to both stores, the list and the dictionary, which are used for different purposes var node = new LinkedTargetInfo(target, linkOptions); AddToList(node, linkOptions.Append); _targetInformation.Add(target, node); // Increment the optimization counter if needed Debug.Assert(_linksWithRemainingMessages >= 0, "_linksWithRemainingMessages must be non-negative at any time."); if (node.RemainingMessages > 0) _linksWithRemainingMessages++; #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockLinking(_owningSource, target); } #endif } /// <summary>Gets whether the registry contains a particular target.</summary> /// <param name="target">The target.</param> /// <returns>true if the registry contains the target; otherwise, false.</returns> internal bool Contains(ITargetBlock<T> target) { return _targetInformation.ContainsKey(target); } /// <summary>Removes the target from the registry.</summary> /// <param name="target">The target to remove.</param> /// <param name="onlyIfReachedMaxMessages"> /// Only remove the target if it's configured to be unlinked after one propagation. /// </param> internal void Remove(ITargetBlock<T> target, bool onlyIfReachedMaxMessages = false) { Debug.Assert(target != null, "Target to remove is required."); // If we are implicitly unlinking and there is nothing to be unlinked implicitly, bail Debug.Assert(_linksWithRemainingMessages >= 0, "_linksWithRemainingMessages must be non-negative at any time."); if (onlyIfReachedMaxMessages && _linksWithRemainingMessages == 0) return; // Otherwise take the slow path Remove_Slow(target, onlyIfReachedMaxMessages); } /// <summary>Actually removes the target from the registry.</summary> /// <param name="target">The target to remove.</param> /// <param name="onlyIfReachedMaxMessages"> /// Only remove the target if it's configured to be unlinked after one propagation. /// </param> private void Remove_Slow(ITargetBlock<T> target, bool onlyIfReachedMaxMessages) { Debug.Assert(target != null, "Target to remove is required."); // Make sure we've intended to go the slow route Debug.Assert(_linksWithRemainingMessages >= 0, "_linksWithRemainingMessages must be non-negative at any time."); Debug.Assert(!onlyIfReachedMaxMessages || _linksWithRemainingMessages > 0, "We shouldn't have ended on the slow path."); // If the target is registered... LinkedTargetInfo node; if (_targetInformation.TryGetValue(target, out node)) { Debug.Assert(node != null, "The LinkedTargetInfo node referenced in the Dictionary must be non-null."); // Remove the target, if either there's no constraint on the removal // or if this was the last remaining message. if (!onlyIfReachedMaxMessages || node.RemainingMessages == 1) { RemoveFromList(node); _targetInformation.Remove(target); // Decrement the optimization counter if needed if (node.RemainingMessages == 0) _linksWithRemainingMessages--; Debug.Assert(_linksWithRemainingMessages >= 0, "_linksWithRemainingMessages must be non-negative at any time."); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockUnlinking(_owningSource, target); } #endif } // If the target is to stay and we are counting the remaining messages for this link, decrement the counter else if (node.RemainingMessages > 0) { Debug.Assert(node.RemainingMessages > 1, "The target should have been removed, because there are no remaining messages."); node.RemainingMessages--; } } } /// <summary>Clears the target registry entry points while allowing subsequent traversals of the linked list.</summary> internal LinkedTargetInfo ClearEntryPoints() { // Save _firstTarget so we can return it LinkedTargetInfo firstTarget = _firstTarget; // Clear out the entry points _firstTarget = _lastTarget = null; _targetInformation.Clear(); Debug.Assert(_linksWithRemainingMessages >= 0, "_linksWithRemainingMessages must be non-negative at any time."); _linksWithRemainingMessages = 0; return firstTarget; } /// <summary>Propagated completion to the targets of the given linked list.</summary> /// <param name="firstTarget">The head of a saved linked list.</param> internal void PropagateCompletion(LinkedTargetInfo firstTarget) { Debug.Assert(_owningSource.Completion.IsCompleted, "The owning source must have completed before propagating completion."); // Cache the owning source's completion task to avoid calling the getter many times Task owningSourceCompletion = _owningSource.Completion; // Propagate completion to those targets that have requested it for (LinkedTargetInfo node = firstTarget; node != null; node = node.Next) { if (node.PropagateCompletion) Common.PropagateCompletion(owningSourceCompletion, node.Target, Common.AsyncExceptionHandler); } } /// <summary>Gets the first node of the ordered target list.</summary> internal LinkedTargetInfo FirstTargetNode { get { return _firstTarget; } } /// <summary>Adds a LinkedTargetInfo node to the doubly-linked list.</summary> /// <param name="node">The node to be added.</param> /// <param name="append">Whether to append or to prepend the node.</param> internal void AddToList(LinkedTargetInfo node, bool append) { Debug.Assert(node != null, "Requires a node to be added."); // If the list is empty, assign the ends to point to the new node and we are done if (_firstTarget == null && _lastTarget == null) { _firstTarget = _lastTarget = node; } else { Debug.Assert(_firstTarget != null && _lastTarget != null, "Both first and last node must either be null or non-null."); Debug.Assert(_lastTarget.Next == null, "The last node must not have a successor."); Debug.Assert(_firstTarget.Previous == null, "The first node must not have a predecessor."); if (append) { // Link the new node to the end of the existing list node.Previous = _lastTarget; _lastTarget.Next = node; _lastTarget = node; } else { // Link the new node to the front of the existing list node.Next = _firstTarget; _firstTarget.Previous = node; _firstTarget = node; } } Debug.Assert(_firstTarget != null && _lastTarget != null, "Both first and last node must be non-null after AddToList."); } /// <summary>Removes the LinkedTargetInfo node from the doubly-linked list.</summary> /// <param name="node">The node to be removed.</param> internal void RemoveFromList(LinkedTargetInfo node) { Debug.Assert(node != null, "Node to remove is required."); Debug.Assert(_firstTarget != null && _lastTarget != null, "Both first and last node must be non-null before RemoveFromList."); LinkedTargetInfo previous = node.Previous; LinkedTargetInfo next = node.Next; // Remove the node by linking the adjacent nodes if (node.Previous != null) { node.Previous.Next = next; node.Previous = null; } if (node.Next != null) { node.Next.Previous = previous; node.Next = null; } // Adjust the list ends if (_firstTarget == node) _firstTarget = next; if (_lastTarget == node) _lastTarget = previous; Debug.Assert((_firstTarget != null) == (_lastTarget != null), "Both first and last node must either be null or non-null after RemoveFromList."); } /// <summary>Gets the number of items in the registry.</summary> private int Count { get { return _targetInformation.Count; } } /// <summary>Converts the linked list of targets to an array for rendering in a debugger.</summary> private ITargetBlock<T>[] TargetsForDebugger { get { var targets = new ITargetBlock<T>[Count]; int i = 0; for (LinkedTargetInfo node = _firstTarget; node != null; node = node.Next) { targets[i++] = node.Target; } return targets; } } /// <summary>Provides a nop passthrough for use with TargetRegistry.</summary> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(TargetRegistry<>.NopLinkPropagator.DebugView))] private sealed class NopLinkPropagator : IPropagatorBlock<T, T>, ISourceBlock<T>, IDebuggerDisplay { /// <summary>The source that encapsulates this block.</summary> private readonly ISourceBlock<T> _owningSource; /// <summary>The target with which this block is associated.</summary> private readonly ITargetBlock<T> _target; /// <summary>Initializes the passthrough.</summary> /// <param name="owningSource">The source that encapsulates this block.</param> /// <param name="target">The target to which messages should be forwarded.</param> internal NopLinkPropagator(ISourceBlock<T> owningSource, ITargetBlock<T> target) { Debug.Assert(owningSource != null, "Propagator must be associated with a source."); Debug.Assert(target != null, "Target to propagate to is required."); // Store the arguments _owningSource = owningSource; _target = target; } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' /> DataflowMessageStatus ITargetBlock<T>.OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, bool consumeToAccept) { Debug.Assert(source == _owningSource, "Only valid to be used with the source for which it was created."); return _target.OfferMessage(messageHeader, messageValue, this, consumeToAccept); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' /> T ISourceBlock<T>.ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target, out bool messageConsumed) { return _owningSource.ConsumeMessage(messageHeader, this, out messageConsumed); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' /> bool ISourceBlock<T>.ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { return _owningSource.ReserveMessage(messageHeader, this); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' /> void ISourceBlock<T>.ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { _owningSource.ReleaseReservation(messageHeader, this); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> Task IDataflowBlock.Completion { get { return _owningSource.Completion; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> void IDataflowBlock.Complete() { _target.Complete(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { _target.Fault(exception); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' /> IDisposable ISourceBlock<T>.LinkTo(ITargetBlock<T> target, DataflowLinkOptions linkOptions) { throw new NotSupportedException(SR.NotSupported_MemberNotNeeded); } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { var displaySource = _owningSource as IDebuggerDisplay; var displayTarget = _target as IDebuggerDisplay; return string.Format("{0} Source=\"{1}\", Target=\"{2}\"", Common.GetNameForDebugger(this), displaySource != null ? displaySource.Content : _owningSource, displayTarget != null ? displayTarget.Content : _target); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for a passthrough.</summary> private sealed class DebugView { /// <summary>The passthrough.</summary> private readonly NopLinkPropagator _passthrough; /// <summary>Initializes the debug view.</summary> /// <param name="passthrough">The passthrough to view.</param> public DebugView(NopLinkPropagator passthrough) { Debug.Assert(passthrough != null, "Need a propagator with which to construct the debug view."); _passthrough = passthrough; } /// <summary>The linked target for this block.</summary> public ITargetBlock<T> LinkedTarget { get { return _passthrough._target; } } } } /// <summary>Provides a debugger type proxy for the target registry.</summary> private sealed class DebugView { /// <summary>The registry being debugged.</summary> private readonly TargetRegistry<T> _registry; /// <summary>Initializes the type proxy.</summary> /// <param name="registry">The target registry.</param> public DebugView(TargetRegistry<T> registry) { Debug.Assert(registry != null, "Need a registry with which to construct the debug view."); _registry = registry; } /// <summary>Gets a list of all targets to show in the debugger.</summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public ITargetBlock<T>[] Targets { get { return _registry.TargetsForDebugger; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.Json; using Xunit; namespace Microsoft.AspNetCore.Authentication.Core.Test { public class AuthenticationPropertiesTests { [Fact] public void Clone_Copies() { var items = new Dictionary<string, string?> { ["foo"] = "bar", }; var value = "value"; var parameters = new Dictionary<string, object?> { ["foo2"] = value, }; var props = new AuthenticationProperties(items, parameters); Assert.Same(items, props.Items); Assert.Same(parameters, props.Parameters); var copy = props.Clone(); Assert.NotSame(props.Items, copy.Items); Assert.NotSame(props.Parameters, copy.Parameters); // Objects in the dictionaries will still be the same Assert.Equal(props.Items, copy.Items); Assert.Equal(props.Parameters, copy.Parameters); props.Items["change"] = "good"; props.Parameters["something"] = "bad"; Assert.NotEqual(props.Items, copy.Items); Assert.NotEqual(props.Parameters, copy.Parameters); } [Fact] public void DefaultConstructor_EmptyCollections() { var props = new AuthenticationProperties(); Assert.Empty(props.Items); Assert.Empty(props.Parameters); } [Fact] public void ItemsConstructor_ReusesItemsDictionary() { var items = new Dictionary<string, string?> { ["foo"] = "bar", }; var props = new AuthenticationProperties(items); Assert.Same(items, props.Items); Assert.Empty(props.Parameters); } [Fact] public void FullConstructor_ReusesDictionaries() { var items = new Dictionary<string, string?> { ["foo"] = "bar", }; var parameters = new Dictionary<string, object?> { ["number"] = 1234, ["list"] = new List<string> { "a", "b", "c" }, }; var props = new AuthenticationProperties(items, parameters); Assert.Same(items, props.Items); Assert.Same(parameters, props.Parameters); } [Fact] public void GetSetString() { var props = new AuthenticationProperties(); Assert.Null(props.GetString("foo")); Assert.Equal(0, props.Items.Count); props.SetString("foo", "foo bar"); Assert.Equal("foo bar", props.GetString("foo")); Assert.Equal("foo bar", props.Items["foo"]); Assert.Equal(1, props.Items.Count); props.SetString("foo", "foo baz"); Assert.Equal("foo baz", props.GetString("foo")); Assert.Equal("foo baz", props.Items["foo"]); Assert.Equal(1, props.Items.Count); props.SetString("bar", "xy"); Assert.Equal("xy", props.GetString("bar")); Assert.Equal("xy", props.Items["bar"]); Assert.Equal(2, props.Items.Count); props.SetString("bar", string.Empty); Assert.Equal(string.Empty, props.GetString("bar")); Assert.Equal(string.Empty, props.Items["bar"]); props.SetString("foo", null); Assert.Null(props.GetString("foo")); Assert.Equal(1, props.Items.Count); props.SetString("doesntexist", null); Assert.False(props.Items.ContainsKey("doesntexist")); Assert.Equal(1, props.Items.Count); } [Fact] public void GetSetParameter_String() { var props = new AuthenticationProperties(); Assert.Null(props.GetParameter<string>("foo")); Assert.Equal(0, props.Parameters.Count); props.SetParameter<string>("foo", "foo bar"); Assert.Equal("foo bar", props.GetParameter<string>("foo")); Assert.Equal("foo bar", props.Parameters["foo"]); Assert.Equal(1, props.Parameters.Count); props.SetParameter<string?>("foo", null); Assert.Null(props.GetParameter<string>("foo")); Assert.Null(props.Parameters["foo"]); Assert.Equal(1, props.Parameters.Count); } [Fact] public void GetSetParameter_Int() { var props = new AuthenticationProperties(); Assert.Null(props.GetParameter<int?>("foo")); Assert.Equal(0, props.Parameters.Count); props.SetParameter<int?>("foo", 123); Assert.Equal(123, props.GetParameter<int?>("foo")); Assert.Equal(123, props.Parameters["foo"]); Assert.Equal(1, props.Parameters.Count); props.SetParameter<int?>("foo", null); Assert.Null(props.GetParameter<int?>("foo")); Assert.Null(props.Parameters["foo"]); Assert.Equal(1, props.Parameters.Count); } [Fact] public void GetSetParameter_Collection() { var props = new AuthenticationProperties(); Assert.Null(props.GetParameter<int?>("foo")); Assert.Equal(0, props.Parameters.Count); var list = new string[] { "a", "b", "c" }; props.SetParameter<ICollection<string>>("foo", list); Assert.Equal(new string[] { "a", "b", "c" }, props.GetParameter<ICollection<string>>("foo")); Assert.Same(list, props.Parameters["foo"]); Assert.Equal(1, props.Parameters.Count); props.SetParameter<ICollection<string>?>("foo", null); Assert.Null(props.GetParameter<ICollection<string>>("foo")); Assert.Null(props.Parameters["foo"]); Assert.Equal(1, props.Parameters.Count); } [Fact] public void IsPersistent_Test() { var props = new AuthenticationProperties(); Assert.False(props.IsPersistent); props.IsPersistent = true; Assert.True(props.IsPersistent); Assert.Equal(string.Empty, props.Items.First().Value); props.Items.Clear(); Assert.False(props.IsPersistent); } [Fact] public void RedirectUri_Test() { var props = new AuthenticationProperties(); Assert.Null(props.RedirectUri); props.RedirectUri = "http://example.com"; Assert.Equal("http://example.com", props.RedirectUri); Assert.Equal("http://example.com", props.Items.First().Value); props.Items.Clear(); Assert.Null(props.RedirectUri); } [Fact] public void IssuedUtc_Test() { var props = new AuthenticationProperties(); Assert.Null(props.IssuedUtc); props.IssuedUtc = new DateTimeOffset(new DateTime(2018, 03, 21, 0, 0, 0, DateTimeKind.Utc)); Assert.Equal(new DateTimeOffset(new DateTime(2018, 03, 21, 0, 0, 0, DateTimeKind.Utc)), props.IssuedUtc); Assert.Equal("Wed, 21 Mar 2018 00:00:00 GMT", props.Items.First().Value); props.Items.Clear(); Assert.Null(props.IssuedUtc); } [Fact] public void ExpiresUtc_Test() { var props = new AuthenticationProperties(); Assert.Null(props.ExpiresUtc); props.ExpiresUtc = new DateTimeOffset(new DateTime(2018, 03, 19, 12, 34, 56, DateTimeKind.Utc)); Assert.Equal(new DateTimeOffset(new DateTime(2018, 03, 19, 12, 34, 56, DateTimeKind.Utc)), props.ExpiresUtc); Assert.Equal("Mon, 19 Mar 2018 12:34:56 GMT", props.Items.First().Value); props.Items.Clear(); Assert.Null(props.ExpiresUtc); } [Fact] public void AllowRefresh_Test() { var props = new AuthenticationProperties(); Assert.Null(props.AllowRefresh); props.AllowRefresh = true; Assert.True(props.AllowRefresh); Assert.Equal("True", props.Items.First().Value); props.AllowRefresh = false; Assert.False(props.AllowRefresh); Assert.Equal("False", props.Items.First().Value); props.Items.Clear(); Assert.Null(props.AllowRefresh); } [Fact] public void SetDateTimeOffset() { var props = new MyAuthenticationProperties(); props.SetDateTimeOffset("foo", new DateTimeOffset(new DateTime(2018, 03, 19, 12, 34, 56, DateTimeKind.Utc))); Assert.Equal("Mon, 19 Mar 2018 12:34:56 GMT", props.Items["foo"]); props.SetDateTimeOffset("foo", null); Assert.False(props.Items.ContainsKey("foo")); props.SetDateTimeOffset("doesnotexist", null); Assert.False(props.Items.ContainsKey("doesnotexist")); } [Fact] public void GetDateTimeOffset() { var props = new MyAuthenticationProperties(); var dateTimeOffset = new DateTimeOffset(new DateTime(2018, 03, 19, 12, 34, 56, DateTimeKind.Utc)); props.Items["foo"] = dateTimeOffset.ToString("r", CultureInfo.InvariantCulture); Assert.Equal(dateTimeOffset, props.GetDateTimeOffset("foo")); props.Items.Remove("foo"); Assert.Null(props.GetDateTimeOffset("foo")); props.Items["foo"] = "BAR"; Assert.Null(props.GetDateTimeOffset("foo")); Assert.Equal("BAR", props.Items["foo"]); } [Fact] public void SetBool() { var props = new MyAuthenticationProperties(); props.SetBool("foo", true); Assert.Equal(true.ToString(), props.Items["foo"]); props.SetBool("foo", false); Assert.Equal(false.ToString(), props.Items["foo"]); props.SetBool("foo", null); Assert.False(props.Items.ContainsKey("foo")); } [Fact] public void GetBool() { var props = new MyAuthenticationProperties(); props.Items["foo"] = true.ToString(); Assert.True(props.GetBool("foo")); props.Items["foo"] = false.ToString(); Assert.False(props.GetBool("foo")); props.Items["foo"] = null; Assert.Null(props.GetBool("foo")); props.Items["foo"] = "BAR"; Assert.Null(props.GetBool("foo")); Assert.Equal("BAR", props.Items["foo"]); } [Fact] public void Roundtrip_Serializes_With_SystemTextJson() { var props = new AuthenticationProperties() { AllowRefresh = true, ExpiresUtc = new DateTimeOffset(2021, 03, 28, 13, 47, 00, TimeSpan.Zero), IssuedUtc = new DateTimeOffset(2021, 03, 28, 12, 47, 00, TimeSpan.Zero), IsPersistent = true, RedirectUri = "/foo/bar" }; props.Items.Add("foo", "bar"); props.Parameters.Add("baz", "quux"); var json = JsonSerializer.Serialize(props); // Verify that Parameters was not serialized Assert.NotNull(json); Assert.DoesNotContain("baz", json); Assert.DoesNotContain("quux", json); var deserialized = JsonSerializer.Deserialize<AuthenticationProperties>(json); Assert.NotNull(deserialized); Assert.Equal(props.AllowRefresh, deserialized!.AllowRefresh); Assert.Equal(props.ExpiresUtc, deserialized.ExpiresUtc); Assert.Equal(props.IssuedUtc, deserialized.IssuedUtc); Assert.Equal(props.IsPersistent, deserialized.IsPersistent); Assert.Equal(props.RedirectUri, deserialized.RedirectUri); Assert.NotNull(deserialized.Items); Assert.True(deserialized.Items.ContainsKey("foo")); Assert.Equal(props.Items["foo"], deserialized.Items["foo"]); // Ensure that parameters are not round-tripped Assert.NotNull(deserialized.Parameters); Assert.Equal(0, deserialized.Parameters.Count); } [Fact] public void Parameters_Is_Not_Deserialized_With_SystemTextJson() { var json = @"{""Parameters"":{""baz"":""quux""}}"; var deserialized = JsonSerializer.Deserialize<AuthenticationProperties>(json); Assert.NotNull(deserialized); // Ensure that parameters is not deserialized from a raw payload Assert.NotNull(deserialized!.Parameters); Assert.Equal(0, deserialized.Parameters.Count); } [Fact] public void Serialization_Is_Minimised_With_SystemTextJson() { var props = new AuthenticationProperties() { AllowRefresh = true, ExpiresUtc = new DateTimeOffset(2021, 03, 28, 13, 47, 00, TimeSpan.Zero), IssuedUtc = new DateTimeOffset(2021, 03, 28, 12, 47, 00, TimeSpan.Zero), IsPersistent = true, RedirectUri = "/foo/bar" }; props.Items.Add("foo", "bar"); var options = new JsonSerializerOptions() { WriteIndented = true }; // Indented for readability if test fails var json = JsonSerializer.Serialize(props, options); // Verify that the payload doesn't duplicate the properties backed by Items Assert.Equal(@"{ ""Items"": { "".refresh"": ""True"", "".expires"": ""Sun, 28 Mar 2021 13:47:00 GMT"", "".issued"": ""Sun, 28 Mar 2021 12:47:00 GMT"", "".persistent"": """", "".redirect"": ""/foo/bar"", ""foo"": ""bar"" } }", json, ignoreLineEndingDifferences: true); } public class MyAuthenticationProperties : AuthenticationProperties { public new DateTimeOffset? GetDateTimeOffset(string key) { return base.GetDateTimeOffset(key); } public new void SetDateTimeOffset(string key, DateTimeOffset? value) { base.SetDateTimeOffset(key, value); } public new void SetBool(string key, bool? value) { base.SetBool(key, value); } public new bool? GetBool(string key) { return base.GetBool(key); } } } }
using System; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VsSDK.IntegrationTestLibrary { /// <summary> /// This class is responsible to close dialog boxes that pop up during different VS Calls /// </summary> internal class DialogBoxPurger : IDisposable { /// <summary> /// The default number of milliseconds to wait for the threads to signal to terminate. /// </summary> private const int DefaultMillisecondsToWait = 3500; /// <summary> /// Object used for synchronization between thread calls. /// </summary> internal static volatile object Mutex = new object(); /// <summary> /// The IVsUIShell. This cannot be queried on the working thread from the service provider. Must be done in the main thread.!! /// </summary> private IVsUIShell uiShell; /// <summary> /// The button to "press" on the dialog. /// </summary> private int buttonAction; /// <summary> /// Thread signales to the calling thread that it is done. /// </summary> private bool exitThread = false; /// <summary> /// Calling thread signales to this thread to die. /// </summary> private AutoResetEvent threadDone = new AutoResetEvent(false); /// <summary> /// The queued thread started. /// </summary> private AutoResetEvent threadStarted = new AutoResetEvent(false); /// <summary> /// The result of the dialogbox closing for all the dialog boxes. That is if there are two of them and one fails this will be false. /// </summary> private bool dialogBoxCloseResult = false; /// <summary> /// The expected text to see on the dialog box. If set the thread will continue finding the dialog box with this text. /// </summary> private string expectedDialogBoxText = String.Empty; /// <summary> /// The number of the same dialog boxes to wait for. /// This is for scenarios when two dialog boxes with the same text are popping up. /// </summary> private int numberOfDialogsToWaitFor = 1; /// <summary> /// Has the object been disposed. /// </summary> private bool isDisposed; /// <summary> /// Overloaded ctor. /// </summary> /// <param name="buttonAction">The botton to "press" on the dialog box.</param> /// <param name="numberOfDialogsToWaitFor">The number of dialog boxes with the same message to wait for. This is the situation when the same action pops up two of the same dialog boxes</param> /// <param name="expectedDialogMesssage">The expected dialog box message to check for.</param> internal DialogBoxPurger(int buttonAction, int numberOfDialogsToWaitFor, string expectedDialogMesssage) { this.buttonAction = buttonAction; this.numberOfDialogsToWaitFor = numberOfDialogsToWaitFor; this.expectedDialogBoxText = expectedDialogMesssage; this.Start(); } /// <summary> /// Overloaded ctor. /// </summary> /// <param name="buttonAction">The botton to "press" on the dialog box.</param> /// <param name="numberOfDialogsToWaitFor">The number of dialog boxes with the same message to wait for. This is the situation when the same action pops up two of the same dialog boxes</param> internal DialogBoxPurger(int buttonAction, int numberOfDialogsToWaitFor) { this.buttonAction = buttonAction; this.numberOfDialogsToWaitFor = numberOfDialogsToWaitFor; this.Start(); } /// <summary> /// Overloaded ctor. /// </summary> /// <param name="buttonAction">The botton to "press" on the dialog box.</param> /// <param name="expectedDialogMesssage">The expected dialog box message to check for.</param> internal DialogBoxPurger(int buttonAction, string expectedDialogMesssage) { this.buttonAction = buttonAction; this.expectedDialogBoxText = expectedDialogMesssage; this.Start(); } /// <summary> /// Overloaded ctor. /// </summary> /// <param name="buttonAction">The botton to "press" on the dialog box.</param> internal DialogBoxPurger(int buttonAction) { this.buttonAction = buttonAction; this.Start(); } void IDisposable.Dispose() { if (this.isDisposed) { return; } this.WaitForDialogThreadToTerminate(); this.isDisposed = true; } /// <summary> /// Spawns a thread that will start listening to dialog boxes. /// </summary> private void Start() { // We ask for the uishell here since we cannot do that on the therad that we will spawn. IVsUIShell uiShell = Package.GetGlobalService(typeof(SVsUIShell)) as IVsUIShell; if (uiShell == null) { throw new InvalidOperationException("Could not get the uiShell from the serviceProvider"); } this.uiShell = uiShell; System.Threading.Thread thread = new System.Threading.Thread(new ThreadStart(this.HandleDialogBoxes)); thread.Start(); // We should never deadlock here, hence do not use the lock. Wait to be sure that the thread started. this.threadStarted.WaitOne(3500, false); } /// <summary> /// Waits for the dialog box close thread to terminate. If the thread does not signal back within millisecondsToWait that it is shutting down, /// then it will tell to the thread to do it. /// </summary> private bool WaitForDialogThreadToTerminate() { return this.WaitForDialogThreadToTerminate(DefaultMillisecondsToWait); } /// <summary> /// Waits for the dialog box close thread to terminate. If the thread does not signal back within millisecondsToWait that it is shutting down, /// then it will tell to the thread to do it. /// </summary> /// <param name="numberOfMillisecondsToWait">The number milliseconds to wait for until the dialog purger thread is signaled to terminate. This is just for safe precaution that we do not hang. </param> /// <returns>The result of the dialog boxes closing</returns> private bool WaitForDialogThreadToTerminate(int numberOfMillisecondsToWait) { bool signaled = false; // We give millisecondsToWait sec to bring up and close the dialog box. signaled = this.threadDone.WaitOne(numberOfMillisecondsToWait, false); // Kill the thread since a timeout occured. if (!signaled) { lock (Mutex) { // Set the exit thread to true. Next time the thread will kill itselfes if it sees this.exitThread = true; } // Wait for the thread to finish. We should never deadlock here. this.threadDone.WaitOne(); } return this.dialogBoxCloseResult; } /// <summary> /// This is the thread method. /// </summary> private void HandleDialogBoxes() { // No synchronization numberOfDialogsToWaitFor since it is readonly IntPtr[] hwnds = new IntPtr[this.numberOfDialogsToWaitFor]; bool[] dialogBoxCloseResults = new bool[this.numberOfDialogsToWaitFor]; try { // Signal that we started lock (Mutex) { this.threadStarted.Set(); } // The loop will be exited either if a message is send by the caller thread or if we found the dialog. If a message box text is specified the loop will not exit until the dialog is found. bool stayInLoop = true; int dialogBoxesToWaitFor = 1; while (stayInLoop) { int hwndIndex = dialogBoxesToWaitFor - 1; // We need to lock since the caller might set context to null. lock (Mutex) { if (this.exitThread) { break; } // We protect the shell too from reentrency. this.uiShell.GetDialogOwnerHwnd(out hwnds[hwndIndex]); } if (hwnds[hwndIndex] != IntPtr.Zero) { StringBuilder windowClassName = new StringBuilder(256); NativeMethods.GetClassName(hwnds[hwndIndex], windowClassName, windowClassName.Capacity); // The #32770 is the class name of a messagebox dialog. if (windowClassName.ToString().Contains("#32770")) { IntPtr unmanagedMemoryLocation = IntPtr.Zero; string dialogBoxText = String.Empty; try { unmanagedMemoryLocation = Marshal.AllocHGlobal(10 * 1024); NativeMethods.EnumChildWindows(hwnds[hwndIndex], new NativeMethods.CallBack(FindMessageBoxString), unmanagedMemoryLocation); dialogBoxText = Marshal.PtrToStringUni(unmanagedMemoryLocation); } finally { if (unmanagedMemoryLocation != IntPtr.Zero) { Marshal.FreeHGlobal(unmanagedMemoryLocation); } } lock (Mutex) { // Since this is running on the main thread be sure that we close the dialog. bool dialogCloseResult = false; if (this.buttonAction != 0) { dialogCloseResult = NativeMethods.EndDialog(hwnds[hwndIndex], this.buttonAction); } // Check if we have found the right dialog box. if (String.IsNullOrEmpty(this.expectedDialogBoxText) || (!String.IsNullOrEmpty(dialogBoxText) && String.Compare(this.expectedDialogBoxText, dialogBoxText.Trim(), StringComparison.OrdinalIgnoreCase) == 0)) { dialogBoxCloseResults[hwndIndex] = dialogCloseResult; if (dialogBoxesToWaitFor++ >= this.numberOfDialogsToWaitFor) { stayInLoop = false; } } } } } } } finally { //Let the main thread run a possible close command. System.Threading.Thread.Sleep(2000); foreach (IntPtr hwnd in hwnds) { // At this point the dialog should be closed, if not attempt to close it. if (hwnd != IntPtr.Zero) { NativeMethods.SendMessage(hwnd, NativeMethods.WM_CLOSE, 0, new IntPtr(0)); } } lock (Mutex) { // Be optimistic. this.dialogBoxCloseResult = true; for (int i = 0; i < dialogBoxCloseResults.Length; i++) { if (!dialogBoxCloseResults[i]) { this.dialogBoxCloseResult = false; break; } } this.threadDone.Set(); } } } /// <summary> /// Finds a messagebox string on a messagebox. /// </summary> /// <param name="hwnd">The windows handle of the dialog</param> /// <param name="unmanagedMemoryLocation">A pointer to the memorylocation the string will be written to</param> /// <returns>True if found.</returns> private static bool FindMessageBoxString(IntPtr hwnd, IntPtr unmanagedMemoryLocation) { StringBuilder sb = new StringBuilder(512); NativeMethods.GetClassName(hwnd, sb, sb.Capacity); if (sb.ToString().ToLower().Contains("static")) { StringBuilder windowText = new StringBuilder(2048); NativeMethods.GetWindowText(hwnd, windowText, windowText.Capacity); if (windowText.Length > 0) { IntPtr stringAsPtr = IntPtr.Zero; try { stringAsPtr = Marshal.StringToHGlobalAnsi(windowText.ToString()); char[] stringAsArray = windowText.ToString().ToCharArray(); // Since unicode characters are copied check if we are out of the allocated length. // If not add the end terminating zero. if ((2 * stringAsArray.Length) + 1 < 2048) { Marshal.Copy(stringAsArray, 0, unmanagedMemoryLocation, stringAsArray.Length); Marshal.WriteInt32(unmanagedMemoryLocation, 2 * stringAsArray.Length, 0); } } finally { if (stringAsPtr != IntPtr.Zero) { Marshal.FreeHGlobal(stringAsPtr); } } return false; } } return true; } } }
using ICSharpCode.TextEditor.Document; using System; using System.Collections.Generic; using System.Drawing; namespace ICSharpCode.TextEditor { public class DrawableLine { private class SimpleTextWord { internal TextWordType Type; internal string Word; internal bool Bold; internal Color Color; internal static readonly DrawableLine.SimpleTextWord Space = new DrawableLine.SimpleTextWord(TextWordType.Space, " ", false, Color.Black); internal static readonly DrawableLine.SimpleTextWord Tab = new DrawableLine.SimpleTextWord(TextWordType.Tab, "\t", false, Color.Black); public SimpleTextWord(TextWordType Type, string Word, bool Bold, Color Color) { this.Type = Type; this.Word = Word; this.Bold = Bold; this.Color = Color; } } private static StringFormat sf = (StringFormat)StringFormat.GenericTypographic.Clone(); private List<DrawableLine.SimpleTextWord> words = new List<DrawableLine.SimpleTextWord>(); private SizeF spaceSize; private Font monospacedFont; private Font boldMonospacedFont; public int LineLength { get { int num = 0; foreach (DrawableLine.SimpleTextWord current in this.words) { num += current.Word.Length; } return num; } } public DrawableLine(IDocument document, LineSegment line, Font monospacedFont, Font boldMonospacedFont) { this.monospacedFont = monospacedFont; this.boldMonospacedFont = boldMonospacedFont; if (line.Words != null) { using (List<TextWord>.Enumerator enumerator = line.Words.GetEnumerator()) { while (enumerator.MoveNext()) { TextWord current = enumerator.Current; if (current.Type == TextWordType.Space) { this.words.Add(DrawableLine.SimpleTextWord.Space); } else { if (current.Type == TextWordType.Tab) { this.words.Add(DrawableLine.SimpleTextWord.Tab); } else { this.words.Add(new DrawableLine.SimpleTextWord(TextWordType.Word, current.Word, current.Bold, current.Color)); } } } return; } } this.words.Add(new DrawableLine.SimpleTextWord(TextWordType.Word, document.GetText(line), false, Color.Black)); } public void SetBold(int startIndex, int endIndex, bool bold) { if (startIndex < 0) { throw new ArgumentException("startIndex must be >= 0"); } if (startIndex > endIndex) { throw new ArgumentException("startIndex must be <= endIndex"); } if (startIndex == endIndex) { return; } int num = 0; for (int i = 0; i < this.words.Count; i++) { DrawableLine.SimpleTextWord simpleTextWord = this.words[i]; if (num >= endIndex) { return; } int num2 = num + simpleTextWord.Word.Length; if (startIndex <= num && endIndex >= num2) { simpleTextWord.Bold = bold; } else { if (startIndex <= num) { int num3 = endIndex - num; DrawableLine.SimpleTextWord item = new DrawableLine.SimpleTextWord(simpleTextWord.Type, simpleTextWord.Word.Substring(num3), simpleTextWord.Bold, simpleTextWord.Color); this.words.Insert(i + 1, item); simpleTextWord.Bold = bold; simpleTextWord.Word = simpleTextWord.Word.Substring(0, num3); } else { if (startIndex < num2) { int num4 = startIndex - num; DrawableLine.SimpleTextWord item2 = new DrawableLine.SimpleTextWord(simpleTextWord.Type, simpleTextWord.Word.Substring(num4), simpleTextWord.Bold, simpleTextWord.Color); this.words.Insert(i + 1, item2); simpleTextWord.Word = simpleTextWord.Word.Substring(0, num4); } } } num = num2; } } public static float DrawDocumentWord(Graphics g, string word, PointF position, Font font, Color foreColor) { if (word == null || word.Length == 0) { return 0f; } SizeF sizeF = g.MeasureString(word, font, 32768, DrawableLine.sf); g.DrawString(word, font, BrushRegistry.GetBrush(foreColor), position, DrawableLine.sf); return sizeF.Width; } public SizeF GetSpaceSize(Graphics g) { if (this.spaceSize.IsEmpty) { this.spaceSize = g.MeasureString("-", this.boldMonospacedFont, new PointF(0f, 0f), DrawableLine.sf); } return this.spaceSize; } public void DrawLine(Graphics g, ref float xPos, float xOffset, float yPos, Color c) { SizeF sizeF = this.GetSpaceSize(g); foreach (DrawableLine.SimpleTextWord current in this.words) { switch (current.Type) { case TextWordType.Word: { xPos += DrawableLine.DrawDocumentWord(g, current.Word, new PointF(xPos + xOffset, yPos), current.Bold ? this.boldMonospacedFont : this.monospacedFont, (c == Color.Empty) ? current.Color : c); break; } case TextWordType.Space: { xPos += sizeF.Width; break; } case TextWordType.Tab: { float num = sizeF.Width * 4f; xPos += num; xPos = (float)((int)((xPos + 2f) / num)) * num; break; } } } } public void DrawLine(Graphics g, ref float xPos, float xOffset, float yPos) { this.DrawLine(g, ref xPos, xOffset, yPos, Color.Empty); } public float MeasureWidth(Graphics g, float xPos) { SizeF sizeF = this.GetSpaceSize(g); foreach (DrawableLine.SimpleTextWord current in this.words) { switch (current.Type) { case TextWordType.Word: { if (current.Word != null && current.Word.Length > 0) { xPos += g.MeasureString(current.Word, current.Bold ? this.boldMonospacedFont : this.monospacedFont, 32768, DrawableLine.sf).Width; } break; } case TextWordType.Space: { xPos += sizeF.Width; break; } case TextWordType.Tab: { float num = sizeF.Width * 4f; xPos += num; xPos = (float)((int)((xPos + 2f) / num)) * num; break; } } } return xPos; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace JitTest { internal class Test { private static void testNumbers(ulong a, ulong b) { ulong c = 0; try { c = checked(a + b); if (c < a || c < b) throw new Exception(); } catch (OverflowException) { ulong AH = a >> 32; ulong AL = a & 0xffffffff; ulong BH = b >> 32; ulong BL = b & 0xffffffff; ulong L = checked(BL + AL); ulong H = checked(AH + BH); if (H < 0x100000000) { if (L >= 0x100000000) { checked { H++; L -= 0x100000000; if (L >= 0x100000000) throw new Exception(); } } if (checked(L <= 0xffffffffffffffff - (H << 32))) throw new Exception(); } return; } if (checked(c - b != a || c - a != b)) throw new Exception(); } private static int Main() { try { testNumbers(0x0000000000000009, 0x00000000000000b8); testNumbers(0x0000000000000009, 0x00000000000000f9); testNumbers(0x000000000000006e, 0x0000000000000093); testNumbers(0x000000000000001e, 0x0000000000000086); testNumbers(0x00000000000000cc, 0x000000000000583f); testNumbers(0x00000000000000c9, 0x000000000000a94c); testNumbers(0x0000000000000054, 0x0000000000002d06); testNumbers(0x0000000000000030, 0x0000000000009921); testNumbers(0x000000000000001d, 0x0000000000450842); testNumbers(0x000000000000002a, 0x0000000000999f6c); testNumbers(0x00000000000000c5, 0x000000000090faa7); testNumbers(0x0000000000000050, 0x000000000069de08); testNumbers(0x000000000000009a, 0x000000000cd715be); testNumbers(0x0000000000000039, 0x0000000016a61eb5); testNumbers(0x00000000000000e0, 0x0000000095575fef); testNumbers(0x0000000000000093, 0x00000000209e58c5); testNumbers(0x000000000000003b, 0x0000000c3c34b48c); testNumbers(0x00000000000000c2, 0x0000006a671c470f); testNumbers(0x000000000000004b, 0x000000f538cede2b); testNumbers(0x0000000000000099, 0x0000005ba885d43b); testNumbers(0x0000000000000068, 0x00009f692f98ac45); testNumbers(0x00000000000000d9, 0x00008d5eaa7f0a8e); testNumbers(0x00000000000000ac, 0x0000ba1316512e4c); testNumbers(0x000000000000001c, 0x00008c4fbf2f14aa); testNumbers(0x00000000000000c0, 0x0069a9eb9a9bc822); testNumbers(0x0000000000000074, 0x003f8f5a893de200); testNumbers(0x0000000000000027, 0x000650eb1747a5bc); testNumbers(0x00000000000000d9, 0x00d3d50809c70fda); testNumbers(0x00000000000000c0, 0xac6556a4ca94513e); testNumbers(0x0000000000000020, 0xa697fcbfd6d232d1); testNumbers(0x000000000000009c, 0xc4421a4f5147b9b8); testNumbers(0x000000000000009e, 0xc5ef494112a7b33f); testNumbers(0x000000000000f7fa, 0x00000000000000af); testNumbers(0x000000000000ad17, 0x00000000000000e8); testNumbers(0x000000000000c9c4, 0x0000000000000045); testNumbers(0x000000000000a704, 0x0000000000000012); testNumbers(0x000000000000c55b, 0x000000000000a33a); testNumbers(0x000000000000ab88, 0x0000000000009a3c); testNumbers(0x000000000000a539, 0x000000000000cf3a); testNumbers(0x0000000000005890, 0x000000000000eec8); testNumbers(0x000000000000e9e2, 0x0000000000fe7c46); testNumbers(0x0000000000007303, 0x0000000000419f2a); testNumbers(0x000000000000e105, 0x000000000013f913); testNumbers(0x0000000000008191, 0x0000000000fa2458); testNumbers(0x00000000000006d9, 0x0000000091cf14f7); testNumbers(0x000000000000bdb1, 0x0000000086c2a97c); testNumbers(0x000000000000e905, 0x0000000064f702f4); testNumbers(0x0000000000002fdc, 0x00000000f059caf6); testNumbers(0x000000000000f8fd, 0x00000013f0265b1e); testNumbers(0x000000000000e8b8, 0x0000000aa69a6308); testNumbers(0x0000000000003d00, 0x000000fbcb67879b); testNumbers(0x000000000000aa46, 0x00000085c3d371d5); testNumbers(0x0000000000005f60, 0x000008cde4a63203); testNumbers(0x00000000000092b5, 0x00007ca86ba2f30e); testNumbers(0x00000000000093c6, 0x0000a2d73fc4eac0); testNumbers(0x0000000000004156, 0x000006dbd08f2fda); testNumbers(0x0000000000004597, 0x006cfb0ba5962826); testNumbers(0x0000000000006bac, 0x001e79315071480f); testNumbers(0x0000000000002c3a, 0x0092f12cbd82df69); testNumbers(0x0000000000009859, 0x00b0f0cd9dc019f2); testNumbers(0x000000000000b37f, 0x4966447d15850076); testNumbers(0x0000000000005e34, 0x7c1869c9ed2cad38); testNumbers(0x0000000000005c54, 0x7cee70ee82837a08); testNumbers(0x000000000000967f, 0x4eb98adf4b8b0d32); testNumbers(0x0000000000fd2919, 0x000000000000005d); testNumbers(0x0000000000abd5b1, 0x0000000000000098); testNumbers(0x0000000000ab1887, 0x00000000000000ef); testNumbers(0x000000000096034a, 0x000000000000002f); testNumbers(0x0000000000d5bb94, 0x00000000000057d2); testNumbers(0x0000000000d7b2cb, 0x00000000000080f5); testNumbers(0x00000000004ccc6d, 0x000000000000087c); testNumbers(0x0000000000ec0c50, 0x000000000000bdff); testNumbers(0x00000000008a6865, 0x000000000076c014); testNumbers(0x0000000000ac38dd, 0x0000000000f12b09); testNumbers(0x0000000000615e2a, 0x0000000000e7cbf8); testNumbers(0x00000000000e214f, 0x00000000005b8e2f); testNumbers(0x00000000003bd7c6, 0x00000000c1db4e46); testNumbers(0x0000000000ae208d, 0x0000000001c9aa7a); testNumbers(0x00000000008a9cef, 0x0000000003930b07); testNumbers(0x000000000036b866, 0x00000000d64b7bef); testNumbers(0x0000000000d337cd, 0x000000a2b45fb7de); testNumbers(0x0000000000024471, 0x0000005c5de3da89); testNumbers(0x0000000000012b15, 0x0000007cd40030fe); testNumbers(0x0000000000d38af2, 0x0000005905921572); testNumbers(0x0000000000aca0d7, 0x0000c632301abeb8); testNumbers(0x00000000004eadc2, 0x00006a1ebf37403c); testNumbers(0x00000000005d909c, 0x00004021bfa15862); testNumbers(0x0000000000710e08, 0x0000e9a1a030b230); testNumbers(0x0000000000478b9b, 0x00804add8afc31d9); testNumbers(0x00000000005754ed, 0x00af85e7ebb1ce33); testNumbers(0x00000000003ab44e, 0x00f41b9f70360f78); testNumbers(0x00000000007aa129, 0x00eb6e4eddf7eb87); testNumbers(0x00000000003b036f, 0x333874e4330fbfa4); testNumbers(0x0000000000a33186, 0xec8607412503fc4c); testNumbers(0x00000000009af471, 0xe7ad0935fdbff151); testNumbers(0x0000000000c04e8c, 0x58ee406ab936ac24); testNumbers(0x0000000054fdd28b, 0x0000000000000034); testNumbers(0x0000000033736b36, 0x00000000000000fd); testNumbers(0x0000000069cfe4b7, 0x0000000000000026); testNumbers(0x00000000fd078d36, 0x00000000000000dc); testNumbers(0x0000000075cc3f36, 0x0000000000001617); testNumbers(0x00000000075d660e, 0x0000000000008511); testNumbers(0x0000000052acb037, 0x00000000000043cb); testNumbers(0x00000000a0db7bf5, 0x0000000000002c98); testNumbers(0x0000000083d4be11, 0x0000000000ba37c9); testNumbers(0x0000000083d04f94, 0x00000000003ddbd0); testNumbers(0x000000005ed41f6a, 0x0000000000eaf1d5); testNumbers(0x000000000e364a9a, 0x000000000085880c); testNumbers(0x0000000012657ecb, 0x00000000a88b8a68); testNumbers(0x000000009897a4ac, 0x0000000076707981); testNumbers(0x00000000469cd1cf, 0x00000000cf40f67a); testNumbers(0x00000000ee7444c8, 0x00000000d1b0d7de); testNumbers(0x00000000fbb6f547, 0x000000c1ef3c4d9b); testNumbers(0x000000000e20dd53, 0x000000b05833c7cf); testNumbers(0x00000000e5733fb8, 0x0000008eae18a855); testNumbers(0x000000005db1c271, 0x000000c4a2f7c27d); testNumbers(0x0000000007add22a, 0x00000ed9fd23dc3e); testNumbers(0x000000002239d1d5, 0x0000a1ae07a62635); testNumbers(0x00000000410d4d58, 0x0000c05c5205bed2); testNumbers(0x000000004c3c435e, 0x00001e30c1bf628a); testNumbers(0x00000000096f44d5, 0x005488c521a6072b); testNumbers(0x0000000017f28913, 0x00796ff3891c44ff); testNumbers(0x0000000065be69cf, 0x00dd5c6f9b3f3119); testNumbers(0x000000002200f221, 0x00ab6c98c90cfe9d); testNumbers(0x00000000d48bee1a, 0x64b76d7491a58799); testNumbers(0x000000006cb93100, 0xa515fe27402dad45); testNumbers(0x00000000bed95abe, 0xc9924098acc74be9); testNumbers(0x0000000092781a2e, 0x67ada9ef3f9e39b7); testNumbers(0x000000e3aafcdae2, 0x000000000000009c); testNumbers(0x000000d8dad80c34, 0x0000000000000099); testNumbers(0x000000addcd074d6, 0x00000000000000ea); testNumbers(0x00000096735bc25a, 0x00000000000000ba); testNumbers(0x000000f492ef7446, 0x00000000000039b1); testNumbers(0x000000bc86816119, 0x0000000000001520); testNumbers(0x00000060a36818e7, 0x000000000000c5a8); testNumbers(0x000000317121d508, 0x000000000000ac3d); testNumbers(0x0000004abfdaf232, 0x00000000005cea57); testNumbers(0x000000acc458f392, 0x0000000000a9c3e3); testNumbers(0x0000001020993532, 0x0000000000df6042); testNumbers(0x000000ad25b80abb, 0x0000000000cec15b); testNumbers(0x0000002305d2c443, 0x000000002a26131c); testNumbers(0x00000007c42e2ce0, 0x000000009768024f); testNumbers(0x00000076f674816c, 0x000000008d33c7b4); testNumbers(0x000000bf567b23bc, 0x00000000ef264890); testNumbers(0x000000e3283681a0, 0x0000002e66850719); testNumbers(0x000000011fe13754, 0x00000066fad0b407); testNumbers(0x00000052f259009f, 0x000000a2886ef414); testNumbers(0x000000a9ebb540fc, 0x0000009d27ba694f); testNumbers(0x00000083af60d7eb, 0x0000b6f2a0f51f4c); testNumbers(0x000000f2ec42d13a, 0x000046855f279407); testNumbers(0x00000094e71cb562, 0x00002d9566618e56); testNumbers(0x000000c0ee690ddc, 0x000054295c8ca584); testNumbers(0x0000002683cd5206, 0x00a5a2d269bcd188); testNumbers(0x0000002e77038305, 0x00c727f0f3787e22); testNumbers(0x0000008323b9d026, 0x00fed29f8575c120); testNumbers(0x0000007b3231f0fc, 0x0091080854b27d3e); testNumbers(0x00000084522a7708, 0x91ba8f22fccd6222); testNumbers(0x000000afb1b50d90, 0x3261a532b65c7838); testNumbers(0x0000002c65e838c6, 0x5b858452c9bf6f39); testNumbers(0x000000219e837734, 0x97873bed5bb0a44b); testNumbers(0x00009f133e2f116f, 0x0000000000000073); testNumbers(0x0000887577574766, 0x0000000000000048); testNumbers(0x0000ba4c778d4aa8, 0x000000000000003a); testNumbers(0x00002683df421474, 0x0000000000000056); testNumbers(0x00006ff76294c275, 0x00000000000089f7); testNumbers(0x0000fdf053abefa2, 0x000000000000eb65); testNumbers(0x0000ea4b254b24eb, 0x000000000000ba27); testNumbers(0x000009f7ce21b811, 0x000000000000e8f6); testNumbers(0x00009cc645fa08a1, 0x0000000000a29ea3); testNumbers(0x0000726f9a9f816e, 0x000000000070dce1); testNumbers(0x0000a4be34825ef6, 0x0000000000bb2be7); testNumbers(0x000057ff147cb7c1, 0x0000000000e255af); testNumbers(0x0000ab9d6f546dd4, 0x000000007e2772a5); testNumbers(0x0000b148e3446e89, 0x0000000051ed3c28); testNumbers(0x00001e3abfe9725e, 0x00000000d4dec3f4); testNumbers(0x0000f61bcaba115e, 0x00000000fade149f); testNumbers(0x0000ae642b9a6626, 0x000000d8de0e0b9a); testNumbers(0x00009d015a13c8ae, 0x000000afc8827997); testNumbers(0x0000ecc72cc2df89, 0x00000070d47ec7c4); testNumbers(0x0000fdbf05894fd2, 0x00000012aec393bd); testNumbers(0x0000cd7675a70874, 0x0000d7d696a62cbc); testNumbers(0x0000fad44a89216d, 0x0000cb8cfc8ada4c); testNumbers(0x0000f41eb5363551, 0x00009c040aa7775e); testNumbers(0x00003c02d93e01f6, 0x0000f1f4e68a14f8); testNumbers(0x0000e0d99954b598, 0x00b2a2de4e453485); testNumbers(0x0000a6081be866d9, 0x00f2a12e845e4f2e); testNumbers(0x0000ae56a5680dfd, 0x00c96cd7c15d5bec); testNumbers(0x0000360363e37938, 0x00d4ed572e1937e0); testNumbers(0x00001f052aebf185, 0x3584e582d1c6db1a); testNumbers(0x00003fac9c7b3d1b, 0xa4b120f080d69113); testNumbers(0x00005330d51c3217, 0xc16dd32ffd822c0e); testNumbers(0x0000cd0694ff5ab0, 0x29673fe67245fbfc); testNumbers(0x0098265e5a308523, 0x000000000000007d); testNumbers(0x00560863350df217, 0x00000000000000c8); testNumbers(0x00798ce804d829a1, 0x00000000000000b1); testNumbers(0x007994c0051256fd, 0x000000000000005c); testNumbers(0x00ff1a2838e69f42, 0x0000000000003c16); testNumbers(0x009e7e95ac5de2c7, 0x000000000000ed49); testNumbers(0x00fd6867eabba5c0, 0x000000000000c689); testNumbers(0x009d1632daf20de0, 0x000000000000b74f); testNumbers(0x00ee29d8f76d4e9c, 0x00000000008020d4); testNumbers(0x0089e03ecf8daa0a, 0x00000000003e7587); testNumbers(0x00115763be4beb44, 0x000000000088f762); testNumbers(0x00815cfc87c427d0, 0x00000000009eec06); testNumbers(0x001d9c3c9ded0c1a, 0x00000000b9f6d331); testNumbers(0x00932225412f1222, 0x00000000130ff743); testNumbers(0x00fe82151e2e0bf3, 0x00000000781cd6f9); testNumbers(0x002222abb5061b12, 0x000000000491f1df); testNumbers(0x0012ce0cf0452748, 0x000000a8566274aa); testNumbers(0x00e570484e9937e1, 0x000000ac81f171be); testNumbers(0x00eb371f7f8f514e, 0x000000df0248189c); testNumbers(0x003777a7cc43dfd7, 0x0000003a7b8eaf40); testNumbers(0x00e181db76238786, 0x00004126e572a568); testNumbers(0x00ac1df87977e122, 0x0000e1e8cfde6678); testNumbers(0x001c858763a2c23b, 0x000004ef61f3964f); testNumbers(0x00bd786bbb71ce46, 0x00002cda097a464f); testNumbers(0x00a7a6de21a46360, 0x00007afda16f98c3); testNumbers(0x006fed70a6ccfdf2, 0x009771441e8e00e8); testNumbers(0x005ad2782dcd5e60, 0x000d170d518385f6); testNumbers(0x001fd67b153bc9b9, 0x007b3366dff66c6c); testNumbers(0x00bf00203beb73f4, 0x693495fefab1c77e); testNumbers(0x002faac1b1b068f8, 0x1cb11cc5c3aaff86); testNumbers(0x00bb63cfbffe7648, 0x84f5b0c583f9e77b); testNumbers(0x00615db89673241c, 0x8de5f125247eba0f); testNumbers(0x9be183a6b293dffe, 0x0000000000000072); testNumbers(0xa3df9b76d8a51b19, 0x00000000000000c4); testNumbers(0xb4cc300f0ea7566d, 0x000000000000007e); testNumbers(0xfdac12a8e23e16e7, 0x0000000000000015); testNumbers(0xc0805405aadc0f47, 0x00000000000019d4); testNumbers(0x843a391f8d9f8972, 0x000000000000317a); testNumbers(0x5a0d124c427ed453, 0x00000000000034fe); testNumbers(0x8631150f34008f1b, 0x0000000000002ecd); testNumbers(0x3ff4c18715ad3a76, 0x000000000072d22a); testNumbers(0x3ef93e5a649422bd, 0x0000000000db5c60); testNumbers(0x6bdd1056ae58fe0e, 0x0000000000805c75); testNumbers(0xeff1fa30f3ad9ded, 0x00000000000c83ca); testNumbers(0xbbc143ac147e56a9, 0x00000000161179b7); testNumbers(0x0829dde88caa2e45, 0x000000001443ab62); testNumbers(0x97ac43ff797a4514, 0x0000000033eef42b); testNumbers(0x703e9cdf96a148aa, 0x000000008e08f3d8); testNumbers(0x75cbb739b54e2ad6, 0x0000007a8b12628c); testNumbers(0x91e42fafe97d638f, 0x0000000fbe867c51); testNumbers(0x9159d77deec116c1, 0x00000096c0c774fc); testNumbers(0xb59dbb4c15761d88, 0x0000004a033a73e7); testNumbers(0xab668e9783af9617, 0x00005aa18404076c); testNumbers(0x54c68e5b5c4127df, 0x0000f2934fd8dd1f); testNumbers(0xf490d3936184c9f9, 0x00004007477e2110); testNumbers(0x349e577c9d5c44e2, 0x0000bdb2235af963); testNumbers(0x58f3ac26cdafde28, 0x0017d4f4ade9ec35); testNumbers(0xa4a263c316d21f4c, 0x00a7ec1e6fda834b); testNumbers(0x6ab14771c448666f, 0x005b0f49593c3a27); testNumbers(0x15f392c3602aa4f7, 0x0018af171045f88e); testNumbers(0xf17de69c0063f62c, 0xee2a164c2c3a46f8); testNumbers(0xf34b743eeff8e5c6, 0x4f4067f1a0e404ad); testNumbers(0xee0296f678756647, 0xf1bbfdc6f0280d36); testNumbers(0x65c33db0c952b829, 0xa7ab9c39dcffbcf3); Console.WriteLine("All tests passed."); return 100; } catch (DivideByZeroException) { return 1; } } } }
using System; using Avalonia.Controls.Metadata; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Controls.Utils; using Avalonia.Layout; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Metadata; namespace Avalonia.Controls.Presenters { /// <summary> /// Presents a single item of data inside a <see cref="TemplatedControl"/> template. /// </summary> [PseudoClasses(":empty")] public class ContentPresenter : Control, IContentPresenter { /// <summary> /// Defines the <see cref="Background"/> property. /// </summary> public static readonly StyledProperty<IBrush?> BackgroundProperty = Border.BackgroundProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="BorderBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush?> BorderBrushProperty = Border.BorderBrushProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="BorderThickness"/> property. /// </summary> public static readonly StyledProperty<Thickness> BorderThicknessProperty = Border.BorderThicknessProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="CornerRadius"/> property. /// </summary> public static readonly StyledProperty<CornerRadius> CornerRadiusProperty = Border.CornerRadiusProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="BoxShadow"/> property. /// </summary> public static readonly StyledProperty<BoxShadows> BoxShadowProperty = Border.BoxShadowProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="Child"/> property. /// </summary> public static readonly DirectProperty<ContentPresenter, IControl?> ChildProperty = AvaloniaProperty.RegisterDirect<ContentPresenter, IControl?>( nameof(Child), o => o.Child); /// <summary> /// Defines the <see cref="Content"/> property. /// </summary> public static readonly StyledProperty<object?> ContentProperty = ContentControl.ContentProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="ContentTemplate"/> property. /// </summary> public static readonly StyledProperty<IDataTemplate?> ContentTemplateProperty = ContentControl.ContentTemplateProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="HorizontalContentAlignment"/> property. /// </summary> public static readonly StyledProperty<HorizontalAlignment> HorizontalContentAlignmentProperty = ContentControl.HorizontalContentAlignmentProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="VerticalContentAlignment"/> property. /// </summary> public static readonly StyledProperty<VerticalAlignment> VerticalContentAlignmentProperty = ContentControl.VerticalContentAlignmentProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="Padding"/> property. /// </summary> public static readonly StyledProperty<Thickness> PaddingProperty = Decorator.PaddingProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="RecognizesAccessKey"/> property /// </summary> public static readonly DirectProperty<ContentPresenter, bool> RecognizesAccessKeyProperty = AvaloniaProperty.RegisterDirect<ContentPresenter, bool>( nameof(RecognizesAccessKey), cp => cp.RecognizesAccessKey, (cp, value) => cp.RecognizesAccessKey = value); private IControl? _child; private bool _createdChild; private IRecyclingDataTemplate? _recyclingDataTemplate; private readonly BorderRenderHelper _borderRenderer = new BorderRenderHelper(); private bool _recognizesAccessKey; /// <summary> /// Initializes static members of the <see cref="ContentPresenter"/> class. /// </summary> static ContentPresenter() { AffectsRender<ContentPresenter>(BackgroundProperty, BorderBrushProperty, BorderThicknessProperty, CornerRadiusProperty); AffectsArrange<ContentPresenter>(HorizontalContentAlignmentProperty, VerticalContentAlignmentProperty); AffectsMeasure<ContentPresenter>(BorderThicknessProperty, PaddingProperty); ContentProperty.Changed.AddClassHandler<ContentPresenter>((x, e) => x.ContentChanged(e)); ContentTemplateProperty.Changed.AddClassHandler<ContentPresenter>((x, e) => x.ContentChanged(e)); TemplatedParentProperty.Changed.AddClassHandler<ContentPresenter>((x, e) => x.TemplatedParentChanged(e)); } public ContentPresenter() { UpdatePseudoClasses(); } /// <summary> /// Gets or sets a brush with which to paint the background. /// </summary> public IBrush? Background { get { return GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } /// <summary> /// Gets or sets a brush with which to paint the border. /// </summary> public IBrush? BorderBrush { get { return GetValue(BorderBrushProperty); } set { SetValue(BorderBrushProperty, value); } } /// <summary> /// Gets or sets the thickness of the border. /// </summary> public Thickness BorderThickness { get { return GetValue(BorderThicknessProperty); } set { SetValue(BorderThicknessProperty, value); } } /// <summary> /// Gets or sets the radius of the border rounded corners. /// </summary> public CornerRadius CornerRadius { get { return GetValue(CornerRadiusProperty); } set { SetValue(CornerRadiusProperty, value); } } /// <summary> /// Gets or sets the box shadow effect parameters /// </summary> public BoxShadows BoxShadow { get => GetValue(BoxShadowProperty); set => SetValue(BoxShadowProperty, value); } /// <summary> /// Gets the control displayed by the presenter. /// </summary> public IControl? Child { get { return _child; } private set { SetAndRaise(ChildProperty, ref _child, value); } } /// <summary> /// Gets or sets the content to be displayed by the presenter. /// </summary> [DependsOn(nameof(ContentTemplate))] public object? Content { get { return GetValue(ContentProperty); } set { SetValue(ContentProperty, value); } } /// <summary> /// Gets or sets the data template used to display the content of the control. /// </summary> public IDataTemplate? ContentTemplate { get { return GetValue(ContentTemplateProperty); } set { SetValue(ContentTemplateProperty, value); } } /// <summary> /// Gets or sets the horizontal alignment of the content within the border the control. /// </summary> public HorizontalAlignment HorizontalContentAlignment { get { return GetValue(HorizontalContentAlignmentProperty); } set { SetValue(HorizontalContentAlignmentProperty, value); } } /// <summary> /// Gets or sets the vertical alignment of the content within the border of the control. /// </summary> public VerticalAlignment VerticalContentAlignment { get { return GetValue(VerticalContentAlignmentProperty); } set { SetValue(VerticalContentAlignmentProperty, value); } } /// <summary> /// Gets or sets the space between the border and the <see cref="Child"/> control. /// </summary> public Thickness Padding { get { return GetValue(PaddingProperty); } set { SetValue(PaddingProperty, value); } } /// <summary> /// Determine if <see cref="ContentPresenter"/> should use <see cref="AccessText"/> in its style /// </summary> public bool RecognizesAccessKey { get => _recognizesAccessKey; set => SetAndRaise(RecognizesAccessKeyProperty, ref _recognizesAccessKey, value); } /// <summary> /// Gets the host content control. /// </summary> internal IContentPresenterHost? Host { get; private set; } /// <inheritdoc/> public sealed override void ApplyTemplate() { if (!_createdChild && ((ILogical)this).IsAttachedToLogicalTree) { UpdateChild(); } } /// <summary> /// Updates the <see cref="Child"/> control based on the control's <see cref="Content"/>. /// </summary> /// <remarks> /// Usually the <see cref="Child"/> control is created automatically when /// <see cref="ApplyTemplate"/> is called; however for this to happen, the control needs to /// be attached to a logical tree (if the control is not attached to the logical tree, it /// is reasonable to expect that the DataTemplates needed for the child are not yet /// available). This method forces the <see cref="Child"/> control's creation at any point, /// and is particularly useful in unit tests. /// </remarks> public void UpdateChild() { var content = Content; var oldChild = Child; var newChild = CreateChild(); var logicalChildren = Host?.LogicalChildren ?? LogicalChildren; // Remove the old child if we're not recycling it. if (newChild != oldChild) { if (oldChild != null) { VisualChildren.Remove(oldChild); logicalChildren.Remove(oldChild); ((ISetInheritanceParent)oldChild).SetParent(oldChild.Parent); } } // Set the DataContext if the data isn't a control. if (!(content is IControl)) { DataContext = content; } else { ClearValue(DataContextProperty); } // Update the Child. if (newChild == null) { Child = null; } else if (newChild != oldChild) { ((ISetInheritanceParent)newChild).SetParent(this); Child = newChild; if (!logicalChildren.Contains(newChild)) { logicalChildren.Add(newChild); } VisualChildren.Add(newChild); } _createdChild = true; } /// <inheritdoc/> protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); _recyclingDataTemplate = null; _createdChild = false; InvalidateMeasure(); } /// <inheritdoc/> public override void Render(DrawingContext context) { _borderRenderer.Render(context, Bounds.Size, BorderThickness, CornerRadius, Background, BorderBrush, BoxShadow); } /// <summary> /// Creates the child control. /// </summary> /// <returns>The child control or null.</returns> protected virtual IControl? CreateChild() { var content = Content; var oldChild = Child; var newChild = content as IControl; // We want to allow creating Child from the Template, if Content is null. // But it's important to not use DataTemplates, otherwise we will break content presenters in many places, // otherwise it will blow up every ContentPresenter without Content set. if (newChild == null && (content != null || ContentTemplate != null)) { var dataTemplate = this.FindDataTemplate(content, ContentTemplate) ?? ( RecognizesAccessKey ? FuncDataTemplate.Access : FuncDataTemplate.Default ); if (dataTemplate is IRecyclingDataTemplate rdt) { var toRecycle = rdt == _recyclingDataTemplate ? oldChild : null; newChild = rdt.Build(content, toRecycle); _recyclingDataTemplate = rdt; } else { newChild = dataTemplate.Build(content); _recyclingDataTemplate = null; } } else { _recyclingDataTemplate = null; } return newChild; } /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { return LayoutHelper.MeasureChild(Child, availableSize, Padding, BorderThickness); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { return ArrangeOverrideImpl(finalSize, new Vector()); } internal Size ArrangeOverrideImpl(Size finalSize, Vector offset) { if (Child == null) return finalSize; var padding = Padding + BorderThickness; var horizontalContentAlignment = HorizontalContentAlignment; var verticalContentAlignment = VerticalContentAlignment; var useLayoutRounding = UseLayoutRounding; var availableSize = finalSize; var sizeForChild = availableSize; var scale = LayoutHelper.GetLayoutScale(this); var originX = offset.X; var originY = offset.Y; if (horizontalContentAlignment != HorizontalAlignment.Stretch) { sizeForChild = sizeForChild.WithWidth(Math.Min(sizeForChild.Width, DesiredSize.Width)); } if (verticalContentAlignment != VerticalAlignment.Stretch) { sizeForChild = sizeForChild.WithHeight(Math.Min(sizeForChild.Height, DesiredSize.Height)); } if (useLayoutRounding) { sizeForChild = LayoutHelper.RoundLayoutSize(sizeForChild, scale, scale); availableSize = LayoutHelper.RoundLayoutSize(availableSize, scale, scale); } switch (horizontalContentAlignment) { case HorizontalAlignment.Center: originX += (availableSize.Width - sizeForChild.Width) / 2; break; case HorizontalAlignment.Right: originX += availableSize.Width - sizeForChild.Width; break; } switch (verticalContentAlignment) { case VerticalAlignment.Center: originY += (availableSize.Height - sizeForChild.Height) / 2; break; case VerticalAlignment.Bottom: originY += availableSize.Height - sizeForChild.Height; break; } if (useLayoutRounding) { originX = LayoutHelper.RoundLayoutValue(originX, scale); originY = LayoutHelper.RoundLayoutValue(originY, scale); } var boundsForChild = new Rect(originX, originY, sizeForChild.Width, sizeForChild.Height).Deflate(padding); Child.Arrange(boundsForChild); return finalSize; } /// <summary> /// Called when the <see cref="Content"/> property changes. /// </summary> /// <param name="e">The event args.</param> private void ContentChanged(AvaloniaPropertyChangedEventArgs e) { _createdChild = false; if (((ILogical)this).IsAttachedToLogicalTree) { UpdateChild(); } else if (Child != null) { VisualChildren.Remove(Child); LogicalChildren.Remove(Child); ((ISetInheritanceParent)Child).SetParent(Child.Parent); Child = null; _recyclingDataTemplate = null; } UpdatePseudoClasses(); InvalidateMeasure(); } private void UpdatePseudoClasses() { PseudoClasses.Set(":empty", Content is null); } private void TemplatedParentChanged(AvaloniaPropertyChangedEventArgs e) { var host = e.NewValue as IContentPresenterHost; Host = host?.RegisterContentPresenter(this) == true ? host : null; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the AprCalendarioVacuna class. /// </summary> [Serializable] public partial class AprCalendarioVacunaCollection : ActiveList<AprCalendarioVacuna, AprCalendarioVacunaCollection> { public AprCalendarioVacunaCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>AprCalendarioVacunaCollection</returns> public AprCalendarioVacunaCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { AprCalendarioVacuna o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the APR_CalendarioVacuna table. /// </summary> [Serializable] public partial class AprCalendarioVacuna : ActiveRecord<AprCalendarioVacuna>, IActiveRecord { #region .ctors and Default Settings public AprCalendarioVacuna() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public AprCalendarioVacuna(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public AprCalendarioVacuna(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public AprCalendarioVacuna(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("APR_CalendarioVacuna", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdCalendarioVacuna = new TableSchema.TableColumn(schema); colvarIdCalendarioVacuna.ColumnName = "idCalendarioVacuna"; colvarIdCalendarioVacuna.DataType = DbType.Int32; colvarIdCalendarioVacuna.MaxLength = 0; colvarIdCalendarioVacuna.AutoIncrement = true; colvarIdCalendarioVacuna.IsNullable = false; colvarIdCalendarioVacuna.IsPrimaryKey = true; colvarIdCalendarioVacuna.IsForeignKey = false; colvarIdCalendarioVacuna.IsReadOnly = false; colvarIdCalendarioVacuna.DefaultSetting = @""; colvarIdCalendarioVacuna.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdCalendarioVacuna); TableSchema.TableColumn colvarIdVacuna = new TableSchema.TableColumn(schema); colvarIdVacuna.ColumnName = "idVacuna"; colvarIdVacuna.DataType = DbType.Int32; colvarIdVacuna.MaxLength = 0; colvarIdVacuna.AutoIncrement = false; colvarIdVacuna.IsNullable = false; colvarIdVacuna.IsPrimaryKey = false; colvarIdVacuna.IsForeignKey = true; colvarIdVacuna.IsReadOnly = false; colvarIdVacuna.DefaultSetting = @""; colvarIdVacuna.ForeignKeyTableName = "Sys_Medicamento"; schema.Columns.Add(colvarIdVacuna); TableSchema.TableColumn colvarNombreVacuna = new TableSchema.TableColumn(schema); colvarNombreVacuna.ColumnName = "NombreVacuna"; colvarNombreVacuna.DataType = DbType.AnsiString; colvarNombreVacuna.MaxLength = 50; colvarNombreVacuna.AutoIncrement = false; colvarNombreVacuna.IsNullable = false; colvarNombreVacuna.IsPrimaryKey = false; colvarNombreVacuna.IsForeignKey = false; colvarNombreVacuna.IsReadOnly = false; colvarNombreVacuna.DefaultSetting = @""; colvarNombreVacuna.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombreVacuna); TableSchema.TableColumn colvarIdNumeroDosis = new TableSchema.TableColumn(schema); colvarIdNumeroDosis.ColumnName = "idNumeroDosis"; colvarIdNumeroDosis.DataType = DbType.Int32; colvarIdNumeroDosis.MaxLength = 0; colvarIdNumeroDosis.AutoIncrement = false; colvarIdNumeroDosis.IsNullable = false; colvarIdNumeroDosis.IsPrimaryKey = false; colvarIdNumeroDosis.IsForeignKey = true; colvarIdNumeroDosis.IsReadOnly = false; colvarIdNumeroDosis.DefaultSetting = @""; colvarIdNumeroDosis.ForeignKeyTableName = "APR_NumeroDosis"; schema.Columns.Add(colvarIdNumeroDosis); TableSchema.TableColumn colvarEdadSemanas = new TableSchema.TableColumn(schema); colvarEdadSemanas.ColumnName = "EdadSemanas"; colvarEdadSemanas.DataType = DbType.Int32; colvarEdadSemanas.MaxLength = 0; colvarEdadSemanas.AutoIncrement = false; colvarEdadSemanas.IsNullable = false; colvarEdadSemanas.IsPrimaryKey = false; colvarEdadSemanas.IsForeignKey = false; colvarEdadSemanas.IsReadOnly = false; colvarEdadSemanas.DefaultSetting = @""; colvarEdadSemanas.ForeignKeyTableName = ""; schema.Columns.Add(colvarEdadSemanas); TableSchema.TableColumn colvarNombreEdad = new TableSchema.TableColumn(schema); colvarNombreEdad.ColumnName = "NombreEdad"; colvarNombreEdad.DataType = DbType.AnsiString; colvarNombreEdad.MaxLength = 50; colvarNombreEdad.AutoIncrement = false; colvarNombreEdad.IsNullable = false; colvarNombreEdad.IsPrimaryKey = false; colvarNombreEdad.IsForeignKey = false; colvarNombreEdad.IsReadOnly = false; colvarNombreEdad.DefaultSetting = @""; colvarNombreEdad.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombreEdad); TableSchema.TableColumn colvarObligatoria = new TableSchema.TableColumn(schema); colvarObligatoria.ColumnName = "Obligatoria"; colvarObligatoria.DataType = DbType.Boolean; colvarObligatoria.MaxLength = 0; colvarObligatoria.AutoIncrement = false; colvarObligatoria.IsNullable = false; colvarObligatoria.IsPrimaryKey = false; colvarObligatoria.IsForeignKey = false; colvarObligatoria.IsReadOnly = false; colvarObligatoria.DefaultSetting = @""; colvarObligatoria.ForeignKeyTableName = ""; schema.Columns.Add(colvarObligatoria); TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema); colvarCreatedBy.ColumnName = "CreatedBy"; colvarCreatedBy.DataType = DbType.AnsiString; colvarCreatedBy.MaxLength = 50; colvarCreatedBy.AutoIncrement = false; colvarCreatedBy.IsNullable = true; colvarCreatedBy.IsPrimaryKey = false; colvarCreatedBy.IsForeignKey = false; colvarCreatedBy.IsReadOnly = false; colvarCreatedBy.DefaultSetting = @""; colvarCreatedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedBy); TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema); colvarCreatedOn.ColumnName = "CreatedOn"; colvarCreatedOn.DataType = DbType.DateTime; colvarCreatedOn.MaxLength = 0; colvarCreatedOn.AutoIncrement = false; colvarCreatedOn.IsNullable = true; colvarCreatedOn.IsPrimaryKey = false; colvarCreatedOn.IsForeignKey = false; colvarCreatedOn.IsReadOnly = false; colvarCreatedOn.DefaultSetting = @""; colvarCreatedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedOn); TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema); colvarModifiedBy.ColumnName = "ModifiedBy"; colvarModifiedBy.DataType = DbType.AnsiString; colvarModifiedBy.MaxLength = 50; colvarModifiedBy.AutoIncrement = false; colvarModifiedBy.IsNullable = true; colvarModifiedBy.IsPrimaryKey = false; colvarModifiedBy.IsForeignKey = false; colvarModifiedBy.IsReadOnly = false; colvarModifiedBy.DefaultSetting = @""; colvarModifiedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedBy); TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema); colvarModifiedOn.ColumnName = "ModifiedOn"; colvarModifiedOn.DataType = DbType.DateTime; colvarModifiedOn.MaxLength = 0; colvarModifiedOn.AutoIncrement = false; colvarModifiedOn.IsNullable = true; colvarModifiedOn.IsPrimaryKey = false; colvarModifiedOn.IsForeignKey = false; colvarModifiedOn.IsReadOnly = false; colvarModifiedOn.DefaultSetting = @""; colvarModifiedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedOn); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("APR_CalendarioVacuna",schema); } } #endregion #region Props [XmlAttribute("IdCalendarioVacuna")] [Bindable(true)] public int IdCalendarioVacuna { get { return GetColumnValue<int>(Columns.IdCalendarioVacuna); } set { SetColumnValue(Columns.IdCalendarioVacuna, value); } } [XmlAttribute("IdVacuna")] [Bindable(true)] public int IdVacuna { get { return GetColumnValue<int>(Columns.IdVacuna); } set { SetColumnValue(Columns.IdVacuna, value); } } [XmlAttribute("NombreVacuna")] [Bindable(true)] public string NombreVacuna { get { return GetColumnValue<string>(Columns.NombreVacuna); } set { SetColumnValue(Columns.NombreVacuna, value); } } [XmlAttribute("IdNumeroDosis")] [Bindable(true)] public int IdNumeroDosis { get { return GetColumnValue<int>(Columns.IdNumeroDosis); } set { SetColumnValue(Columns.IdNumeroDosis, value); } } [XmlAttribute("EdadSemanas")] [Bindable(true)] public int EdadSemanas { get { return GetColumnValue<int>(Columns.EdadSemanas); } set { SetColumnValue(Columns.EdadSemanas, value); } } [XmlAttribute("NombreEdad")] [Bindable(true)] public string NombreEdad { get { return GetColumnValue<string>(Columns.NombreEdad); } set { SetColumnValue(Columns.NombreEdad, value); } } [XmlAttribute("Obligatoria")] [Bindable(true)] public bool Obligatoria { get { return GetColumnValue<bool>(Columns.Obligatoria); } set { SetColumnValue(Columns.Obligatoria, value); } } [XmlAttribute("CreatedBy")] [Bindable(true)] public string CreatedBy { get { return GetColumnValue<string>(Columns.CreatedBy); } set { SetColumnValue(Columns.CreatedBy, value); } } [XmlAttribute("CreatedOn")] [Bindable(true)] public DateTime? CreatedOn { get { return GetColumnValue<DateTime?>(Columns.CreatedOn); } set { SetColumnValue(Columns.CreatedOn, value); } } [XmlAttribute("ModifiedBy")] [Bindable(true)] public string ModifiedBy { get { return GetColumnValue<string>(Columns.ModifiedBy); } set { SetColumnValue(Columns.ModifiedBy, value); } } [XmlAttribute("ModifiedOn")] [Bindable(true)] public DateTime? ModifiedOn { get { return GetColumnValue<DateTime?>(Columns.ModifiedOn); } set { SetColumnValue(Columns.ModifiedOn, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a AprNumeroDosi ActiveRecord object related to this AprCalendarioVacuna /// /// </summary> public DalSic.AprNumeroDosi AprNumeroDosi { get { return DalSic.AprNumeroDosi.FetchByID(this.IdNumeroDosis); } set { SetColumnValue("idNumeroDosis", value.IdNumeroDosis); } } /// <summary> /// Returns a SysMedicamento ActiveRecord object related to this AprCalendarioVacuna /// /// </summary> public DalSic.SysMedicamento SysMedicamento { get { return DalSic.SysMedicamento.FetchByID(this.IdVacuna); } set { SetColumnValue("idVacuna", value.IdMedicamento); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdVacuna,string varNombreVacuna,int varIdNumeroDosis,int varEdadSemanas,string varNombreEdad,bool varObligatoria,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn) { AprCalendarioVacuna item = new AprCalendarioVacuna(); item.IdVacuna = varIdVacuna; item.NombreVacuna = varNombreVacuna; item.IdNumeroDosis = varIdNumeroDosis; item.EdadSemanas = varEdadSemanas; item.NombreEdad = varNombreEdad; item.Obligatoria = varObligatoria; item.CreatedBy = varCreatedBy; item.CreatedOn = varCreatedOn; item.ModifiedBy = varModifiedBy; item.ModifiedOn = varModifiedOn; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdCalendarioVacuna,int varIdVacuna,string varNombreVacuna,int varIdNumeroDosis,int varEdadSemanas,string varNombreEdad,bool varObligatoria,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn) { AprCalendarioVacuna item = new AprCalendarioVacuna(); item.IdCalendarioVacuna = varIdCalendarioVacuna; item.IdVacuna = varIdVacuna; item.NombreVacuna = varNombreVacuna; item.IdNumeroDosis = varIdNumeroDosis; item.EdadSemanas = varEdadSemanas; item.NombreEdad = varNombreEdad; item.Obligatoria = varObligatoria; item.CreatedBy = varCreatedBy; item.CreatedOn = varCreatedOn; item.ModifiedBy = varModifiedBy; item.ModifiedOn = varModifiedOn; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdCalendarioVacunaColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdVacunaColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn NombreVacunaColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn IdNumeroDosisColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn EdadSemanasColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn NombreEdadColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn ObligatoriaColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn CreatedByColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn CreatedOnColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn ModifiedByColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn ModifiedOnColumn { get { return Schema.Columns[10]; } } #endregion #region Columns Struct public struct Columns { public static string IdCalendarioVacuna = @"idCalendarioVacuna"; public static string IdVacuna = @"idVacuna"; public static string NombreVacuna = @"NombreVacuna"; public static string IdNumeroDosis = @"idNumeroDosis"; public static string EdadSemanas = @"EdadSemanas"; public static string NombreEdad = @"NombreEdad"; public static string Obligatoria = @"Obligatoria"; public static string CreatedBy = @"CreatedBy"; public static string CreatedOn = @"CreatedOn"; public static string ModifiedBy = @"ModifiedBy"; public static string ModifiedOn = @"ModifiedOn"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
namespace Demo { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.panel1 = new System.Windows.Forms.Panel(); this.checkBoxPOI = new System.Windows.Forms.CheckBox(); this.checkBoxMM = new System.Windows.Forms.CheckBox(); this.checkBoxFG = new System.Windows.Forms.CheckBox(); this.checkBoxBG = new System.Windows.Forms.CheckBox(); this.label1 = new System.Windows.Forms.Label(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.button1 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // pictureBox1 // this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.pictureBox1.Location = new System.Drawing.Point(0, 0); this.pictureBox1.Margin = new System.Windows.Forms.Padding(4); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(745, 523); this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // panel1 // this.panel1.Controls.Add(this.checkBoxPOI); this.panel1.Controls.Add(this.checkBoxMM); this.panel1.Controls.Add(this.checkBoxFG); this.panel1.Controls.Add(this.checkBoxBG); this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.comboBox1); this.panel1.Controls.Add(this.button1); this.panel1.Controls.Add(this.textBox1); this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel1.Location = new System.Drawing.Point(0, 523); this.panel1.Margin = new System.Windows.Forms.Padding(4); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(745, 95); this.panel1.TabIndex = 1; // // checkBoxPOI // this.checkBoxPOI.AutoSize = true; this.checkBoxPOI.Checked = true; this.checkBoxPOI.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBoxPOI.Location = new System.Drawing.Point(142, 52); this.checkBoxPOI.Name = "checkBoxPOI"; this.checkBoxPOI.Size = new System.Drawing.Size(60, 21); this.checkBoxPOI.TabIndex = 7; this.checkBoxPOI.Text = "POIs"; this.checkBoxPOI.UseVisualStyleBackColor = true; this.checkBoxPOI.CheckedChanged += new System.EventHandler(this.checkBoxPOI_CheckedChanged); // // checkBoxMM // this.checkBoxMM.AutoSize = true; this.checkBoxMM.Checked = true; this.checkBoxMM.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBoxMM.Location = new System.Drawing.Point(142, 25); this.checkBoxMM.Name = "checkBoxMM"; this.checkBoxMM.Size = new System.Drawing.Size(100, 21); this.checkBoxMM.TabIndex = 6; this.checkBoxMM.Text = "Map&Market"; this.checkBoxMM.UseVisualStyleBackColor = true; this.checkBoxMM.CheckedChanged += new System.EventHandler(this.ckechBoxMM_CheckedChanged); // // checkBoxFG // this.checkBoxFG.AutoSize = true; this.checkBoxFG.Checked = true; this.checkBoxFG.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBoxFG.Location = new System.Drawing.Point(19, 52); this.checkBoxFG.Name = "checkBoxFG"; this.checkBoxFG.Size = new System.Drawing.Size(104, 21); this.checkBoxFG.TabIndex = 5; this.checkBoxFG.Text = "Foreground"; this.checkBoxFG.UseVisualStyleBackColor = true; this.checkBoxFG.CheckedChanged += new System.EventHandler(this.checkBoxFG_CheckedChanged); // // checkBoxBG // this.checkBoxBG.AutoSize = true; this.checkBoxBG.Checked = true; this.checkBoxBG.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBoxBG.Location = new System.Drawing.Point(17, 25); this.checkBoxBG.Name = "checkBoxBG"; this.checkBoxBG.Size = new System.Drawing.Size(106, 21); this.checkBoxBG.TabIndex = 4; this.checkBoxBG.Text = "Background"; this.checkBoxBG.UseVisualStyleBackColor = true; this.checkBoxBG.CheckedChanged += new System.EventHandler(this.checkBoxBG_CheckedChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(264, 25); this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(65, 17); this.label1.TabIndex = 3; this.label1.Text = "MM Filter"; // // comboBox1 // this.comboBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.comboBox1.FormattingEnabled = true; this.comboBox1.Items.AddRange(new object[] { "GID = \'08212\'", "EW_W / EW_M > 1", "AUSL / EW > 0.1", "EW_QKM > 250"}); this.comboBox1.Location = new System.Drawing.Point(337, 39); this.comboBox1.Margin = new System.Windows.Forms.Padding(4); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(283, 24); this.comboBox1.TabIndex = 2; this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); // // button1 // this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button1.Location = new System.Drawing.Point(629, 20); this.button1.Margin = new System.Windows.Forms.Padding(4); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(100, 28); this.button1.TabIndex = 1; this.button1.Text = "Apply"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // textBox1 // this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox1.Location = new System.Drawing.Point(337, 20); this.textBox1.Margin = new System.Windows.Forms.Padding(4); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(283, 22); this.textBox1.TabIndex = 0; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(745, 618); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.panel1); this.Margin = new System.Windows.Forms.Padding(4); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.Resize += new System.EventHandler(this.Form1_Resize); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button1; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.CheckBox checkBoxPOI; private System.Windows.Forms.CheckBox checkBoxMM; private System.Windows.Forms.CheckBox checkBoxFG; private System.Windows.Forms.CheckBox checkBoxBG; } }
// Copyright 2013, 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. // Author: api.anash@gmail.com (Anash P. Oommen) // Author: Chris Seeley (https://github.com/Narwalter) using Google.Api.Ads.Common.Util; using Google.Api.Ads.Dfp.v201403; using System; using System.Collections.Generic; using System.Text; using DateTime = Google.Api.Ads.Dfp.v201403.DateTime; namespace Google.Api.Ads.Dfp.Util.v201403 { /// <summary> /// A utility class that allows for statements to be constructed in parts. /// Typical usage is: /// <code> /// StatementBuilder statementBuilder = new StatementBuilder() /// .Where("lastModifiedTime > :yesterday AND type = :type") /// .OrderBy("name DESC") /// .Limit(200) /// .Offset(20) /// .AddValue("yesterday", /// DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(-1))) /// .AddValue("type", "Type"); /// Statement statement = statementBuilder.ToStatement(); /// // ... /// statementBuilder.increaseOffsetBy(20); /// statement = statementBuilder.ToStatement(); /// </code> /// </summary> public class StatementBuilder { public const int SUGGESTED_PAGE_LIMIT = 500; private const string SELECT = "SELECT"; private const string FROM = "FROM"; private const string WHERE = "WHERE"; private const string LIMIT = "LIMIT"; private const string OFFSET = "OFFSET"; private const string ORDER_BY = "ORDER BY"; protected string query; protected string select; protected string from; protected string where; protected int? limit = null; protected int? offset = null; protected string orderBy; /// <summary> /// The list of query parameters. /// </summary> private List<String_ValueMapEntry> valueEntries; /// <summary> /// Constructs a statement builder for partial query building. /// </summary> public StatementBuilder() { valueEntries = new List<String_ValueMapEntry>(); } /// <summary> /// Constructs a statement builder with a complete query. /// </summary> /// <param name="query">The query string.</param> [Obsolete("Use partial query construction instead")] public StatementBuilder(string query) { this.query = query; valueEntries = new List<String_ValueMapEntry>(); } /// <summary> /// Gets or sets the statement query. /// </summary> [Obsolete("Use partial query construction instead")] public string Query { get { ValidateUsingCompleteQuery(); return query; } set { ValidateUsingCompleteQuery(); query = value; } } /// <summary> /// Removes a keyword from the start of a clause, if it exists. /// </summary> /// <param name="clause">The clause to remove the keyword from</param> /// <param name="keyword">The keyword to remove</param> /// <returns>The clause with the keyword removed</returns> private static string RemoveKeyword(string clause, string keyword) { string formattedKeyword = keyword.Trim() + " "; return clause.StartsWith(formattedKeyword, true, null) ? clause.Substring(formattedKeyword.Length) : clause; } private void ValidateUsingCompleteQuery() { if (PartialQueryExists()) { throw new InvalidOperationException(DfpErrorMessages.PartialQuerySet); } } private bool PartialQueryExists() { return select != null || from != null || where != null || limit != null || offset != null || orderBy != null; } private void ValidateUsingPartialQuery() { if (!String.IsNullOrEmpty(query)) { throw new InvalidOperationException(DfpErrorMessages.CompleteQuerySet); } } /// <summary> /// Sets the statement SELECT clause in the form of "a,b". /// Only necessary for statements being sent to the /// <see cref="PublisherQueryLanguageService"/>. /// The "SELECT " keyword will be ignored. /// </summary> /// <param name="columns"> /// The statement serlect clause without "SELECT". /// </param> /// <returns>The statement builder, for chaining method calls.</returns> public StatementBuilder Select(String columns) { PreconditionUtilities.CheckArgumentNotNull(columns, "columns"); ValidateUsingPartialQuery(); this.select = RemoveKeyword(columns, SELECT); return this; } /// <summary> /// Sets the statement FROM clause in the form of "table". /// Only necessary for statements being sent to the /// <see cref="PublisherQueryLanguageService"/>. /// The "FROM " keyword will be ignored. /// </summary> /// <param name="table">The statement from clause without "FROM"</param> /// <returns>The statement builder, for chaining method calls.</returns> public StatementBuilder From(String table) { PreconditionUtilities.CheckArgumentNotNull(table, "table"); ValidateUsingPartialQuery(); this.from = RemoveKeyword(table, FROM); return this; } /// <summary> /// Sets the statement WHERE clause in the form of /// <code> /// "WHERE &lt;condition&gt; {[AND | OR] &lt;condition&gt; ...}" /// </code> /// e.g. "a = b OR b = c". The "WHERE " keyword will be ignored. /// </summary> /// <param name="conditions">The statement query without "WHERE"</param> /// <returns>The statement builder, for chaining method calls.</returns> public StatementBuilder Where(String conditions) { PreconditionUtilities.CheckArgumentNotNull(conditions, "conditions"); ValidateUsingPartialQuery(); this.where = RemoveKeyword(conditions, WHERE); return this; } /// <summary> /// Sets the statement LIMIT clause in the form of /// <code>"LIMIT &lt;count&gt;"</code> /// </summary> /// <param name="count">the statement limit</param> /// <returns>The statement builder, for chaining method calls.</returns> public StatementBuilder Limit(Int32 count) { ValidateUsingPartialQuery(); this.limit = count; return this; } /// <summary> /// Sets the statement OFFSET clause in the form of /// <code>"OFFSET &lt;count&gt;"</code> /// </summary> /// <param name="count">the statement offset</param> /// <returns>The statement builder, for chaining method calls.</returns> public StatementBuilder Offset(Int32 count) { ValidateUsingPartialQuery(); this.offset = count; return this; } /// <summary> /// Increases the offset by the given amount. /// </summary> /// <param name="amount">the amount to increase the offset</param> /// <returns>The statement builder, for chaining method calls.</returns> public StatementBuilder IncreaseOffsetBy(Int32 amount) { ValidateUsingPartialQuery(); if (this.offset == null) { this.offset = 0; } this.offset += amount; return this; } /// <summary> /// Gets the curent offset /// </summary> /// <returns>The current offset</returns> public int? GetOffset() { ValidateUsingPartialQuery(); return this.offset; } /// <summary> /// Removes the limit and offset from the query. /// </summary> /// <returns>The statement builder, for chaining method calls.</returns> public StatementBuilder RemoveLimitAndOffset() { ValidateUsingPartialQuery(); this.offset = null; this.limit = null; return this; } /// <summary> /// Sets the statement ORDER BY clause in the form of /// <code>"ORDER BY &lt;property&gt; [ASC | DESC]"</code> /// e.g. "type ASC, lastModifiedDateTime DESC". /// The "ORDER BY " keyword will be ignored. /// </summary> /// <param name="orderBy">the statement order by without "ORDER BY"</param> /// <returns>The statement builder, for chaining method calls.</returns> public StatementBuilder OrderBy(String orderBy) { PreconditionUtilities.CheckArgumentNotNull(orderBy, "orderBy"); this.orderBy = RemoveKeyword(orderBy, ORDER_BY); return this; } /// <summary> /// Adds a new string value to the list of query parameters. /// </summary> /// <param name="key">The parameter name.</param> /// <param name="value">The parameter value.</param> /// <returns>The statement builder, for chaining method calls.</returns> public StatementBuilder AddValue(string key, string value) { TextValue queryValue = new TextValue(); queryValue.value = value; return AddValue(key, queryValue); } /// <summary> /// Adds a new boolean value to the list of query parameters. /// </summary> /// <param name="key">The parameter name.</param> /// <param name="value">The parameter value.</param> /// <returns>The statement builder, for chaining method calls.</returns> public StatementBuilder AddValue(string key, bool value) { BooleanValue queryValue = new BooleanValue(); queryValue.value = value; return AddValue(key, queryValue); } /// <summary> /// Adds a new decimal value to the list of query parameters. /// </summary> /// <param name="key">The parameter name.</param> /// <param name="value">The parameter value.</param> /// <returns>The statement builder, for chaining method calls.</returns> public StatementBuilder AddValue(string key, decimal value) { NumberValue queryValue = new NumberValue(); queryValue.value = value.ToString(); return AddValue(key, queryValue); } /// <summary> /// Adds a new DateTime value to the list of query parameters. /// </summary> /// <param name="key">The parameter name.</param> /// <param name="value">The parameter value.</param> /// <returns>The statement builder, for chaining method calls.</returns> public StatementBuilder AddValue(string key, DateTime value) { DateTimeValue queryValue = new DateTimeValue(); queryValue.value = value; return AddValue(key, queryValue); } /// <summary> /// Adds a new Date value to the list of query parameters. /// </summary> /// <param name="key">The parameter name.</param> /// <param name="value">The parameter value.</param> /// <returns>The statement builder, for chaining method calls.</returns> public StatementBuilder AddValue(string key, Date value) { DateValue queryValue = new DateValue(); queryValue.value = value; return AddValue(key, queryValue); } /// <summary> /// Adds a new value to the list of query parameters. /// </summary> /// <param name="key">The parameter name.</param> /// <param name="value">The parameter value.</param> /// <returns>The statement builder, for chaining method calls.</returns> private StatementBuilder AddValue(string key, Value value) { String_ValueMapEntry queryValue = new String_ValueMapEntry(); queryValue.key = key; queryValue.value = value; valueEntries.Add(queryValue); return this; } private void ValidateQuery() { if (limit == null && offset != null) { throw new InvalidOperationException( DfpErrorMessages.InvalidOffsetAndLimit); } } private String BuildQuery() { ValidateQuery(); StringBuilder stringBuilder = new StringBuilder(); if (!String.IsNullOrEmpty(select)) { stringBuilder = stringBuilder.Append(SELECT).Append(" ") .Append(select).Append(" "); } if (!String.IsNullOrEmpty(from)) { stringBuilder = stringBuilder.Append(FROM).Append(" ") .Append(from).Append(" "); } if (!String.IsNullOrEmpty(where)) { stringBuilder = stringBuilder.Append(WHERE).Append(" ") .Append(where).Append(" "); } if (!String.IsNullOrEmpty(orderBy)) { stringBuilder = stringBuilder.Append(ORDER_BY).Append(" ") .Append(orderBy).Append(" "); } if (limit != null) { stringBuilder = stringBuilder.Append(LIMIT).Append(" ") .Append(limit).Append(" "); } if (offset != null) { stringBuilder = stringBuilder.Append(OFFSET).Append(" ") .Append(offset).Append(" "); } return stringBuilder.ToString().Trim(); } /// <summary> /// Gets the <see cref="Statement"/> representing the state of this /// statement builder. /// </summary> /// <returns>The statement.</returns> public Statement ToStatement() { Statement statement = new Statement(); statement.query = !String.IsNullOrEmpty(query) ? query : BuildQuery(); statement.values = valueEntries.ToArray(); return statement; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using ALinq.Mapping; using ALinq.SqlClient; namespace ALinq.SqlClient { internal interface ISqlParameterizer { ReadOnlyCollection<SqlParameterInfo> Parameterize(SqlNode node); ReadOnlyCollection<ReadOnlyCollection<SqlParameterInfo>> ParameterizeBlock(SqlBlock sqlBlock); ITypeSystemProvider TypeProvider { get; } SqlNodeAnnotations Annotations { get; } } internal class SqlParameterizer : ISqlParameterizer { // Fields private readonly SqlNodeAnnotations annotations; internal readonly ITypeSystemProvider typeProvider; // Methods internal SqlParameterizer(ITypeSystemProvider typeProvider, SqlNodeAnnotations annotations) { this.typeProvider = typeProvider; this.annotations = annotations; } ReadOnlyCollection<SqlParameterInfo> ISqlParameterizer.Parameterize(SqlNode node) { return ParameterizeInternal(node).AsReadOnly(); } ReadOnlyCollection<ReadOnlyCollection<SqlParameterInfo>> ISqlParameterizer.ParameterizeBlock(SqlBlock block) { var item = new SqlParameterInfo(new SqlParameter(typeof(int), typeProvider.From(typeof(int)), "@ROWCOUNT", block.SourceExpression)); var list = new List<ReadOnlyCollection<SqlParameterInfo>>(); int num = 0; int count = block.Statements.Count; while (num < count) { SqlNode node = block.Statements[num]; List<SqlParameterInfo> list2 = this.ParameterizeInternal(node); if (num > 0) { list2.Add(item); } list.Add(list2.AsReadOnly()); num++; } return list.AsReadOnly(); } public ITypeSystemProvider TypeProvider { get { return this.typeProvider; } } public SqlNodeAnnotations Annotations { get { return this.annotations; } } private List<SqlParameterInfo> ParameterizeInternal(SqlNode node) { var visitor = new Visitor(this); visitor.Visit(node); return new List<SqlParameterInfo>(visitor.currentParams); } // Nested Types internal class Visitor : SqlVisitor { // Fields internal readonly List<SqlParameterInfo> currentParams; internal readonly Dictionary<object, SqlParameterInfo> map; internal readonly ISqlParameterizer parameterizer; internal bool topLevel; private int index; // Methods internal Visitor(ISqlParameterizer parameterizer) { this.parameterizer = parameterizer; this.topLevel = true; this.map = new Dictionary<object, SqlParameterInfo>(); this.currentParams = new List<SqlParameterInfo>(); } internal virtual string CreateParameterName() { return ("@p" + index++); } internal static ParameterDirection GetParameterDirection(MetaParameter p) { if (p.Parameter.IsRetval) { return ParameterDirection.ReturnValue; } if (p.Parameter.IsOut) { return ParameterDirection.Output; } if (p.Parameter.ParameterType.IsByRef) { return ParameterDirection.InputOutput; } return ParameterDirection.Input; } internal virtual SqlParameter InsertLookup(SqlValue cp) { SqlParameterInfo info; if (!map.TryGetValue(cp, out info)) { var parameter = new SqlParameter(cp.ClrType, cp.SqlType, CreateParameterName(), cp.SourceExpression); info = new SqlParameterInfo(parameter, cp.Value); map.Add(cp, info); currentParams.Add(info); } return info.Parameter; } internal bool RetypeOutParameter(SqlParameter node) { if (node.SqlType.IsLargeType) { IProviderType bestLargeType = this.parameterizer.TypeProvider.GetBestLargeType(node.SqlType); if (node.SqlType != bestLargeType) { node.SetSqlType(bestLargeType); return true; } this.parameterizer.Annotations.Add(node, new SqlServerCompatibilityAnnotation(Strings.MaxSizeNotSupported(node.SourceExpression), new[] { SqlProvider.ProviderMode.Sql2000 })); } return false; } internal override SqlExpression VisitBinaryOperator(SqlBinary bo) { base.VisitBinaryOperator(bo); return bo; } internal override SqlExpression VisitClientParameter(SqlClientParameter cp) { if (cp.SqlType.CanBeParameter) { var parameter = new SqlParameter(cp.ClrType, cp.SqlType, CreateParameterName(), cp.SourceExpression); currentParams.Add(new SqlParameterInfo(parameter, cp.Accessor.Compile())); return parameter; } return cp; } internal override SqlStatement VisitDelete(SqlDelete sd) { bool topLevel = this.topLevel; this.topLevel = false; base.VisitDelete(sd); this.topLevel = topLevel; return sd; } internal override SqlStatement VisitInsert(SqlInsert sin) { bool topLevel = this.topLevel; this.topLevel = false; base.VisitInsert(sin); this.topLevel = topLevel; return sin; } internal SqlExpression VisitParameter(SqlExpression expr) { SqlExpression expression = VisitExpression(expr); SqlNodeType nodeType = expression.NodeType; if (nodeType != SqlNodeType.Parameter) { return nodeType == SqlNodeType.Value ? InsertLookup((SqlValue)expression) : expression; } return expression; } internal override SqlSelect VisitSelect(SqlSelect select) { bool topLevel = this.topLevel; this.topLevel = false; select.From = (SqlSource)Visit(select.From); select.Where = VisitExpression(select.Where); int num = 0; int count = select.GroupBy.Count; while (num < count) { select.GroupBy[num] = VisitExpression(select.GroupBy[num]); num++; } select.Having = this.VisitExpression(select.Having); int num3 = 0; int num4 = select.OrderBy.Count; while (num3 < num4) { select.OrderBy[num3].Expression = this.VisitExpression(select.OrderBy[num3].Expression); num3++; } select.Top = this.VisitExpression(select.Top); select.Row = (SqlRow)this.Visit(select.Row); this.topLevel = topLevel; select.Selection = this.VisitExpression(select.Selection); return select; } internal override SqlStoredProcedureCall VisitStoredProcedureCall(SqlStoredProcedureCall spc) { var returnType = spc.Function.Method.ReturnType; if (returnType != typeof(void)) { var parameter3 = new SqlParameter(returnType, parameterizer.TypeProvider.From(returnType), "@RETURN_VALUE", spc.SourceExpression) { Direction = ParameterDirection.Output }; this.currentParams.Add(new SqlParameterInfo(parameter3)); } this.VisitUserQuery(spc); int num = 0; int count = spc.Function.Parameters.Count; while (num < count) { MetaParameter p = spc.Function.Parameters[num]; var node = spc.Arguments[num] as SqlParameter; if (node != null) { node.Direction = GetParameterDirection(p); node.Name = p.MappedName.StartsWith("@") ? p.MappedName : "@" + p.MappedName; if ((node.Direction == ParameterDirection.InputOutput) || (node.Direction == ParameterDirection.Output)) { RetypeOutParameter(node); } } num++; } //var parameter3 = new SqlParameter(typeof(int?), // parameterizer.TypeProvider.From(typeof(int)), // "@RETURN_VALUE", spc.SourceExpression) { Direction = ParameterDirection.Output }; //currentParams.Add(new SqlParameterInfo(parameter3)); return spc; } internal override SqlStatement VisitUpdate(SqlUpdate sup) { bool topLevel = this.topLevel; this.topLevel = false; base.VisitUpdate(sup); this.topLevel = topLevel; return sup; } internal override SqlUserQuery VisitUserQuery(SqlUserQuery suq) { bool topLevel = this.topLevel; this.topLevel = false; int num = 0; int count = suq.Arguments.Count; while (num < count) { suq.Arguments[num] = this.VisitParameter(suq.Arguments[num]); num++; } this.topLevel = topLevel; suq.Projection = this.VisitExpression(suq.Projection); return suq; } internal override SqlExpression VisitValue(SqlValue value) { if ((!this.topLevel && value.IsClientSpecified) && value.SqlType.CanBeParameter) { return InsertLookup(value); } return value; } } } }
// Generated by TinyPG v1.2 available at www.codeproject.com using System; using System.Collections.Generic; using System.Text; namespace Rawr.Mage.StateDescription { #region ParseTree public class ParseErrors : List<ParseError> { } public class ParseError { private string message; private int code; private int line; private int col; private int pos; private int length; public int Code { get { return code; } } public int Line { get { return line; } } public int Column { get { return col; } } public int Position { get { return pos; } } public int Length { get { return length; } } public string Message { get { return message; } } public ParseError(string message, int code, ParseNode node) : this(message, code, 0, node.Token.StartPos, node.Token.StartPos, node.Token.Length) { } public ParseError(string message, int code, int line, int col, int pos, int length) { this.message = message; this.code = code; this.line = line; this.col = col; this.pos = pos; this.length = length; } } public delegate bool StateDescriptionDelegate(int effects); // rootlevel of the node tree public partial class ParseTree : ParseNode { public ParseErrors Errors; public List<Token> Skipped; public ParseTree() : base(new Token(), "ParseTree") { Token.Type = TokenType.Start; Token.Text = "Root"; Skipped = new List<Token>(); Errors = new ParseErrors(); } public string PrintTree() { StringBuilder sb = new StringBuilder(); int indent = 0; PrintNode(sb, this, indent); return sb.ToString(); } private void PrintNode(StringBuilder sb, ParseNode node, int indent) { string space = "".PadLeft(indent, ' '); sb.Append(space); sb.AppendLine(node.Text); foreach (ParseNode n in node.Nodes) PrintNode(sb, n, indent + 2); } /// <summary> /// this is the entry point for executing and evaluating the parse tree. /// </summary> /// <param name="paramlist">additional optional input parameters</param> /// <returns>the output of the evaluation function</returns> public StateDescriptionDelegate Compile() { return Nodes[0].Compile(this); } public bool Interpret(int effects) { return Nodes[0].Interpret(this, effects); } } public partial class ParseNode { protected string text; protected List<ParseNode> nodes; public List<ParseNode> Nodes { get {return nodes;} } public ParseNode Parent; public Token Token; // the token/rule public string Text { // text to display in parse tree get { return text;} set { text = value; } } public virtual ParseNode CreateNode(Token token, string text) { ParseNode node = new ParseNode(token, text); node.Parent = this; return node; } protected ParseNode(Token token, string text) { this.Token = token; this.text = text; this.nodes = new List<ParseNode>(); } internal StateDescriptionDelegate Compile(ParseTree tree) { StateDescriptionDelegate Value = null; switch (Token.Type) { case TokenType.Start: Value = EvalStart(tree); break; case TokenType.UnionExpr: Value = EvalUnionExpr(tree); break; case TokenType.DiffExpr: Value = EvalDiffExpr(tree); break; case TokenType.IntExpr: Value = EvalIntExpr(tree); break; case TokenType.CompExpr: Value = EvalCompExpr(tree); break; case TokenType.Atom: Value = EvalAtom(tree); break; default: Value = delegate { return true; }; break; } return Value; } internal bool Interpret(ParseTree tree, int effects) { bool Value = true; switch (Token.Type) { case TokenType.Start: Value = EvalStart(tree, effects); break; case TokenType.UnionExpr: Value = EvalUnionExpr(tree, effects); break; case TokenType.DiffExpr: Value = EvalDiffExpr(tree, effects); break; case TokenType.IntExpr: Value = EvalIntExpr(tree, effects); break; case TokenType.CompExpr: Value = EvalCompExpr(tree, effects); break; case TokenType.Atom: Value = EvalAtom(tree, effects); break; default: Value = true; break; } return Value; } protected virtual bool EvalStart(ParseTree tree, int effects) { foreach (ParseNode node in nodes) { if (node.Token.Type == TokenType.UnionExpr) { return node.Interpret(tree, effects); } } return true; } protected virtual bool EvalUnionExpr(ParseTree tree, int effects) { foreach (ParseNode node in nodes) { if (node.Token.Type == TokenType.DiffExpr) { bool value = node.Interpret(tree, effects); if (value) return true; } } return false; } protected virtual bool EvalDiffExpr(ParseTree tree, int effects) { int i = 0; for (; i < nodes.Count; i++) { ParseNode node = nodes[i]; if (node.Token.Type == TokenType.IntExpr) { bool value = node.Interpret(tree, effects); if (!value) return false; i++; break; } } for (; i < nodes.Count; i++) { ParseNode node = nodes[i]; if (node.Token.Type == TokenType.IntExpr) { return !node.Interpret(tree, effects); } } return true; } protected virtual bool EvalIntExpr(ParseTree tree, int effects) { foreach (ParseNode node in nodes) { if (node.Token.Type == TokenType.CompExpr) { bool value = node.Interpret(tree, effects); if (!value) return false; } } return true; } protected virtual bool EvalCompExpr(ParseTree tree, int effects) { bool complement = false; for (int i = 0; i < nodes.Count; i++) { ParseNode node = nodes[i]; if (node.Token.Type == TokenType.COMPLEMENT) { complement = true; } else if (node.Token.Type == TokenType.Atom) { return node.Interpret(tree, effects) ^ complement; } } return true; } private int EvalState(ParseNode node) { string text = node.Token.Text.Replace(" ", ""); if (text.ToUpper() == "ANY") { return 0; } else { return (int)Enum.Parse(typeof(StandardEffect), text, true); } } protected virtual bool EvalAtom(ParseTree tree, int effects) { foreach (ParseNode node in nodes) { if (node.Token.Type == TokenType.UnionExpr) { return node.Interpret(tree, effects); } else if (node.Token.Type == TokenType.STATE) { int stateEffects = EvalState(node); return (effects & stateEffects) == stateEffects; } } return true; } protected virtual StateDescriptionDelegate EvalStart(ParseTree tree) { foreach (ParseNode node in nodes) { if (node.Token.Type == TokenType.UnionExpr) { return node.Compile(tree); } } return delegate { return true; }; } protected virtual StateDescriptionDelegate EvalUnionExpr(ParseTree tree) { List<StateDescriptionDelegate> nodelist = new List<StateDescriptionDelegate>(); foreach (ParseNode node in nodes) { if (node.Token.Type == TokenType.DiffExpr) { nodelist.Add(node.Compile(tree)); } } StateDescriptionDelegate[] list = nodelist.ToArray(); if (list.Length == 1) return list[0]; return delegate(int effects) { for (int i = 0; i < list.Length; i++) { if (list[i](effects)) return true; } return false; }; } protected virtual StateDescriptionDelegate EvalDiffExpr(ParseTree tree) { StateDescriptionDelegate a = null; StateDescriptionDelegate b = null; int i = 0; for (; i < nodes.Count; i++) { ParseNode node = nodes[i]; if (node.Token.Type == TokenType.IntExpr) { a = node.Compile(tree); i++; break; } } for (; i < nodes.Count; i++) { ParseNode node = nodes[i]; if (node.Token.Type == TokenType.IntExpr) { b = node.Compile(tree); break; } } if (b != null) { return delegate(int effects) { return a(effects) && !b(effects); }; } else { return a; } } protected virtual StateDescriptionDelegate EvalIntExpr(ParseTree tree) { bool allAtom = true; List<StateDescriptionDelegate> nodelist = new List<StateDescriptionDelegate>(); int stateEffects = 0; foreach (ParseNode node in nodes) { if (node.Token.Type == TokenType.CompExpr) { if (node.nodes[0].Token.Type == TokenType.Atom && node.nodes[0].nodes[0].Token.Type == TokenType.STATE) { stateEffects = stateEffects | EvalState(node.nodes[0].nodes[0]); } else { allAtom = false; } nodelist.Add(node.Compile(tree)); } } if (allAtom) { return delegate(int effects) { return (effects & stateEffects) == stateEffects; }; } else { StateDescriptionDelegate[] list = nodelist.ToArray(); if (list.Length == 1) return list[0]; return delegate(int effects) { for (int i = 0; i < list.Length; i++) { if (!list[i](effects)) return false; } return true; }; } } protected virtual StateDescriptionDelegate EvalCompExpr(ParseTree tree) { bool complement = false; for (int i = 0; i < nodes.Count; i++) { ParseNode node = nodes[i]; if (node.Token.Type == TokenType.COMPLEMENT) { complement = true; } else if (node.Token.Type == TokenType.Atom) { StateDescriptionDelegate value = node.Compile(tree); if (complement) { return delegate(int effects) { return !value(effects); }; } else { return value; } } } return null; } protected virtual StateDescriptionDelegate EvalAtom(ParseTree tree) { foreach (ParseNode node in nodes) { if (node.Token.Type == TokenType.UnionExpr) { return node.Compile(tree); } else if (node.Token.Type == TokenType.STATE) { int stateEffects = EvalState(node); return delegate(int effects) { return (effects & stateEffects) == stateEffects; }; } } return null; } } #endregion ParseTree }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace XmlDocMarkdown.Core { /// <summary> /// Helps process command-line arguments. /// </summary> /// <remarks>To use this class, construct an <c>ArgsReader</c> with the command-line arguments from <c>Main</c>, /// read the supported options one at a time with <see cref="ReadFlag" /> and <see cref="ReadOption"/>, /// read any normal arguments with <see cref="ReadArgument"/>, and finally call <see cref="VerifyComplete"/>, /// which throws an <see cref="ArgsReaderException"/> if any unsupported options or arguments haven't been read.</remarks> internal sealed class ArgsReader { /// <summary> /// Creates a reader for the specified command-line arguments. /// </summary> /// <param name="args">The command-line arguments from <c>Main</c>.</param> /// <exception cref="ArgumentNullException"><c>args</c> is <c>null</c>.</exception> public ArgsReader(IEnumerable<string> args) { m_args = (args ?? throw new ArgumentNullException(nameof(args))).ToList(); } /// <summary> /// True if short options (e.g. <c>-h</c>) should ignore case. (Default false.) /// </summary> public bool ShortOptionIgnoreCase { get; set; } /// <summary> /// True if long options (e.g. <c>--help</c>) should ignore case. (Default false.) /// </summary> public bool LongOptionIgnoreCase { get; set; } /// <summary> /// True if long options (e.g. <c>--dry-run</c>) should ignore "kebab case", i.e. allow <c>--dryrun</c>. (Default false.) /// </summary> public bool LongOptionIgnoreKebabCase { get; set; } /// <summary> /// True if <c>--</c> is ignored and all following arguments are not read as options. (Default false.) /// </summary> public bool NoOptionsAfterDoubleDash { get; set; } /// <summary> /// Reads the specified flag, returning true if it is found. /// </summary> /// <param name="name">The name of the specified flag.</param> /// <returns>True if the specified flag was found on the command line.</returns> /// <remarks><para>If the flag is found, the method returns <c>true</c> and the flag is /// removed. If <c>ReadFlag</c> is called again with the same name, it will return <c>false</c>, /// unless the same flag appears twice on the command line.</para> /// <para>To support multiple names for the same flag, use a <c>|</c> to separate them, /// e.g. use <c>help|h|?</c> to support three different names for a help flag.</para> /// <para>Single-character names use a single hyphen, e.g. <c>-h</c>. Longer names /// use a double hyphen, e.g. <c>--help</c>.</para></remarks> /// <exception cref="ArgumentNullException"><c>name</c> is <c>null</c>.</exception> /// <exception cref="ArgumentException">One of the names is empty.</exception> public bool ReadFlag(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException("Flag name must not be empty.", nameof(name)); var names = name.Split('|'); if (names.Length > 1) return names.Any(ReadFlag); var index = FindOptionArgumentIndex(name); if (index == -1) return false; m_args.RemoveAt(index); return true; } /// <summary> /// Reads the value of the specified option, if any. /// </summary> /// <param name="name">The name of the specified option.</param> /// <returns>The specified option if it was found on the command line; <c>null</c> otherwise.</returns> /// <remarks><para>If the option is found, the method returns the command-line argument /// after the option and both arguments are removed. If <c>ReadOption</c> is called again with the /// same name, it will return <c>null</c>, unless the same option appears twice on the command line.</para> /// <para>To support multiple names for the same option, use a vertical bar (<c>|</c>) to separate them, /// e.g. use <c>n|name</c> to support two different names for a module option.</para> /// <para>Single-character names use a single hyphen, e.g. <c>-n example</c>. Longer names use a /// double hyphen, e.g. <c>--name example</c>.</para></remarks> /// <exception cref="ArgumentNullException"><c>name</c> is <c>null</c>.</exception> /// <exception cref="ArgumentException">One of the names is empty.</exception> /// <exception cref="ArgsReaderException">The argument that must follow the option is missing.</exception> public string? ReadOption(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException("Option name must not be empty.", nameof(name)); var names = name.Split('|'); if (names.Length > 1) return names.Select(ReadOption).FirstOrDefault(x => x != null); var index = FindOptionArgumentIndex(name); if (index == -1) return null; var value = index + 1 < m_args.Count ? m_args[index + 1] : null; if (value == null || IsOption(value)) throw new ArgsReaderException($"Missing value after '{RenderOption(name)}'."); m_args.RemoveAt(index); m_args.RemoveAt(index); return value; } /// <summary> /// Reads the next non-option argument. /// </summary> /// <returns>The next non-option argument, or null if none remain.</returns> /// <remarks><para>If the next argument is an option, this method throws an exception. /// If options can appear before normal arguments, be sure to read all options before reading /// any normal arguments.</para></remarks> /// <exception cref="ArgsReaderException">The next argument is an option.</exception> public string? ReadArgument() { if (m_args.Count == 0) return null; var value = m_args[0]; if (NoOptionsAfterDoubleDash && value == "--") { m_args.RemoveAt(0); m_noMoreOptions = true; return ReadArgument(); } if (!m_noMoreOptions && IsOption(value)) throw new ArgsReaderException($"Unexpected option '{value}'."); m_args.RemoveAt(0); return value; } /// <summary> /// Reads any remaining non-option arguments. /// </summary> /// <returns>The remaining non-option arguments, if any.</returns> /// <remarks><para>If any remaining arguments are options, this method throws an exception. /// If options can appear before normal arguments, be sure to read all options before reading /// any normal arguments.</para></remarks> /// <exception cref="ArgsReaderException">A remaining argument is an option.</exception> public IReadOnlyList<string> ReadArguments() { var arguments = new List<string>(); while (true) { var argument = ReadArgument(); if (argument == null) return arguments; arguments.Add(argument); } } /// <summary> /// Confirms that all arguments were processed. /// </summary> /// <exception cref="ArgsReaderException">A command-line argument was not read.</exception> public void VerifyComplete() { if (m_args.Count != 0) throw new ArgsReaderException($"Unexpected {(IsOption(m_args[0]) ? "option" : "argument")} '{m_args[0]}'."); } private static bool IsOption(string value) => value.Length >= 2 && value[0] == '-' && value != "--"; private static string RenderOption(string name) => name.Length == 1 ? $"-{name}" : $"--{name}"; private bool IsOptionArgument(string optionName, string argument) { var renderedOption = RenderOption(optionName); if (optionName.Length == 1) { return string.Equals(argument, renderedOption, ShortOptionIgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } else { if (LongOptionIgnoreKebabCase) { argument = Regex.Replace(argument, @"\b-\b", ""); renderedOption = Regex.Replace(renderedOption, @"\b-\b", ""); } return string.Equals(argument, renderedOption, LongOptionIgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } } private int FindOptionArgumentIndex(string optionName) { for (var index = 0; index < m_args.Count; index++) { var arg = m_args[index]; if (NoOptionsAfterDoubleDash && arg == "--") break; if (IsOptionArgument(optionName, arg)) return index; } return -1; } private readonly List<string> m_args; private bool m_noMoreOptions; } }
// 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.Concurrent; using System.Runtime.Serialization; using System.Xml; namespace SerializationTestTypes { [Serializable] public class PrimitiveTypeResolver : DataContractResolver { private readonly static string s_defaultNS = "http://www.default.com"; private readonly static ConcurrentDictionary<string, Type> s_types = new ConcurrentDictionary<string, Type>(); public override bool TryResolveType(Type dcType, Type declaredType, DataContractResolver KTResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { string resolvedTypeName = string.Empty; string resolvedNamespace = string.Empty; resolvedNamespace = s_defaultNS; resolvedTypeName = dcType.Name + "_foo"; s_types[resolvedTypeName] = dcType; XmlDictionary dic = new XmlDictionary(); typeName = dic.Add(resolvedTypeName); typeNamespace = dic.Add(resolvedNamespace); return true; } public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver KTResolver) { return s_types[typeName]; } } public class EmptyNamespaceResolver : DataContractResolver { public override bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { XmlDictionary dic = new XmlDictionary(); if (dataContractType == typeof(EmptyNsContainer)) { typeName = dic.Add("EmptyNsContainer"); typeNamespace = dic.Add("MyNamespace"); return true; } else if (dataContractType == typeof(UknownEmptyNSAddress)) { typeName = dic.Add("AddressFoo"); typeNamespace = dic.Add(""); return true; } else { return knownTypeResolver.TryResolveType(dataContractType, declaredType, null, out typeName, out typeNamespace); } } public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver) { if (typeNamespace == "MyNamespace") { switch (typeName) { case "EmptyNsContainer": return typeof(EmptyNsContainer); } } else if (typeName.Equals("AddressFoo")) { return typeof(UknownEmptyNSAddress); } return knownTypeResolver.ResolveName(typeName, typeNamespace, declaredType, null); } } [Serializable] public class ProxyDataContractResolver : DataContractResolver { public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver) { return knownTypeResolver.ResolveName(typeName, typeNamespace, declaredType, null); } public override bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { Type actualDataContractType = dataContractType.Name.EndsWith("Proxy") ? dataContractType.BaseType : dataContractType; return knownTypeResolver.TryResolveType(actualDataContractType, declaredType, null, out typeName, out typeNamespace); } } [Serializable] public class POCOTypeResolver : DataContractResolver { public override bool TryResolveType(Type dcType, Type declaredType, DataContractResolver KTResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { string resolvedTypeName = string.Empty; string resolvedNamespace = string.Empty; resolvedNamespace = "http://www.default.com"; switch (dcType.Name) { case "POCOObjectContainer": { resolvedTypeName = "POCO"; } break; case "Person": { throw new InvalidOperationException("Member with attribute 'IgnoreDataMember' should be ignored during ser"); } default: { return KTResolver.TryResolveType(dcType, declaredType, null, out typeName, out typeNamespace); } } //for types resolved by the DCR XmlDictionary dic = new XmlDictionary(); typeName = dic.Add(resolvedTypeName); typeNamespace = dic.Add(resolvedNamespace); return true; } public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver KTResolver) { if (typeNamespace.Equals("http://www.default.com")) { if (typeName.Equals("POCO")) { return typeof(POCOObjectContainer); } } if (typeName.Equals("Person")) { throw new InvalidOperationException("Member with attribute 'IgnoreDataMember' should be ignored during deser"); } Type result = KTResolver.ResolveName(typeName, typeNamespace, declaredType, null); return result; } } public class WireFormatVerificationResolver : DataContractResolver { private Type _type; public override bool TryResolveType(Type dcType, Type declaredType, DataContractResolver KTResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { if (!KTResolver.TryResolveType(dcType, declaredType, null, out typeName, out typeNamespace)) { _type = dcType; typeName = new XmlDictionary().Add(dcType.FullName + "***"); typeNamespace = new XmlDictionary().Add(dcType.Assembly.FullName + "***"); } return true; } public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver KTResolver) { Type t = null; if (typeName.Contains("***")) { t = _type; } else { t = KTResolver.ResolveName(typeName, typeNamespace, declaredType, null); if (t == null) { t = Type.GetType(typeName + "," + typeNamespace); } } return t; } } public class UserTypeToPrimitiveTypeResolver : DataContractResolver { public override bool TryResolveType(Type dcType, Type declaredType, DataContractResolver KTResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { string resolvedTypeName = string.Empty; string resolvedNamespace = "http://www.default.com"; switch (dcType.Name) { case "UnknownEmployee": resolvedTypeName = "int"; resolvedNamespace = "http://www.w3.org/2001/XMLSchema"; break; case "UserTypeContainer": resolvedTypeName = "UserType"; break; default: return KTResolver.TryResolveType(dcType, declaredType, null, out typeName, out typeNamespace); } XmlDictionary dic = new XmlDictionary(); typeName = dic.Add(resolvedTypeName); typeNamespace = dic.Add(resolvedNamespace); return true; } public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver KTResolver) { if (typeNamespace.Equals("http://www.default.com")) { if (typeName.Equals("UserType")) { return typeof(UserTypeContainer); } } if (typeNamespace.Equals("http://www.w3.org/2001/XMLSchema") && typeName.Equals("int")) { return typeof(UnknownEmployee); } return KTResolver.ResolveName(typeName, typeNamespace, declaredType, null); } } [Serializable] public class SimpleResolver_Ser : DataContractResolver { private static readonly string s_defaultNs = "http://schemas.datacontract.org/2004/07/"; public override bool TryResolveType(Type dcType, Type declaredType, DataContractResolver KTResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { string resolvedNamespace = string.Empty; resolvedNamespace = s_defaultNs; XmlDictionary dictionary = new XmlDictionary(); typeName = dictionary.Add(dcType.FullName); typeNamespace = dictionary.Add(resolvedNamespace); return true; } public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver KTResolver) { throw new NotImplementedException("Deserialization is supposed to be handled by the SimpleResolver_DeSer resolver."); } } [Serializable] public class SimpleResolver_DeSer : DataContractResolver { private static readonly string s_defaultNs = "http://schemas.datacontract.org/2004/07/"; public override bool TryResolveType(Type dcType, Type declaredType, DataContractResolver KTResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { throw new NotImplementedException("Serialization is supposed to be handled by the SimpleResolver_Ser resolver."); } public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver KTResolver) { if (typeNamespace.Equals(s_defaultNs)) { if (typeName.Equals(typeof(DCRVariations).FullName)) { return typeof(DCRVariations); } if (typeName.Equals(typeof(Person).FullName)) { return typeof(Person); } if (typeName.Equals(typeof(SimpleDC).FullName)) { return typeof(SimpleDC); } } return KTResolver.ResolveName(typeName, typeNamespace, declaredType, null); } } public class VerySimpleResolver : DataContractResolver { public override bool TryResolveType(Type dcType, Type declaredType, DataContractResolver KTResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { if (!KTResolver.TryResolveType(dcType, declaredType, null, out typeName, out typeNamespace)) { typeName = new XmlDictionary().Add(dcType.FullName); typeNamespace = new XmlDictionary().Add(dcType.Assembly.FullName); } return true; } public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver KTResolver) { Type t = KTResolver.ResolveName(typeName, typeNamespace, declaredType, null); if (t == null) { try { t = Type.GetType(typeName + "," + typeNamespace); } catch (Exception) { return null; } } return t; } } public class ResolverDefaultCollections : DataContractResolver { private readonly static string s_defaultNs = "http://www.default.com"; public override bool TryResolveType(Type dcType, Type declaredType, DataContractResolver KTResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { string resolvedNamespace = string.Empty; resolvedNamespace = s_defaultNs; XmlDictionary dictionary = new XmlDictionary(); typeName = dictionary.Add(dcType.FullName); typeNamespace = dictionary.Add(resolvedNamespace); return true; } public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver KTResolver) { if (typeNamespace.Equals(s_defaultNs)) { if (typeName.Equals(typeof(Person).FullName)) { return typeof(Person); } if (typeName.Equals(typeof(CharClass).FullName)) { return typeof(CharClass); } if (typeName.Equals("System.String")) { return typeof(string); } if (typeName.Equals(typeof(Version1).FullName)) { return typeof(Version1); } if (typeName.Equals(typeof(Employee).FullName)) { return typeof(Employee); } } return KTResolver.ResolveName(typeName, typeNamespace, declaredType, null); } } [Serializable] public class SimpleResolver : DataContractResolver { private static readonly string s_defaultNS = "http://schemas.datacontract.org/2004/07/"; private TypeLibraryManager _mgr = new TypeLibraryManager(); public override bool TryResolveType(Type dcType, Type declaredType, DataContractResolver KTResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { string resolvedTypeName = string.Empty; string resolvedNamespace = string.Empty; XmlDictionary dic = new XmlDictionary(); if (_mgr.AllTypesList.Contains(dcType)) { resolvedTypeName = dcType.FullName + "***"; resolvedNamespace = s_defaultNS + resolvedTypeName; typeName = dic.Add(resolvedTypeName); typeNamespace = dic.Add(resolvedNamespace); } else { KTResolver.TryResolveType(dcType, declaredType, null, out typeName, out typeNamespace); } if (typeName == null || typeNamespace == null) { XmlDictionary dictionary = new XmlDictionary(); typeName = dictionary.Add(dcType.FullName); typeNamespace = dictionary.Add(dcType.Assembly.FullName); } return true; } public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver KTResolver) { TypeLibraryManager mgr = new TypeLibraryManager(); string inputTypeName = typeName.Trim('*'); Type result = null; if (null != mgr.AllTypesHashtable[inputTypeName]) { result = (Type)mgr.AllTypesHashtable[inputTypeName]; } else { result = KTResolver.ResolveName(typeName, typeNamespace, declaredType, null); } if (null == result) { try { result = Type.GetType(string.Format("{0}, {1}", typeName, typeNamespace)); } catch (System.IO.FileLoadException) { //Type.GetType throws exception on netfx if it cannot find a type while it just returns null on NetCore. //The behavior difference of Type.GetType is a known issue. //Catch the exception so that test case can pass on netfx. return null; } } return result; } } }
using System; namespace Yarn { // A value from inside Yarn. public class Value : IComparable, IComparable<Value> { public static readonly Value NULL = new Value(); public enum Type { Number, // a constant number String, // a string Bool, // a boolean value Variable, // the name of a variable; will be expanded at runtime Null, // the null value } public Value.Type type { get; internal set; } // The underlying values for this object internal float numberValue {get; private set;} internal string variableName {get; set;} internal string stringValue {get; private set;} internal bool boolValue {get; private set;} private object backingValue { get { switch( this.type ) { case Type.Null: return null; case Type.String: return this.stringValue; case Type.Number: return this.numberValue; case Type.Bool: return this.boolValue; } throw new InvalidOperationException( string.Format("Can't get good backing type for {0}", this.type) ); } } public float AsNumber { get { switch (type) { case Type.Number: return numberValue; case Type.String: try { return float.Parse (stringValue); } catch (FormatException) { return 0.0f; } case Type.Bool: return boolValue ? 1.0f : 0.0f; case Type.Null: return 0.0f; default: throw new InvalidOperationException ("Cannot cast to number from " + type.ToString()); } } } public bool AsBool { get { switch (type) { case Type.Number: return !float.IsNaN(numberValue) && numberValue != 0.0f; case Type.String: return !String.IsNullOrEmpty(stringValue); case Type.Bool: return boolValue; case Type.Null: return false; default: throw new InvalidOperationException ("Cannot cast to bool from " + type.ToString()); } } } public string AsString { get { switch (type) { case Type.Number: if (float.IsNaN(numberValue) ) { return "NaN"; } return numberValue.ToString (); case Type.String: return stringValue; case Type.Bool: return boolValue.ToString (); case Type.Null: return "null"; default: throw new ArgumentOutOfRangeException (); } } } // Create a null value public Value () : this(null) { } // Create a value with a C# object public Value (object value) { // Copy an existing value if (typeof(Value).IsInstanceOfType(value)) { var otherValue = value as Value; type = otherValue.type; switch (type) { case Type.Number: numberValue = otherValue.numberValue; break; case Type.String: stringValue = otherValue.stringValue; break; case Type.Bool: boolValue = otherValue.boolValue; break; case Type.Variable: variableName = otherValue.variableName; break; case Type.Null: break; default: throw new ArgumentOutOfRangeException (); } return; } if (value == null) { type = Type.Null; return; } if (value.GetType() == typeof(string) ) { type = Type.String; stringValue = (string)value; return; } if (value.GetType() == typeof(int) || value.GetType() == typeof(float) || value.GetType() == typeof(double)) { type = Type.Number; numberValue = (float)value; return; } if (value.GetType() == typeof(bool) ) { type = Type.Bool; boolValue = (bool)value; return; } var error = string.Format("Attempted to create a Value using a {0}; currently, " + "Values can only be numbers, strings, bools or null.", value.GetType().Name); throw new YarnException(error); } public virtual int CompareTo(object obj) { if (obj == null) return 1; // soft, fast coercion var other = obj as Value; // not a value if( other == null ) throw new ArgumentException("Object is not a Value"); // it is a value! return this.CompareTo(other); } public virtual int CompareTo(Value other) { if (other == null) { return 1; } if (other.type == this.type) { switch (this.type) { case Type.Null: return 0; case Type.String: return this.stringValue.CompareTo (other.stringValue); case Type.Number: return this.numberValue.CompareTo (other.numberValue); case Type.Bool: return this.boolValue.CompareTo (other.boolValue); } } // try to do a string test at that point! return this.AsString.CompareTo(other.AsString); } public override bool Equals (object obj) { if (obj == null || GetType() != obj.GetType()) { return false; } var other = (Value)obj; switch (this.type) { case Type.Number: return this.AsNumber == other.AsNumber; case Type.String: return this.AsString == other.AsString; case Type.Bool: return this.AsBool == other.AsBool; case Type.Null: return other.type == Type.Null || other.AsNumber == 0 || other.AsBool == false; default: throw new ArgumentOutOfRangeException (); } } // override object.GetHashCode public override int GetHashCode() { var backing = this.backingValue; // TODO: yeah hay maybe fix this if( backing != null ) { return backing.GetHashCode(); } return 0; } public override string ToString () { return string.Format ("[Value: type={0}, AsNumber={1}, AsBool={2}, AsString={3}]", type, AsNumber, AsBool, AsString); } public static Value operator+ (Value a, Value b) { // catches: // undefined + string // number + string // string + string // bool + string // null + string if (a.type == Type.String || b.type == Type.String ) { // we're headed for string town! return new Value( a.AsString + b.AsString ); } // catches: // number + number // bool (=> 0 or 1) + number // null (=> 0) + number // bool (=> 0 or 1) + bool (=> 0 or 1) // null (=> 0) + null (=> 0) if ((a.type == Type.Number || b.type == Type.Number) || (a.type == Type.Bool && b.type == Type.Bool) || (a.type == Type.Null && b.type == Type.Null) ) { return new Value( a.AsNumber + b.AsNumber ); } throw new System.ArgumentException( string.Format("Cannot add types {0} and {1}.", a.type, b.type ) ); } public static Value operator- (Value a, Value b) { if (a.type == Type.Number && (b.type == Type.Number || b.type == Type.Null) || b.type == Type.Number && (a.type == Type.Number || a.type == Type.Null) ) { return new Value( a.AsNumber - b.AsNumber ); } throw new System.ArgumentException( string.Format("Cannot subtract types {0} and {1}.", a.type, b.type ) ); } public static Value operator* (Value a, Value b) { if (a.type == Type.Number && (b.type == Type.Number || b.type == Type.Null) || b.type == Type.Number && (a.type == Type.Number || a.type == Type.Null) ) { return new Value( a.AsNumber * b.AsNumber ); } throw new System.ArgumentException( string.Format("Cannot multiply types {0} and {1}.", a.type, b.type ) ); } public static Value operator/ (Value a, Value b) { if (a.type == Type.Number && (b.type == Type.Number || b.type == Type.Null) || b.type == Type.Number && (a.type == Type.Number || a.type == Type.Null) ) { return new Value( a.AsNumber / b.AsNumber ); } throw new System.ArgumentException( string.Format("Cannot divide types {0} and {1}.", a.type, b.type ) ); } public static Value operator- (Value a) { if( a.type == Type.Number ) { return new Value( -a.AsNumber ); } if (a.type == Type.Null && a.type == Type.String && (a.AsString == null || a.AsString.Trim() == "") ) { return new Value( -0 ); } return new Value( float.NaN ); } // Define the is greater than operator. public static bool operator > (Value operand1, Value operand2) { return operand1.CompareTo(operand2) == 1; } // Define the is less than operator. public static bool operator < (Value operand1, Value operand2) { return operand1.CompareTo(operand2) == -1; } // Define the is greater than or equal to operator. public static bool operator >= (Value operand1, Value operand2) { return operand1.CompareTo(operand2) >= 0; } // Define the is less than or equal to operator. public static bool operator <= (Value operand1, Value operand2) { return operand1.CompareTo(operand2) <= 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.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using Xunit; namespace System.Reflection.Context.Tests { public class VirtualPropertyInfo_PropertySetter_Tests { // Points to a PropertyInfo instance created by reflection. This doesn't work in a reflection-only context. private readonly MethodInfo _virtualPropertySetter; private readonly TestObject _testObject = new TestObject("Age"); public VirtualPropertyInfo_PropertySetter_Tests() { var customReflectionContext = new VirtualPropertyInfoCustomReflectionContext(); TypeInfo typeInfo = typeof(TestObject).GetTypeInfo(); TypeInfo customTypeInfo = customReflectionContext.MapType(typeInfo); PropertyInfo virtualProperty = customTypeInfo.DeclaredProperties.ElementAt(2); _virtualPropertySetter = virtualProperty.GetSetMethod(false); } [Fact] public void ProjectionTest() { Assert.Equal(ProjectionConstants.VirtualPropertyInfoSetter, _virtualPropertySetter.GetType().FullName); } [Fact] public void GetCustomAttributes_WithType_Test() { object[] attributes = _virtualPropertySetter.GetCustomAttributes(typeof(TestGetterSetterAttribute), true); Assert.Single(attributes); Assert.IsType<TestGetterSetterAttribute>(attributes[0]); } [Fact] public void GetCustomAttributes_NoType_Test() { object[] attributes = _virtualPropertySetter.GetCustomAttributes(false); Assert.Single(attributes); Assert.IsType<TestGetterSetterAttribute>(attributes[0]); } [Fact] public void GetCustomAttributesDataTest() { // This will never return any results as virtual properties never have custom attributes // defined in code as they are instantiated during runtime. But as the method is overriden // we call it for code coverage. IList<CustomAttributeData> customAttributesData = _virtualPropertySetter.GetCustomAttributesData(); Assert.Empty(customAttributesData); } [Fact] public void IsDefinedTest() { Assert.True(_virtualPropertySetter.IsDefined(typeof(TestGetterSetterAttribute), true)); Assert.True(_virtualPropertySetter.IsDefined(typeof(TestGetterSetterAttribute), false)); Assert.False(_virtualPropertySetter.IsDefined(typeof(DataContractAttribute), true)); Assert.False(_virtualPropertySetter.IsDefined(typeof(DataContractAttribute), false)); } [Fact] public void GetParametersTest() { ParameterInfo[] virtualParameters = _virtualPropertySetter.GetParameters(); Assert.Single(virtualParameters); Assert.Equal(ProjectionConstants.VirtualParameter, virtualParameters[0].GetType().FullName); } [Fact] public void Invoke_NullParameter_Throws() { Assert.Throws<TargetParameterCountException>(() => _virtualPropertySetter.Invoke(null, BindingFlags.GetProperty, null, null, CultureInfo.InvariantCulture)); } [Fact] public void Invoke_NotSingleParameter_Throws() { Assert.Throws<TargetParameterCountException>(() => _virtualPropertySetter.Invoke(_testObject, BindingFlags.GetProperty, null, new object[] { }, CultureInfo.InvariantCulture)); Assert.Throws<TargetParameterCountException>(() => _virtualPropertySetter.Invoke(_testObject, BindingFlags.GetProperty, null, new object[] { "a", 1 }, CultureInfo.InvariantCulture)); } [Fact] public void Invoke_NullObject_Throws() { Assert.Throws<TargetException>(() => _virtualPropertySetter.Invoke(null, BindingFlags.GetProperty, null, new object[] { 2 }, CultureInfo.InvariantCulture)); } [Fact] public void Invoke_WrongObject_Throws() { Assert.Throws<TargetException>(() => _virtualPropertySetter.Invoke("text", BindingFlags.GetProperty, null, new object[] { 2 }, CultureInfo.InvariantCulture)); } [Fact] public void Invoke_ValidArguments_Success() { object returnVal = _virtualPropertySetter.Invoke(_testObject, BindingFlags.GetProperty, null, new object[] { 2 }, CultureInfo.InvariantCulture); Assert.Null(returnVal); } [Fact] public void CallingConventionTest() { Assert.Equal(CallingConventions.HasThis | CallingConventions.Standard, _virtualPropertySetter.CallingConvention); } [Fact] public void ContainsGenericParametersTest() { Assert.False(_virtualPropertySetter.ContainsGenericParameters); } [Fact] public void IsGenericMethodTest() { Assert.False(_virtualPropertySetter.IsGenericMethod); } [Fact] public void IsGenericMethodDefinitionTest() { Assert.False(_virtualPropertySetter.IsGenericMethodDefinition); } [Fact] public void MethodHandleTest() { Assert.Throws<NotSupportedException>(() => _virtualPropertySetter.MethodHandle); } [Fact] public void ModuleTest() { Module customModule = _virtualPropertySetter.Module; Assert.Equal(ProjectionConstants.CustomModule, customModule.GetType().FullName); } [Fact] public void ReturnParameterTest() { ParameterInfo virtualReturnParameter = _virtualPropertySetter.ReturnParameter; Assert.Equal(ProjectionConstants.VirtualReturnParameter, virtualReturnParameter.GetType().FullName); ParameterInfo clone = _virtualPropertySetter.ReturnParameter; Assert.Equal(virtualReturnParameter.GetHashCode(), clone.GetHashCode()); Assert.True(virtualReturnParameter.Equals(clone)); } [Fact] public void ReturnTypeCustomAttributes() { ICustomAttributeProvider virtualReturnParameter = _virtualPropertySetter.ReturnTypeCustomAttributes; Assert.Equal(ProjectionConstants.VirtualReturnParameter, virtualReturnParameter.GetType().FullName); } [Fact] public void GetBaseDefinition() { Assert.Equal(_virtualPropertySetter, _virtualPropertySetter.GetBaseDefinition()); } [Fact] public void GetGenericArgumentsTest() { object[] attributes = _virtualPropertySetter.GetGenericArguments(); Assert.IsType<Type[]>(attributes); Assert.Empty(attributes); } [Fact] public void GetGenericMethodDefinitionTest() { Assert.Throws<InvalidOperationException>(() => _virtualPropertySetter.GetGenericMethodDefinition()); } [Fact] public void GetMethodImplementationFlagsTest() { Assert.Equal(MethodImplAttributes.IL, _virtualPropertySetter.GetMethodImplementationFlags()); } [Fact] public void MakeGenericMethodTest() { Assert.Throws<InvalidOperationException>(() => _virtualPropertySetter.MakeGenericMethod()); } [Fact] public void GetCustomAttributesTest() { Assert.True(_virtualPropertySetter.Equals(_virtualPropertySetter)); } } }
/* * 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.Client { using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Client.Cache; using Apache.Ignite.Core.Configuration; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Tests.Client.Cache; using NUnit.Framework; /// <summary> /// Tests client connection: port ranges, version checks, etc. /// </summary> public class ClientConnectionTest { /** Temp dir for WAL. */ private readonly string _tempDir = PathUtils.GetTempDirectoryName(); /// <summary> /// Sets up the test. /// </summary> [SetUp] public void SetUp() { TestUtils.ClearWorkDir(); } /// <summary> /// Test tear down. /// </summary> [TearDown] public void TearDown() { Ignition.StopAll(true); if (Directory.Exists(_tempDir)) { Directory.Delete(_tempDir, true); } TestUtils.ClearWorkDir(); } /// <summary> /// Tests that missing server yields connection refused error. /// </summary> [Test] public void TestNoServerConnectionRefused() { var ex = Assert.Throws<AggregateException>(() => StartClient()); var socketEx = ex.InnerExceptions.OfType<SocketException>().First(); Assert.AreEqual(SocketError.ConnectionRefused, socketEx.SocketErrorCode); } /// <summary> /// Tests that empty username or password are not allowed. /// </summary> [Test] public void TestAuthenticationEmptyCredentials() { using (Ignition.Start(SecureServerConfig())) { var cliCfg = GetSecureClientConfig(); cliCfg.Password = null; var ex = Assert.Throws<IgniteClientException>(() => { Ignition.StartClient(cliCfg); }); Assert.IsTrue(ex.Message.StartsWith("IgniteClientConfiguration.Password cannot be null")); cliCfg.Password = ""; ex = Assert.Throws<IgniteClientException>(() => { Ignition.StartClient(cliCfg); }); Assert.IsTrue(ex.Message.StartsWith("IgniteClientConfiguration.Password cannot be empty")); cliCfg.Password = "ignite"; cliCfg.UserName = null; ex = Assert.Throws<IgniteClientException>(() => { Ignition.StartClient(cliCfg); }); Assert.IsTrue(ex.Message.StartsWith("IgniteClientConfiguration.UserName cannot be null")); cliCfg.UserName = ""; ex = Assert.Throws<IgniteClientException>(() => { Ignition.StartClient(cliCfg); }); Assert.IsTrue(ex.Message.StartsWith("IgniteClientConfiguration.Username cannot be empty")); } } /// <summary> /// Test invalid username or password. /// </summary> [Test] public void TestAuthenticationInvalidCredentials() { using (Ignition.Start(SecureServerConfig())) { var cliCfg = GetSecureClientConfig(); cliCfg.UserName = "invalid"; var ex = Assert.Throws<IgniteClientException>(() => { Ignition.StartClient(cliCfg); }); Assert.True(ex.StatusCode == ClientStatusCode.AuthenticationFailed); cliCfg.UserName = "ignite"; cliCfg.Password = "invalid"; ex = Assert.Throws<IgniteClientException>(() => { Ignition.StartClient(cliCfg); }); Assert.True(ex.StatusCode == ClientStatusCode.AuthenticationFailed); } } /// <summary> /// Test authentication. /// </summary> [Test] public void TestAuthentication() { CreateNewUserAndAuthenticate("my_User", "my_Password"); } /// <summary> /// Test authentication. /// </summary> [Test] public void TestAuthenticationLongToken() { string user = new string('G', 59); string pass = new string('q', 16 * 1024); CreateNewUserAndAuthenticate(user, pass); } /// <summary> /// Tests that multiple clients can connect to one server. /// </summary> [Test] public void TestMultipleClients() { using (Ignition.Start(TestUtils.GetTestConfiguration())) { var client1 = StartClient(); var client2 = StartClient(); var client3 = StartClient(); client1.Dispose(); client2.Dispose(); client3.Dispose(); } } /// <summary> /// Tests custom connector and client configuration. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestCustomConfig() { var servCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { ClientConnectorConfiguration = new ClientConnectorConfiguration { Host = "localhost", Port = 2000, PortRange = 1, SocketSendBufferSize = 100, SocketReceiveBufferSize = 50 } }; var clientCfg = new IgniteClientConfiguration { Endpoints = new[] {"localhost:2000"}, Logger = new ConsoleLogger() }; using (Ignition.Start(servCfg)) using (var client = Ignition.StartClient(clientCfg)) { Assert.AreNotEqual(clientCfg, client.GetConfiguration()); Assert.AreNotEqual(client.GetConfiguration(), client.GetConfiguration()); Assert.AreEqual(clientCfg.ToXml(), client.GetConfiguration().ToXml()); var conn = client.GetConnections().Single(); Assert.AreEqual(servCfg.ClientConnectorConfiguration.Port, ((IPEndPoint) conn.RemoteEndPoint).Port); } } /// <summary> /// Tests client config with EndPoints property. /// </summary> [Test] public void TestEndPoints() { using (var ignite = Ignition.Start(TestUtils.GetTestConfiguration())) { ignite.CreateCache<int, int>("foo"); const int port = IgniteClientConfiguration.DefaultPort; // DnsEndPoint. var cfg = new IgniteClientConfiguration { Endpoints = new[] { "localhost" } }; using (var client = Ignition.StartClient(cfg)) { Assert.AreEqual("foo", client.GetCacheNames().Single()); } // IPEndPoint. cfg = new IgniteClientConfiguration { Endpoints = new[] { "127.0.0.1:" + port } }; using (var client = Ignition.StartClient(cfg)) { Assert.AreEqual("foo", client.GetCacheNames().Single()); } // Port range. cfg = new IgniteClientConfiguration("127.0.0.1:10798..10800"); using (var client = Ignition.StartClient(cfg)) { Assert.AreEqual("foo", client.GetCacheNames().Single()); } } } /// <summary> /// Tests that empty port range causes an exception. /// </summary> [Test] public void TestEmptyPortRangeThrows() { var cfg = new IgniteClientConfiguration("127.0.0.1:10800..10700"); var ex = Assert.Throws<IgniteClientException>(() => Ignition.StartClient(cfg)); Assert.AreEqual( "Invalid format of IgniteClientConfiguration.Endpoint, port range is empty: 127.0.0.1:10800..10700", ex.Message); } /// <summary> /// Tests that default configuration throws. /// </summary> [Test] public void TestDefaultConfigThrows() { Assert.Throws<IgniteClientException>(() => Ignition.StartClient(new IgniteClientConfiguration())); } /// <summary> /// Tests that connector can be disabled. /// </summary> [Test] public void TestDisabledConnector() { var servCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { ClientConnectorConfigurationEnabled = false }; var clientCfg = new IgniteClientConfiguration { Endpoints = new[] {"localhost"} }; using (Ignition.Start(servCfg)) { var ex = Assert.Throws<AggregateException>(() => Ignition.StartClient(clientCfg)); Assert.AreEqual("Failed to establish Ignite thin client connection, " + "examine inner exceptions for details.", ex.Message.Substring(0, 88)); } // Disable only thin client. servCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { ClientConnectorConfiguration = new ClientConnectorConfiguration { ThinClientEnabled = false } }; using (Ignition.Start(servCfg)) { var ex = Assert.Throws<IgniteClientException>(() => Ignition.StartClient(clientCfg)); Assert.AreEqual("Client handshake failed: 'Thin client connection is not allowed, " + "see ClientConnectorConfiguration.thinClientEnabled.'.", ex.Message.Substring(0, 118)); } } /// <summary> /// Tests that we get a proper exception when server disconnects (node shutdown, network issues, etc). /// </summary> [Test] public void TestServerConnectionAborted() { var evt = new ManualResetEventSlim(); var ignite = Ignition.Start(TestUtils.GetTestConfiguration()); var putGetTask = TaskRunner.Run(() => { using (var client = StartClient()) { var cache = client.GetOrCreateCache<int, int>("foo"); evt.Set(); for (var i = 0; i < 100000; i++) { cache[i] = i; Assert.AreEqual(i, cache.GetAsync(i).Result); } } }); evt.Wait(); ignite.Dispose(); var ex = Assert.Throws<AggregateException>(() => putGetTask.Wait()); var socketEx = ex.GetInnermostException() as SocketException; if (socketEx != null) { Assert.AreEqual(SocketError.ConnectionAborted, socketEx.SocketErrorCode); } else { Assert.Fail("Unexpected exception: " + ex); } } /// <summary> /// Tests the operation timeout. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestOperationTimeout() { var data = Enumerable.Range(1, 500000).ToDictionary(x => x, x => x.ToString()); Ignition.Start(TestUtils.GetTestConfiguration()); var cfg = GetClientConfiguration(); cfg.SocketTimeout = TimeSpan.FromMilliseconds(500); var client = Ignition.StartClient(cfg); var cache = client.CreateCache<int, string>("s"); Assert.AreEqual(cfg.SocketTimeout, client.GetConfiguration().SocketTimeout); // Async. var task = cache.PutAllAsync(data); Assert.IsFalse(task.IsCompleted); var ex = Assert.Catch(() => task.Wait()); Assert.AreEqual(SocketError.TimedOut, GetSocketException(ex).SocketErrorCode); // Sync (reconnect for clean state). Ignition.StopAll(true); Ignition.Start(TestUtils.GetTestConfiguration()); client = Ignition.StartClient(cfg); cache = client.CreateCache<int, string>("s"); ex = Assert.Catch(() => cache.PutAll(data)); Assert.AreEqual(SocketError.TimedOut, GetSocketException(ex).SocketErrorCode); } /// <summary> /// Tests the client dispose while operations are in progress. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestClientDisposeWhileOperationsAreInProgress() { Ignition.Start(TestUtils.GetTestConfiguration()); const int count = 100000; var ops = new Task[count]; using (var client = StartClient()) { var cache = client.GetOrCreateCache<int, int>("foo"); Parallel.For(0, count, new ParallelOptions {MaxDegreeOfParallelism = Environment.ProcessorCount}, i => { ops[i] = cache.PutAllAsync(Enumerable.Range(i*100, 100).ToDictionary(x => x, x => x)); }); } var completed = ops.Count(x => x.Status == TaskStatus.RanToCompletion); Assert.Greater(completed, 0, "Some tasks should have completed."); var failed = ops.Where(x => x.Status == TaskStatus.Faulted).ToArray(); Assert.IsTrue(failed.Any(), "Some tasks should have failed."); foreach (var task in failed) { var ex = task.Exception; Assert.IsNotNull(ex); var baseEx = ex.GetBaseException(); Assert.IsNotNull((object) (baseEx as SocketException) ?? baseEx as ObjectDisposedException, ex.ToString()); } } /// <summary> /// Tests the <see cref="ClientConnectorConfiguration.IdleTimeout"/> property. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestIdleTimeout() { var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { ClientConnectorConfiguration = new ClientConnectorConfiguration { IdleTimeout = TimeSpan.FromMilliseconds(100) } }; var ignite = Ignition.Start(cfg); Assert.AreEqual(100, ignite.GetConfiguration().ClientConnectorConfiguration.IdleTimeout.TotalMilliseconds); using (var client = StartClient()) { var cache = client.GetOrCreateCache<int, int>("foo"); cache[1] = 1; Assert.AreEqual(1, cache[1]); Thread.Sleep(90); Assert.AreEqual(1, cache[1]); // Idle check frequency is 2 seconds. Thread.Sleep(4000); var ex = Assert.Catch(() => cache.Get(1)); Assert.AreEqual(SocketError.ConnectionAborted, GetSocketException(ex).SocketErrorCode); } } /// <summary> /// Tests the protocol mismatch behavior: attempt to connect to an HTTP endpoint. /// </summary> [Test] public void TestProtocolMismatch() { using (Ignition.Start(TestUtils.GetTestConfiguration())) { // Connect to Ignite REST endpoint. var cfg = new IgniteClientConfiguration("127.0.0.1:11211"); var ex = GetSocketException(Assert.Catch(() => Ignition.StartClient(cfg))); Assert.AreEqual(SocketError.ConnectionAborted, ex.SocketErrorCode); } } /// <summary> /// Tests reconnect logic with single server. /// </summary> [Test] public void TestReconnect() { // Connect client and check. Ignition.Start(TestUtils.GetTestConfiguration()); var client = Ignition.StartClient(new IgniteClientConfiguration("127.0.0.1")); Assert.AreEqual(0, client.GetCacheNames().Count); var ep = client.RemoteEndPoint as IPEndPoint; Assert.IsNotNull(ep); Assert.AreEqual(IgniteClientConfiguration.DefaultPort, ep.Port); Assert.AreEqual("127.0.0.1", ep.Address.ToString()); ep = client.LocalEndPoint as IPEndPoint; Assert.IsNotNull(ep); Assert.AreNotEqual(IgniteClientConfiguration.DefaultPort, ep.Port); Assert.AreEqual("127.0.0.1", ep.Address.ToString()); // Stop server. Ignition.StopAll(true); // First request fails, error is detected. var ex = Assert.Catch(() => client.GetCacheNames()); Assert.IsNotNull(GetSocketException(ex)); // Second request causes reconnect attempt which fails (server is stopped). Assert.Catch(() => client.GetCacheNames()); // Start server, next operation succeeds. Ignition.Start(TestUtils.GetTestConfiguration()); Assert.AreEqual(0, client.GetCacheNames().Count); } /// <summary> /// Tests disabled reconnect behavior. /// </summary> [Test] public void TestReconnectDisabled() { // Connect client and check. Ignition.Start(TestUtils.GetTestConfiguration()); using (var client = Ignition.StartClient(new IgniteClientConfiguration("127.0.0.1") { ReconnectDisabled = true })) { Assert.AreEqual(0, client.GetCacheNames().Count); // Stop server. Ignition.StopAll(true); // Request fails, error is detected. var ex = Assert.Catch(() => client.GetCacheNames()); Assert.IsNotNull(GetSocketException(ex)); // Restart server, client does not reconnect. Ignition.Start(TestUtils.GetTestConfiguration()); ex = Assert.Catch(() => client.GetCacheNames()); Assert.IsNotNull(GetSocketException(ex)); } } /// <summary> /// Tests reconnect logic with multiple servers. /// </summary> [Test] public void TestFailover() { // Start 3 nodes. Ignition.Start(TestUtils.GetTestConfiguration(name: "0")); Ignition.Start(TestUtils.GetTestConfiguration(name: "1")); Ignition.Start(TestUtils.GetTestConfiguration(name: "2")); // Connect client. var port = IgniteClientConfiguration.DefaultPort; var cfg = new IgniteClientConfiguration { Endpoints = new[] { "localhost", string.Format("127.0.0.1:{0}..{1}", port + 1, port + 2) } }; using (var client = Ignition.StartClient(cfg)) { Assert.AreEqual(0, client.GetCacheNames().Count); // Stop target node. var nodeId = ((IPEndPoint) client.RemoteEndPoint).Port - port; Ignition.Stop(nodeId.ToString(), true); // Check failure. Assert.IsNotNull(GetSocketException(Assert.Catch(() => client.GetCacheNames()))); // Check reconnect. Assert.AreEqual(0, client.GetCacheNames().Count); // Stop target node. nodeId = ((IPEndPoint) client.RemoteEndPoint).Port - port; Ignition.Stop(nodeId.ToString(), true); // Check failure. Assert.IsNotNull(GetSocketException(Assert.Catch(() => client.GetCacheNames()))); // Check reconnect. Assert.AreEqual(0, client.GetCacheNames().Count); // Stop all nodes. Ignition.StopAll(true); Assert.IsNotNull(GetSocketException(Assert.Catch(() => client.GetCacheNames()))); Assert.IsNotNull(GetSocketException(Assert.Catch(() => client.GetCacheNames()))); } } /// <summary> /// Tests that client stops it's receiver thread upon disposal. /// </summary> [Test] public void TestClientDisposalStopsReceiverThread([Values(true, false)] bool async) { Ignition.Start(TestUtils.GetTestConfiguration()); var logger = new ListLogger {EnabledLevels = new[] {LogLevel.Trace}}; var cfg = new IgniteClientConfiguration(GetClientConfiguration()) { Logger = logger }; using (var client = Ignition.StartClient(cfg)) { var cache = client.GetOrCreateCache<int, int>("c"); if (async) { cache.PutAsync(1, 1); } else { cache.Put(1, 1); } } var threadId = logger.Entries .Select(e => Regex.Match(e.Message, "Receiver thread #([0-9]+) started.")) .Where(m => m.Success) .Select(m => int.Parse(m.Groups[1].Value)) .First(); TestUtils.WaitForTrueCondition(() => logger.Entries.Any( e => e.Message == string.Format("Receiver thread #{0} stopped.", threadId))); } /// <summary> /// Starts the client. /// </summary> private static IIgniteClient StartClient() { return Ignition.StartClient(GetClientConfiguration()); } /// <summary> /// Gets the client configuration. /// </summary> private static IgniteClientConfiguration GetClientConfiguration() { return new IgniteClientConfiguration(IPAddress.Loopback.ToString()); } /// <summary> /// Finds SocketException in the hierarchy. /// </summary> private static SocketException GetSocketException(Exception ex) { Assert.IsNotNull(ex); var origEx = ex; while (ex != null) { var socketEx = ex as SocketException; if (socketEx != null) { return socketEx; } ex = ex.InnerException; } throw new Exception("SocketException not found.", origEx); } /// <summary> /// Create server configuration with enabled authentication. /// </summary> /// <returns>Server configuration.</returns> private IgniteConfiguration SecureServerConfig() { return new IgniteConfiguration(TestUtils.GetTestConfiguration()) { AuthenticationEnabled = true, DataStorageConfiguration = new DataStorageConfiguration { StoragePath = Path.Combine(_tempDir, "Store"), WalPath = Path.Combine(_tempDir, "WalStore"), WalArchivePath = Path.Combine(_tempDir, "WalArchive"), DefaultDataRegionConfiguration = new DataRegionConfiguration { Name = "default", PersistenceEnabled = true } } }; } /// <summary> /// Create client configuration with enabled authentication. /// </summary> /// <returns>Client configuration.</returns> private static IgniteClientConfiguration GetSecureClientConfig() { return new IgniteClientConfiguration("localhost") { UserName = "ignite", Password = "ignite" }; } /// <summary> /// Start new node, create new user with given credentials and try to authenticate. /// </summary> /// <param name="user">Username</param> /// <param name="pass">Password</param> private void CreateNewUserAndAuthenticate(string user, string pass) { using (var srv = Ignition.Start(SecureServerConfig())) { srv.GetCluster().SetActive(true); using (var cli = Ignition.StartClient(GetSecureClientConfig())) { CacheClientConfiguration ccfg = new CacheClientConfiguration { Name = "TestCache", QueryEntities = new[] { new QueryEntity { KeyType = typeof(string), ValueType = typeof(string), }, }, }; ICacheClient<string, string> cache = cli.GetOrCreateCache<string, string>(ccfg); cache.Put("key1", "val1"); cache.Query(new SqlFieldsQuery("CREATE USER \"" + user + "\" WITH PASSWORD '" + pass + "'")).GetAll(); } var cliCfg = GetSecureClientConfig(); cliCfg.UserName = user; cliCfg.Password = pass; using (var cli = Ignition.StartClient(cliCfg)) { ICacheClient<string, string> cache = cli.GetCache<string, string>("TestCache"); string val = cache.Get("key1"); Assert.True(val == "val1"); } } } } }
// 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; namespace System.Globalization { internal class CalendricalCalculationsHelper { private const double FullCircleOfArc = 360.0; // 360.0; private const int HalfCircleOfArc = 180; private const double TwelveHours = 0.5; // half a day private const double Noon2000Jan01 = 730120.5; internal const double MeanTropicalYearInDays = 365.242189; private const double MeanSpeedOfSun = MeanTropicalYearInDays / FullCircleOfArc; private const double LongitudeSpring = 0.0; private const double TwoDegreesAfterSpring = 2.0; private const int SecondsPerDay = 24 * 60 * 60; // 24 hours * 60 minutes * 60 seconds private const int DaysInUniformLengthCentury = 36525; private const int SecondsPerMinute = 60; private const int MinutesPerDegree = 60; private static readonly long s_startOf1810 = GetNumberOfDays(new DateTime(1810, 1, 1)); private static readonly long s_startOf1900Century = GetNumberOfDays(new DateTime(1900, 1, 1)); private static readonly double[] s_coefficients1900to1987 = new double[] { -0.00002, 0.000297, 0.025184, -0.181133, 0.553040, -0.861938, 0.677066, -0.212591 }; private static readonly double[] s_coefficients1800to1899 = new double[] { -0.000009, 0.003844, 0.083563, 0.865736, 4.867575, 15.845535, 31.332267, 38.291999, 28.316289, 11.636204, 2.043794 }; private static readonly double[] s_coefficients1700to1799 = new double[] { 8.118780842, -0.005092142, 0.003336121, -0.0000266484 }; private static readonly double[] s_coefficients1620to1699 = new double[] { 196.58333, -4.0675, 0.0219167 }; private static readonly double[] s_lambdaCoefficients = new double[] { 280.46645, 36000.76983, 0.0003032 }; private static readonly double[] s_anomalyCoefficients = new double[] { 357.52910, 35999.05030, -0.0001559, -0.00000048 }; private static readonly double[] s_eccentricityCoefficients = new double[] { 0.016708617, -0.000042037, -0.0000001236 }; private static readonly double[] s_coefficients = new double[] { Angle(23, 26, 21.448), Angle(0, 0, -46.8150), Angle(0, 0, -0.00059), Angle(0, 0, 0.001813) }; private static readonly double[] s_coefficientsA = new double[] { 124.90, -1934.134, 0.002063 }; private static readonly double[] s_coefficientsB = new double[] { 201.11, 72001.5377, 0.00057 }; private static double RadiansFromDegrees(double degree) { return degree * Math.PI / 180; } private static double SinOfDegree(double degree) { return Math.Sin(RadiansFromDegrees(degree)); } private static double CosOfDegree(double degree) { return Math.Cos(RadiansFromDegrees(degree)); } private static double TanOfDegree(double degree) { return Math.Tan(RadiansFromDegrees(degree)); } public static double Angle(int degrees, int minutes, double seconds) { return ((seconds / SecondsPerMinute + minutes) / MinutesPerDegree) + degrees; } private static double Obliquity(double julianCenturies) { return PolynomialSum(s_coefficients, julianCenturies); } internal static long GetNumberOfDays(DateTime date) { return date.Ticks / GregorianCalendar.TicksPerDay; } private static int GetGregorianYear(double numberOfDays) { return new DateTime(Math.Min((long)(Math.Floor(numberOfDays) * GregorianCalendar.TicksPerDay), DateTime.MaxValue.Ticks)).Year; } private enum CorrectionAlgorithm { Default, Year1988to2019, Year1900to1987, Year1800to1899, Year1700to1799, Year1620to1699 } private struct EphemerisCorrectionAlgorithmMap { public EphemerisCorrectionAlgorithmMap(int year, CorrectionAlgorithm algorithm) { _lowestYear = year; _algorithm = algorithm; } internal int _lowestYear; internal CorrectionAlgorithm _algorithm; }; private static readonly EphemerisCorrectionAlgorithmMap[] s_ephemerisCorrectionTable = new EphemerisCorrectionAlgorithmMap[] { // lowest year that starts algorithm, algorithm to use new EphemerisCorrectionAlgorithmMap(2020, CorrectionAlgorithm.Default), new EphemerisCorrectionAlgorithmMap(1988, CorrectionAlgorithm.Year1988to2019), new EphemerisCorrectionAlgorithmMap(1900, CorrectionAlgorithm.Year1900to1987), new EphemerisCorrectionAlgorithmMap(1800, CorrectionAlgorithm.Year1800to1899), new EphemerisCorrectionAlgorithmMap(1700, CorrectionAlgorithm.Year1700to1799), new EphemerisCorrectionAlgorithmMap(1620, CorrectionAlgorithm.Year1620to1699), new EphemerisCorrectionAlgorithmMap(int.MinValue, CorrectionAlgorithm.Default) // default must be last }; private static double Reminder(double divisor, double dividend) { double whole = Math.Floor(divisor / dividend); return divisor - (dividend * whole); } private static double NormalizeLongitude(double longitude) { longitude = Reminder(longitude, FullCircleOfArc); if (longitude < 0) { longitude += FullCircleOfArc; } return longitude; } public static double AsDayFraction(double longitude) { return longitude / FullCircleOfArc; } private static double PolynomialSum(double[] coefficients, double indeterminate) { double sum = coefficients[0]; double indeterminateRaised = 1; for (int i = 1; i < coefficients.Length; i++) { indeterminateRaised *= indeterminate; sum += (coefficients[i] * indeterminateRaised); } return sum; } private static double CenturiesFrom1900(int gregorianYear) { long july1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 7, 1)); return (double)(july1stOfYear - s_startOf1900Century) / DaysInUniformLengthCentury; } // the following formulas defines a polynomial function which gives us the amount that the earth is slowing down for specific year ranges private static double DefaultEphemerisCorrection(int gregorianYear) { Debug.Assert(gregorianYear < 1620 || 2020 <= gregorianYear); long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1)); double daysSinceStartOf1810 = january1stOfYear - s_startOf1810; double x = TwelveHours + daysSinceStartOf1810; return ((Math.Pow(x, 2) / 41048480) - 15) / SecondsPerDay; } private static double EphemerisCorrection1988to2019(int gregorianYear) { Debug.Assert(1988 <= gregorianYear && gregorianYear <= 2019); return (double)(gregorianYear - 1933) / SecondsPerDay; } private static double EphemerisCorrection1900to1987(int gregorianYear) { Debug.Assert(1900 <= gregorianYear && gregorianYear <= 1987); double centuriesFrom1900 = CenturiesFrom1900(gregorianYear); return PolynomialSum(s_coefficients1900to1987, centuriesFrom1900); } private static double EphemerisCorrection1800to1899(int gregorianYear) { Debug.Assert(1800 <= gregorianYear && gregorianYear <= 1899); double centuriesFrom1900 = CenturiesFrom1900(gregorianYear); return PolynomialSum(s_coefficients1800to1899, centuriesFrom1900); } private static double EphemerisCorrection1700to1799(int gregorianYear) { Debug.Assert(1700 <= gregorianYear && gregorianYear <= 1799); double yearsSince1700 = gregorianYear - 1700; return PolynomialSum(s_coefficients1700to1799, yearsSince1700) / SecondsPerDay; } private static double EphemerisCorrection1620to1699(int gregorianYear) { Debug.Assert(1620 <= gregorianYear && gregorianYear <= 1699); double yearsSince1600 = gregorianYear - 1600; return PolynomialSum(s_coefficients1620to1699, yearsSince1600) / SecondsPerDay; } // ephemeris-correction: correction to account for the slowing down of the rotation of the earth private static double EphemerisCorrection(double time) { int year = GetGregorianYear(time); foreach (EphemerisCorrectionAlgorithmMap map in s_ephemerisCorrectionTable) { if (map._lowestYear <= year) { switch (map._algorithm) { case CorrectionAlgorithm.Default: return DefaultEphemerisCorrection(year); case CorrectionAlgorithm.Year1988to2019: return EphemerisCorrection1988to2019(year); case CorrectionAlgorithm.Year1900to1987: return EphemerisCorrection1900to1987(year); case CorrectionAlgorithm.Year1800to1899: return EphemerisCorrection1800to1899(year); case CorrectionAlgorithm.Year1700to1799: return EphemerisCorrection1700to1799(year); case CorrectionAlgorithm.Year1620to1699: return EphemerisCorrection1620to1699(year); } break; // break the loop and assert eventually } } Debug.Fail("Not expected to come here"); return DefaultEphemerisCorrection(year); } public static double JulianCenturies(double moment) { double dynamicalMoment = moment + EphemerisCorrection(moment); return (dynamicalMoment - Noon2000Jan01) / DaysInUniformLengthCentury; } private static bool IsNegative(double value) { return Math.Sign(value) == -1; } private static double CopySign(double value, double sign) { return (IsNegative(value) == IsNegative(sign)) ? value : -value; } // equation-of-time; approximate the difference between apparent solar time and mean solar time // formal definition is EOT = GHA - GMHA // GHA is the Greenwich Hour Angle of the apparent (actual) Sun // GMHA is the Greenwich Mean Hour Angle of the mean (fictitious) Sun // http://www.esrl.noaa.gov/gmd/grad/solcalc/ // http://en.wikipedia.org/wiki/Equation_of_time private static double EquationOfTime(double time) { double julianCenturies = JulianCenturies(time); double lambda = PolynomialSum(s_lambdaCoefficients, julianCenturies); double anomaly = PolynomialSum(s_anomalyCoefficients, julianCenturies); double eccentricity = PolynomialSum(s_eccentricityCoefficients, julianCenturies); double epsilon = Obliquity(julianCenturies); double tanHalfEpsilon = TanOfDegree(epsilon / 2); double y = tanHalfEpsilon * tanHalfEpsilon; double dividend = ((y * SinOfDegree(2 * lambda)) - (2 * eccentricity * SinOfDegree(anomaly)) + (4 * eccentricity * y * SinOfDegree(anomaly) * CosOfDegree(2 * lambda)) - (0.5 * Math.Pow(y, 2) * SinOfDegree(4 * lambda)) - (1.25 * Math.Pow(eccentricity, 2) * SinOfDegree(2 * anomaly))); double divisor = 2 * Math.PI; double equation = dividend / divisor; // approximation of equation of time is not valid for dates that are many millennia in the past or future // thus limited to a half day return CopySign(Math.Min(Math.Abs(equation), TwelveHours), equation); } private static double AsLocalTime(double apparentMidday, double longitude) { // slightly inaccurate since equation of time takes mean time not apparent time as its argument, but the difference is negligible double universalTime = apparentMidday - AsDayFraction(longitude); return apparentMidday - EquationOfTime(universalTime); } // midday public static double Midday(double date, double longitude) { return AsLocalTime(date + TwelveHours, longitude) - AsDayFraction(longitude); } private static double InitLongitude(double longitude) { return NormalizeLongitude(longitude + HalfCircleOfArc) - HalfCircleOfArc; } // midday-in-tehran public static double MiddayAtPersianObservationSite(double date) { return Midday(date, InitLongitude(52.5)); // 52.5 degrees east - longitude of UTC+3:30 which defines Iranian Standard Time } private static double PeriodicTerm(double julianCenturies, int x, double y, double z) { return x * SinOfDegree(y + z * julianCenturies); } private static double SumLongSequenceOfPeriodicTerms(double julianCenturies) { double sum = 0.0; sum += PeriodicTerm(julianCenturies, 403406, 270.54861, 0.9287892); sum += PeriodicTerm(julianCenturies, 195207, 340.19128, 35999.1376958); sum += PeriodicTerm(julianCenturies, 119433, 63.91854, 35999.4089666); sum += PeriodicTerm(julianCenturies, 112392, 331.2622, 35998.7287385); sum += PeriodicTerm(julianCenturies, 3891, 317.843, 71998.20261); sum += PeriodicTerm(julianCenturies, 2819, 86.631, 71998.4403); sum += PeriodicTerm(julianCenturies, 1721, 240.052, 36000.35726); sum += PeriodicTerm(julianCenturies, 660, 310.26, 71997.4812); sum += PeriodicTerm(julianCenturies, 350, 247.23, 32964.4678); sum += PeriodicTerm(julianCenturies, 334, 260.87, -19.441); sum += PeriodicTerm(julianCenturies, 314, 297.82, 445267.1117); sum += PeriodicTerm(julianCenturies, 268, 343.14, 45036.884); sum += PeriodicTerm(julianCenturies, 242, 166.79, 3.1008); sum += PeriodicTerm(julianCenturies, 234, 81.53, 22518.4434); sum += PeriodicTerm(julianCenturies, 158, 3.5, -19.9739); sum += PeriodicTerm(julianCenturies, 132, 132.75, 65928.9345); sum += PeriodicTerm(julianCenturies, 129, 182.95, 9038.0293); sum += PeriodicTerm(julianCenturies, 114, 162.03, 3034.7684); sum += PeriodicTerm(julianCenturies, 99, 29.8, 33718.148); sum += PeriodicTerm(julianCenturies, 93, 266.4, 3034.448); sum += PeriodicTerm(julianCenturies, 86, 249.2, -2280.773); sum += PeriodicTerm(julianCenturies, 78, 157.6, 29929.992); sum += PeriodicTerm(julianCenturies, 72, 257.8, 31556.493); sum += PeriodicTerm(julianCenturies, 68, 185.1, 149.588); sum += PeriodicTerm(julianCenturies, 64, 69.9, 9037.75); sum += PeriodicTerm(julianCenturies, 46, 8.0, 107997.405); sum += PeriodicTerm(julianCenturies, 38, 197.1, -4444.176); sum += PeriodicTerm(julianCenturies, 37, 250.4, 151.771); sum += PeriodicTerm(julianCenturies, 32, 65.3, 67555.316); sum += PeriodicTerm(julianCenturies, 29, 162.7, 31556.08); sum += PeriodicTerm(julianCenturies, 28, 341.5, -4561.54); sum += PeriodicTerm(julianCenturies, 27, 291.6, 107996.706); sum += PeriodicTerm(julianCenturies, 27, 98.5, 1221.655); sum += PeriodicTerm(julianCenturies, 25, 146.7, 62894.167); sum += PeriodicTerm(julianCenturies, 24, 110.0, 31437.369); sum += PeriodicTerm(julianCenturies, 21, 5.2, 14578.298); sum += PeriodicTerm(julianCenturies, 21, 342.6, -31931.757); sum += PeriodicTerm(julianCenturies, 20, 230.9, 34777.243); sum += PeriodicTerm(julianCenturies, 18, 256.1, 1221.999); sum += PeriodicTerm(julianCenturies, 17, 45.3, 62894.511); sum += PeriodicTerm(julianCenturies, 14, 242.9, -4442.039); sum += PeriodicTerm(julianCenturies, 13, 115.2, 107997.909); sum += PeriodicTerm(julianCenturies, 13, 151.8, 119.066); sum += PeriodicTerm(julianCenturies, 13, 285.3, 16859.071); sum += PeriodicTerm(julianCenturies, 12, 53.3, -4.578); sum += PeriodicTerm(julianCenturies, 10, 126.6, 26895.292); sum += PeriodicTerm(julianCenturies, 10, 205.7, -39.127); sum += PeriodicTerm(julianCenturies, 10, 85.9, 12297.536); sum += PeriodicTerm(julianCenturies, 10, 146.1, 90073.778); return sum; } private static double Aberration(double julianCenturies) { return (0.0000974 * CosOfDegree(177.63 + (35999.01848 * julianCenturies))) - 0.005575; } private static double Nutation(double julianCenturies) { double a = PolynomialSum(s_coefficientsA, julianCenturies); double b = PolynomialSum(s_coefficientsB, julianCenturies); return (-0.004778 * SinOfDegree(a)) - (0.0003667 * SinOfDegree(b)); } public static double Compute(double time) { double julianCenturies = JulianCenturies(time); double lambda = 282.7771834 + (36000.76953744 * julianCenturies) + (0.000005729577951308232 * SumLongSequenceOfPeriodicTerms(julianCenturies)); double longitude = lambda + Aberration(julianCenturies) + Nutation(julianCenturies); return InitLongitude(longitude); } public static double AsSeason(double longitude) { return (longitude < 0) ? (longitude + FullCircleOfArc) : longitude; } private static double EstimatePrior(double longitude, double time) { double timeSunLastAtLongitude = time - (MeanSpeedOfSun * AsSeason(InitLongitude(Compute(time) - longitude))); double longitudeErrorDelta = InitLongitude(Compute(timeSunLastAtLongitude) - longitude); return Math.Min(time, timeSunLastAtLongitude - (MeanSpeedOfSun * longitudeErrorDelta)); } // persian-new-year-on-or-before // number of days is the absolute date. The absolute date is the number of days from January 1st, 1 A.D. // 1/1/0001 is absolute date 1. internal static long PersianNewYearOnOrBefore(long numberOfDays) { double date = (double)numberOfDays; double approx = EstimatePrior(LongitudeSpring, MiddayAtPersianObservationSite(date)); long lowerBoundNewYearDay = (long)Math.Floor(approx) - 1; long upperBoundNewYearDay = lowerBoundNewYearDay + 3; // estimate is generally within a day of the actual occurrance (at the limits, the error expands, since the calculations rely on the mean tropical year which changes...) long day = lowerBoundNewYearDay; for (; day != upperBoundNewYearDay; ++day) { double midday = MiddayAtPersianObservationSite((double)day); double l = Compute(midday); if ((LongitudeSpring <= l) && (l <= TwoDegreesAfterSpring)) { break; } } Debug.Assert(day != upperBoundNewYearDay); return day - 1; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using Bloom; using Bloom.Book; using Bloom.Collection; using Bloom.Publish.Epub; using Bloom.web; using ICSharpCode.SharpZipLib.Zip; using Moq; using NUnit.Framework; using SIL.IO; using SIL.TestUtilities; using SIL.Windows.Forms.ClearShare; using SIL.Windows.Forms.ImageToolbox; using Color = System.Drawing.Color; namespace BloomTests.Book { class BookCompressorTests : BookTestsBase { private BookServer _bookServer; private TemporaryFolder _projectFolder; private Mock<CollectionSettings> _librarySettings; private BookStarter _starter; private string kMinimumValidBookHtml = @"<html><head><link rel='stylesheet' href='Basic Book.css' type='text/css'></link></head><body> <div class='bloom-page' id='guid1'></div> </body></html>"; [SetUp] public void SetupFixture() { _bookServer = CreateBookServer(); } [Test] public void CompressBookForDevice_FileNameIsCorrect() { var testBook = CreateBookWithPhysicalFile(kMinimumValidBookHtml, bringBookUpToDate: true); using (var bloomdTempFile = TempFile.WithFilenameInTempFolder(testBook.Title + BookCompressor.ExtensionForDeviceBloomBook)) { BookCompressor.CompressBookForDevice(bloomdTempFile.Path, testBook, _bookServer, Color.Azure, new NullWebSocketProgress()); Assert.AreEqual(testBook.Title + BookCompressor.ExtensionForDeviceBloomBook, Path.GetFileName(bloomdTempFile.Path)); } } [Test] public void CompressBookForDevice_IncludesWantedFiles() { var wantedFiles = new List<string>() { "thumbnail.png", // should be left alone "previewMode.css", "meta.json", // should be left alone "readerStyles.css", // gets added "Device-XMatter.css" // added when we apply this xmatter }; TestHtmlAfterCompression(kMinimumValidBookHtml, actionsOnFolderBeforeCompressing: folderPath => { // These png files have to be real; just putting some text in it leads to out-of-memory failures when Bloom // tries to make its background transparent. File.Copy(SIL.IO.FileLocator.GetFileDistributedWithApplication(_pathToTestImages, "shirt.png"), Path.Combine(folderPath, "thumbnail.png")); File.WriteAllText(Path.Combine(folderPath, "previewMode.css"), @"This is wanted"); }, assertionsOnZipArchive: zip => { foreach (var name in wantedFiles) { Assert.AreNotEqual(-1, zip.FindEntry(Path.GetFileName(name), true), "expected " + name + " to be part of .bloomd zip"); } }); } [Test] public void CompressBookForDevice_OmitsUnwantedFiles() { // some files we don't want copied into the .bloomd var unwantedFiles = new List<string> { "book.BloomBookOrder", "book.pdf", "thumbnail-256.png", "thumbnail-70.png", // these are artifacts of uploading book to BloomLibrary.org "Traditional-XMatter.css" // since we're adding Device-XMatter.css, this is no longer needed }; TestHtmlAfterCompression(kMinimumValidBookHtml, actionsOnFolderBeforeCompressing: folderPath => { // The png files have to be real; just putting some text in them leads to out-of-memory failures when Bloom // tries to make their background transparent. File.Copy(SIL.IO.FileLocator.GetFileDistributedWithApplication(_pathToTestImages, "shirt.png"), Path.Combine(folderPath, "thumbnail.png")); File.WriteAllText(Path.Combine(folderPath, "previewMode.css"), @"This is wanted"); // now some files we expect to be omitted from the .bloomd archive File.WriteAllText(Path.Combine(folderPath, "book.BloomBookOrder"), @"This is unwanted"); File.WriteAllText(Path.Combine(folderPath, "book.pdf"), @"This is unwanted"); File.Copy(SIL.IO.FileLocator.GetFileDistributedWithApplication(_pathToTestImages, "shirt.png"), Path.Combine(folderPath, "thumbnail-256.png")); File.Copy(SIL.IO.FileLocator.GetFileDistributedWithApplication(_pathToTestImages, "shirt.png"), Path.Combine(folderPath, "thumbnail-70.png")); }, assertionsOnZipArchive: zip => { foreach(var name in unwantedFiles) { Assert.AreEqual(-1, zip.FindEntry(Path.GetFileName(name), true), "expected " + name + " to not be part of .bloomd zip"); } }); } // Also verifies that images that DO exist are NOT removed (even if src attr includes params like ?optional=true) // Since this is one of the few tests that makes a real HTML file we use it also to check // the the HTML file is at the root of the zip. [Test] public void CompressBookForDevice_RemovesImgElementsWithMissingSrc_AndContentEditable() { const string imgsToRemove = "<img class='branding branding-wide' src='back-cover-outside-wide.svg' type='image/svg' onerror='this.style.display='none''></img><img src = 'nonsence.svg'/><img src=\"rubbish\"> </img >"; const string positiveCe = " contenteditable=\"true\""; // This one uses double quotes just to confirm that works. const string negativeCe = " contenteditable='false'"; var htmlTemplate = @"<html> <body> <div class='bloom-page cover coverColor outsideBackCover bloom-backMatter A5Portrait' data-page='required singleton' data-export='back-matter-back-cover' id='b1b3129a-7675-44c4-bc1e-8265bd1dfb08'> <div class='pageLabel' lang='en'> Outside Back Cover </div> <div class='pageDescription' lang='en'></div> <div class='marginBox'> <div class='bloom-translationGroup' data-default-languages='N1'> <div class='bloom-editable Outside-Back-Cover-style bloom-copyFromOtherLanguageIfNecessary bloom-contentNational1 bloom-visibility-code-on' lang='fr'{1} data-book='outsideBackCover'> <label class='bubble'>If you need somewhere to put more information about the book, you can use this page, which is the outside of the back cover.</label> </div> <div class='bloom-editable Outside-Back-Cover-style bloom-copyFromOtherLanguageIfNecessary bloom-contentNational2' lang='de'{1} data-book='outsideBackCover'></div> <div class='bloom-editable Outside-Back-Cover-style bloom-copyFromOtherLanguageIfNecessary bloom-content1' lang='ksf'{1} data-book='outsideBackCover'></div> </div{2}>{0} <img class='branding' src='back-cover-outside.svg?optional=true' type='image/svg' onerror='this.style.display='none''></img></div> </div> </body> </html>"; var htmlOriginal = string.Format(htmlTemplate, imgsToRemove, positiveCe, negativeCe); var testBook = CreateBookWithPhysicalFile(htmlOriginal, bringBookUpToDate: true); TestHtmlAfterCompression(htmlOriginal, actionsOnFolderBeforeCompressing: bookFolderPath => // Simulate the typical situation where we have the regular but not the wide svg File.WriteAllText(Path.Combine(bookFolderPath, "back-cover-outside.svg"), @"this is a fake for testing"), assertionsOnResultingHtmlString: html => { var htmlDom = XmlHtmlConverter.GetXmlDomFromHtml(html); AssertThatXmlIn.Dom(htmlDom).HasSpecifiedNumberOfMatchesForXpath("//img", 2); // only license and back-cover-outside.svg survives AssertThatXmlIn.Dom(htmlDom).HasSpecifiedNumberOfMatchesForXpath("//img[@src='back-cover-outside.svg']", 1); // only back-cover-outside.svg survives AssertThatXmlIn.Dom(htmlDom).HasNoMatchForXpath("//div[@contenteditable]"); }); } [Test] public void CompressBookForDevice_ImgInImageContainer_ConvertedToBackground() { // The odd file names here are an important part of the test; they need to get converted to proper URL syntax. const string bookHtml = @"<html> <body> <div class='bloom-page' id='blah'> <div class='marginBox'> <div class='bloom-imageContainer bloom-leadingElement'>" +" <img src=\"HL00'14 1.svg\"/>" +@"</div> <div class='bloom-imageContainer bloom-leadingElement'>" + "<img src=\"HL00'14 1.svg\"/>" +@"</div> </div> </body> </html>"; TestHtmlAfterCompression(bookHtml, actionsOnFolderBeforeCompressing: bookFolderPath => File.WriteAllText(Path.Combine(bookFolderPath, "HL00'14 1.svg"), @"this is a fake for testing"), assertionsOnResultingHtmlString: changedHtml => { // The imgs should be replaced with something like this: // "<div class='bloom-imageContainer bloom-leadingElement bloom-backgroundImage' style='background-image:url('HL00%2714%201.svg.svg')'</div> // Note that normally there would also be data-creator, data-license, etc. If we put those in the html, they will be stripped because // the code will actually look at our fake image and, finding now metadata will remove these. This is not a problem for our // testing here, because we're not trying to test the functioning of that function here. The bit we can test, that the image became a // background image, is sufficient to know the function was run. // Oct 2017 jh: I added this bloom-imageContainer/ because the code that does the conversion is limited to these, // presumably because that is the only img's that were giving us problems (ones that need to be sized at display time). // But Xmatter has other img's, for license & branding. var changedDom = XmlHtmlConverter.GetXmlDomFromHtml(changedHtml); AssertThatXmlIn.Dom(changedDom).HasNoMatchForXpath("//bloom-imageContainer/img"); // should be merged into parent //Note: things like @data-creator='Anis', @data-license='cc-by' and @data-copyright='1996 SIL PNG' are not going to be there by now, //because they aren't actually supported by the image file, so they get stripped. AssertThatXmlIn.Dom(changedDom).HasSpecifiedNumberOfMatchesForXpath("//div[@class='bloom-imageContainer bloom-leadingElement bloom-backgroundImage' and @style=\"background-image:url('HL00%2714%201.svg')\"]", 2); }); } [Test] public void CompressBookForDevice_IncludesVersionFileAndStyleSheet() { // This requires a real book file (which a mocked book usually doesn't have). // It's also important that the book contains something like contenteditable that will be removed when // sending the book. The sha is based on the actual file contents of the book, not the // content actually embedded in the bloomd. var bookHtml = @"<html> <head> <meta charset='UTF-8'></meta> <link rel='stylesheet' href='../settingsCollectionStyles.css' type='text/css'></link> <link rel='stylesheet' href='../customCollectionStyles.css' type='text/css'></link> </head> <body> <div class='bloom-page cover coverColor outsideBackCover bloom-backMatter A5Portrait' data-page='required singleton' data-export='back-matter-back-cover' id='b1b3129a-7675-44c4-bc1e-8265bd1dfb08'> <div contenteditable='true'>something</div> </div> </body> </html>"; string entryContents = null; TestHtmlAfterCompression(bookHtml, actionsOnFolderBeforeCompressing: bookFolderPath => // Simulate the typical situation where we have the regular but not the wide svg File.WriteAllText(Path.Combine(bookFolderPath, "back-cover-outside.svg"), @"this is a fake for testing"), assertionsOnResultingHtmlString: html => { AssertThatXmlIn.Dom(XmlHtmlConverter.GetXmlDomFromHtml(html)).HasSpecifiedNumberOfMatchesForXpath("//html/head/link[@rel='stylesheet' and @href='readerStyles.css' and @type='text/css']", 1); }, assertionsOnZipArchive: zip => // This test worked when we didn't have to modify the book before making the .bloomd. // Now that we do I haven't figured out a reasonable way to rewrite it to test this value again... // Assert.That(GetEntryContents(zip, "version.txt"), Is.EqualTo(Bloom.Book.Book.MakeVersionCode(html, bookPath))); // ... so for now we just make sure that it was added and looks like a hash code { entryContents = GetEntryContents(zip, "version.txt"); Assert.AreEqual(44, entryContents.Length); }, assertionsOnRepeat: zip => { Assert.That(GetEntryContents(zip, "version.txt"), Is.EqualTo(entryContents)); }); } [Test] public void CompressBookForDevice_QuestionsPages_ConvertsToJson() { // This requires a real book file (which a mocked book usually doesn't have). // Test data reflects a number of important conditions, including presence or absence of // white space before and after asterisk, paragraphs broken up with br. // As yet does not cover questions with no answers (currently will be excluded), // questions with no right answer (currently will be included) // questions with more than one right answer (currently will be included) // questions with only one answer (currently will be included), // since I'm not sure what the desired behavior is. // If we want to test corner cases it might be easier to test BloomReaderFileMaker.MakeQuestion directly. var bookHtml = @"<html> <head> <meta charset='UTF-8'></meta> <link rel='stylesheet' href='../settingsCollectionStyles.css' type='text/css'></link> <link rel='stylesheet' href='../customCollectionStyles.css' type='text/css'></link> </head> <body> <div class='bloom-page cover coverColor outsideBackCover bloom-backMatter A5Portrait' data-page='required singleton' data-export='back-matter-back-cover' id='b1b3129a-7675-44c4-bc1e-8265bd1dfb08'> <div contenteditable='true'>This page should make it into the book</div> </div> <div class='bloom-page customPage enterprise questions nonprinting Device16x9Portrait layout-style-Default side-left bloom-monolingual' id='86574a93-a50f-42da-b78f-574ef790c481' data-page='' data-pagelineage='4140d100-e4c3-49c4-af05-dda5789e019b' data-page-number='1' lang=''> <div class='pageLabel' lang='en'> Comprehension Questions </div> <div class='pageDescription' lang='en'></div> <div class='marginBox'> <div style='min-width: 0px;' class='split-pane vertical-percent'> <div class='split-pane-component position-left'> <div class='split-pane-component-inner'> <div class='ccLabel'> <p>Enter your comprehension questions for this book..., see <a href='https://docs.google.com/document/d/1LV0_OtjH1BTJl7wqdth0bZXQxduTqD7WenX4AsksVGs/edit#heading=h.lxe9k6qcvzwb'>Bloom Enterprise Service</a></p> ... <p>*Appeared to wear the cap</p> </div> </div> </div> <div class='split-pane-divider vertical-divider'></div> <div class='split-pane-component position-right'> <div class='split-pane-component-inner adding'> <div class='bloom-translationGroup bloom-trailingElement cc-style' data-default-languages='auto'> <div data-languagetipcontent='English' aria-label='false' role='textbox' spellcheck='true' tabindex='0' style='min-height: 24px;' class='bloom-editable cke_editable cke_editable_inline cke_contents_ltr cc-style cke_focus bloom-content1 bloom-visibility-code-on' contenteditable='true' lang='en'> <p>Where do questions belong?</p> <p>* At the end</p> <p>At the start</p> <p>In the middle</p> <p></p> </div> <div class='bloom-editable' contenteditable='true' lang='fr'> <p>Where do French questions belong?</p> <p> *At the end of the French</p> <p>At the start of the French</p> <p>In the middle of the French</p> </div> <div class='bloom-editable' contenteditable='true' lang='z'></div> <div aria-label='false' role='textbox' spellcheck='true' tabindex='0' class='bloom-editable cke_editable cke_editable_inline cke_contents_ltr bloom-contentNational1' contenteditable='true' lang='es'> <p></p> </div> </div> </div> </div> </div> </div> </div> <div class='bloom-page customPage enterprise questions nonprinting Device16x9Portrait layout-style-Default side-left bloom-monolingual' id='299c0b20-56f7-4a0f-a6d4-08f1ec01f1e6' data-page='' data-pagelineage='4140d100-e4c3-49c4-af05-dda5789e019b' data-page-number='2' lang=''> <div class='pageLabel' lang='en'> Comprehension Questions </div> <div class='pageDescription' lang='en'></div> <div class='marginBox'> <div style='min-width: 0px;' class='split-pane vertical-percent'> <div class='split-pane-component position-left'> <div class='split-pane-component-inner'> <div class='ccLabel'> <p>Enter your ..., see <a href='https://docs.google.com/document/d/1LV0_OtjH1BTJl7wqdth0bZXQxduTqD7WenX4AsksVGs/edit#heading=h.lxe9k6qcvzwb'>Bloom Enterprise Service</a></p> <p></p> ... <p>*Appeared to wear the cap</p> </div> </div> </div> <div class='split-pane-divider vertical-divider'></div> <div class='split-pane-component position-right'> <div class='split-pane-component-inner adding'> <div class='bloom-translationGroup bloom-trailingElement cc-style' data-default-languages='auto'> <div data-languagetipcontent='English' aria-label='false' role='textbox' spellcheck='true' tabindex='0' style='min-height: 24px;' class='bloom-editable cke_editable cke_editable_inline cke_contents_ltr cc-style cke_focus bloom-content1 bloom-visibility-code-on' contenteditable='true' lang='en'> <p>Where is the USA?<br></br> South America<br></br> *North America<br></br> Europe<br></br> Asia</p> <p></p> <p>Where does the platypus come from?<br></br> *Australia<br></br> Papua New Guinea<br></br> Africa<br></br> Peru</p> <p></p> <p>What is an Emu?<br></br> A fish<br></br> An insect<br></br> A spider<br></br> * A bird</p> <p></p> <p>Where do emus live?<br></br> New Zealand<br></br> * Farms in the USA<br></br> England<br></br> Wherever</p> <p></p> </div> <div class='bloom-editable' contenteditable='true' lang='z'></div> <div aria-label='false' role='textbox' spellcheck='true' tabindex='0' class='bloom-editable cke_editable cke_editable_inline cke_contents_ltr bloom-contentNational1' contenteditable='true' lang='es'> <p></p> </div> </div> </div> </div> </div> </div> </div> </body> </html>"; TestHtmlAfterCompression(bookHtml, assertionsOnResultingHtmlString: html => { // The questions pages should be removed. var htmlDom = XmlHtmlConverter.GetXmlDomFromHtml(html); AssertThatXmlIn.Dom(htmlDom).HasNoMatchForXpath("//html/body/div[contains(@class, 'bloom-page') and contains(@class, 'questions')]"); }, assertionsOnZipArchive: zip => { var json = GetEntryContents(zip, BloomReaderFileMaker.QuestionFileName); var groups = QuestionGroup.FromJson(json); // Two (non-z-language) groups in first question page, one in second. Assert.That(groups, Has.Length.EqualTo(3)); Assert.That(groups[0].questions, Has.Length.EqualTo(1)); Assert.That(groups[1].questions, Has.Length.EqualTo(1)); Assert.That(groups[2].questions, Has.Length.EqualTo(4)); Assert.That(groups[0].lang, Is.EqualTo("en")); Assert.That(groups[1].lang, Is.EqualTo("fr")); Assert.That(groups[0].questions[0].question, Is.EqualTo("Where do questions belong?")); Assert.That(groups[0].questions[0].answers, Has.Length.EqualTo(3)); Assert.That(groups[0].questions[0].answers[0].text, Is.EqualTo("At the end")); Assert.That(groups[0].questions[0].answers[0].correct, Is.True); Assert.That(groups[0].questions[0].answers[1].text, Is.EqualTo("At the start")); Assert.That(groups[0].questions[0].answers[1].correct, Is.False); Assert.That(groups[1].questions[0].question, Is.EqualTo("Where do French questions belong?")); Assert.That(groups[1].questions[0].answers, Has.Length.EqualTo(3)); Assert.That(groups[1].questions[0].answers[0].text, Is.EqualTo("At the end of the French")); Assert.That(groups[1].questions[0].answers[0].correct, Is.True); Assert.That(groups[1].questions[0].answers[1].text, Is.EqualTo("At the start of the French")); Assert.That(groups[1].questions[0].answers[1].correct, Is.False); Assert.That(groups[2].questions[0].question, Is.EqualTo("Where is the USA?")); Assert.That(groups[2].questions[0].answers, Has.Length.EqualTo(4)); Assert.That(groups[2].questions[0].answers[3].text, Is.EqualTo("Asia")); Assert.That(groups[2].questions[0].answers[3].correct, Is.False); Assert.That(groups[2].questions[0].answers[1].text, Is.EqualTo("North America")); Assert.That(groups[2].questions[0].answers[1].correct, Is.True); Assert.That(groups[2].questions[2].question, Is.EqualTo("What is an Emu?")); Assert.That(groups[2].questions[2].answers, Has.Length.EqualTo(4)); Assert.That(groups[2].questions[2].answers[0].text, Is.EqualTo("A fish")); Assert.That(groups[2].questions[2].answers[0].correct, Is.False); Assert.That(groups[2].questions[2].answers[3].text, Is.EqualTo("A bird")); Assert.That(groups[2].questions[2].answers[3].correct, Is.True); // Make sure we don't miss the last answer of the last question. Assert.That(groups[2].questions[3].answers[3].text, Is.EqualTo("Wherever")); } ); } [Test] public void CompressBookForDevice_MakesThumbnailFromCoverPicture() { // This requires a real book file (which a mocked book usually doesn't have). var bookHtml = @"<html> <head> <meta charset='UTF-8'></meta> <link rel='stylesheet' href='../settingsCollectionStyles.css' type='text/css'></link> <link rel='stylesheet' href='../customCollectionStyles.css' type='text/css'></link> </head> <body> <div id='bloomDataDiv'> <div data-book='coverImage' lang='*'> Listen to My Body_Cover.png </div> </div> <div class='bloom-page cover coverColor outsideBackCover bloom-backMatter A5Portrait' data-page='required singleton' data-export='back-matter-back-cover' id='b1b3129a-7675-44c4-bc1e-8265bd1dfb08'> <div class='marginBox'>" + "<div class=\"bloom-imageContainer bloom-backgroundImage\" data-book=\"coverImage\" style=\"background-image:url('Listen%20to%20My%20Body_Cover.png')\"></div>" + @"</div> </div> </body> </html>"; TestHtmlAfterCompression(bookHtml, actionsOnFolderBeforeCompressing: bookFolderPath => { File.Copy(SIL.IO.FileLocator.GetFileDistributedWithApplication(_pathToTestImages, "shirt.png"), Path.Combine(bookFolderPath, "Listen to My Body_Cover.png")); }, assertionsOnZipArchive: zip => { using (var thumbStream = GetEntryContentsStream(zip, "thumbnail.png")) { using (var thumbImage = Image.FromStream(thumbStream)) { // I don't know how to verify that it's made from shirt.png, but this at least verifies // that some shrinking was done and that it considers height as well as width, since // the shirt.png image happens to be higher than it is wide. // It would make sense to test that it works for jpg images, too, but it's rather a slow // test and jpg doesn't involve a different path through the new code. Assert.That(thumbImage.Width, Is.LessThanOrEqualTo(256)); Assert.That(thumbImage.Height, Is.LessThanOrEqualTo(256)); } } } ); } private Stream GetEntryContentsStream(ZipFile zip, string name, bool exact = false) { Func<ZipEntry, bool> predicate; if (exact) predicate = n => n.Name.Equals(name); else predicate = n => n.Name.EndsWith(name); var ze = (from ZipEntry entry in zip select entry).FirstOrDefault(predicate); Assert.That(ze, Is.Not.Null); return zip.GetInputStream(ze); } private string GetEntryContents(ZipFile zip, string name, bool exact = false) { var buffer = new byte[4096]; using (var instream = GetEntryContentsStream(zip, name, exact)) using (var writer = new MemoryStream()) { ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(instream, writer, buffer); writer.Position = 0; using (var reader = new StreamReader(writer)) { return reader.ReadToEnd(); } } } // re-use the images from another test (added LakePendOreille.jpg for these tests) private const string _pathToTestImages = "src/BloomTests/ImageProcessing/images"; [Test] public void GetBytesOfReducedImage_SmallPngImageMadeTransparent() { // bird.png: PNG image data, 274 x 300, 8-bit/color RGBA, non-interlaced var path = SIL.IO.FileLocator.GetFileDistributedWithApplication(_pathToTestImages, "bird.png"); byte[] originalBytes = File.ReadAllBytes(path); byte[] reducedBytes = BookCompressor.GetBytesOfReducedImage(path); Assert.That(reducedBytes, Is.Not.EqualTo(originalBytes)); // no easy way to check it was made transparent, but should be changed. // Size should not change much. Assert.That(reducedBytes.Length, Is.LessThan(originalBytes.Length * 11/10)); Assert.That(reducedBytes.Length, Is.GreaterThan(originalBytes.Length * 9 / 10)); using (var tempFile = TempFile.WithExtension(Path.GetExtension(path))) { var oldMetadata = Metadata.FromFile(path); RobustFile.WriteAllBytes(tempFile.Path, reducedBytes); var newMetadata = Metadata.FromFile(tempFile.Path); if (oldMetadata.IsEmpty) { Assert.IsTrue(newMetadata.IsEmpty); } else { Assert.IsFalse(newMetadata.IsEmpty); Assert.AreEqual(oldMetadata.CopyrightNotice, newMetadata.CopyrightNotice, "copyright preserved for bird.png"); Assert.AreEqual(oldMetadata.Creator, newMetadata.Creator, "creator preserved for bird.png"); Assert.AreEqual(oldMetadata.License.ToString(), newMetadata.License.ToString(), "license preserved for bird.png"); } } } [Test] public void GetBytesOfReducedImage_SmallJpgImageStaysSame() { // man.jpg: JPEG image data, JFIF standard 1.01, ..., precision 8, 118x154, frames 3 var path = SIL.IO.FileLocator.GetFileDistributedWithApplication(_pathToTestImages, "man.jpg"); var originalBytes = File.ReadAllBytes(path); var reducedBytes = BookCompressor.GetBytesOfReducedImage(path); Assert.AreEqual(originalBytes, reducedBytes, "man.jpg is already small enough (118x154)"); using (var tempFile = TempFile.WithExtension(Path.GetExtension(path))) { var oldMetadata = Metadata.FromFile(path); RobustFile.WriteAllBytes(tempFile.Path, reducedBytes); var newMetadata = Metadata.FromFile(tempFile.Path); if (oldMetadata.IsEmpty) { Assert.IsTrue(newMetadata.IsEmpty); } else { Assert.IsFalse(newMetadata.IsEmpty); Assert.AreEqual(oldMetadata.CopyrightNotice, newMetadata.CopyrightNotice, "copyright preserved for man.jpg"); Assert.AreEqual(oldMetadata.Creator, newMetadata.Creator, "creator preserved for man.jpg"); Assert.AreEqual(oldMetadata.License.ToString(), newMetadata.License.ToString(), "license preserved for man.jpg"); } } } [Test] public void GetBytesOfReducedImage_LargePngImageReduced() { // shirtWithTransparentBg.png: PNG image data, 2208 x 2400, 8-bit/color RGBA, non-interlaced var path = SIL.IO.FileLocator.GetFileDistributedWithApplication(_pathToTestImages, "shirt.png"); var originalBytes = File.ReadAllBytes(path); var reducedBytes = BookCompressor.GetBytesOfReducedImage(path); Assert.Greater(originalBytes.Length, reducedBytes.Length, "shirt.png is reduced from 2208x2400"); using (var tempFile = TempFile.WithExtension(Path.GetExtension(path))) { var oldMetadata = Metadata.FromFile(path); RobustFile.WriteAllBytes(tempFile.Path, reducedBytes); var newMetadata = Metadata.FromFile(tempFile.Path); if (oldMetadata.IsEmpty) { Assert.IsTrue(newMetadata.IsEmpty); } else { Assert.IsFalse(newMetadata.IsEmpty); Assert.AreEqual(oldMetadata.CopyrightNotice, newMetadata.CopyrightNotice, "copyright preserved for shirt.png"); Assert.AreEqual(oldMetadata.Creator, newMetadata.Creator, "creator preserved for shirt.png"); Assert.AreEqual(oldMetadata.License.ToString(), newMetadata.License.ToString(), "license preserved for shirt.png"); } } } [Test] public void GetBytesOfReducedImage_LargeJpgImageReduced() { // LakePendOreille.jpg: JPEG image data, JFIF standard 1.01, ... precision 8, 3264x2448, frames 3 var path = SIL.IO.FileLocator.GetFileDistributedWithApplication(_pathToTestImages, "LakePendOreille.jpg"); var originalBytes = File.ReadAllBytes(path); var reducedBytes = BookCompressor.GetBytesOfReducedImage(path); Assert.Greater(originalBytes.Length, reducedBytes.Length, "LakePendOreille.jpg is reduced from 3264x2448"); using (var tempFile = TempFile.WithExtension(Path.GetExtension(path))) { var oldMetadata = Metadata.FromFile(path); RobustFile.WriteAllBytes(tempFile.Path, reducedBytes); var newMetadata = Metadata.FromFile(tempFile.Path); if (oldMetadata.IsEmpty) { Assert.IsTrue(newMetadata.IsEmpty); } else { Assert.IsFalse(newMetadata.IsEmpty); Assert.AreEqual(oldMetadata.CopyrightNotice, newMetadata.CopyrightNotice, "copyright preserved for LakePendOreille.jpg"); Assert.AreEqual(oldMetadata.Creator, newMetadata.Creator, "creator preserved for LakePendOreille.jpg"); Assert.AreEqual(oldMetadata.License.ToString(), newMetadata.License.ToString(), "license preserved for LakePendOreille.jpg"); } } } [Test] public void GetBytesOfReducedImage_LargePng24bImageReduced() { // lady24b.png: PNG image data, 24bit depth, 3632w x 3872h var path = FileLocator.GetFileDistributedWithApplication(_pathToTestImages, "lady24b.png"); var originalBytes = File.ReadAllBytes(path); var reducedBytes = BookCompressor.GetBytesOfReducedImage(path); // Is it reduced, even tho' we switched from 24bit depth to 32bit depth? Assert.Greater(originalBytes.Length, reducedBytes.Length, "lady24b.png is reduced from 3632x3872"); using (var tempFile = TempFile.WithExtension(Path.GetExtension(path))) { RobustFile.WriteAllBytes(tempFile.Path, reducedBytes); using (var newImage = PalasoImage.FromFileRobustly(tempFile.Path)) Assert.AreEqual(PixelFormat.Format32bppArgb, newImage.Image.PixelFormat, "should have switched to 32bit depth"); } } [Test] public void CompressBookForDevice_PointsAtDeviceXMatter() { var bookHtml = @"<html><head> <link rel='stylesheet' href='Basic Book.css' type='text/css'></link> <link rel='stylesheet' href='Traditional-XMatter.css' type='text/css'></link> </head><body> <div class='bloom-page' id='guid1'></div> </body></html>"; TestHtmlAfterCompression(bookHtml, assertionsOnResultingHtmlString: html => { var htmlDom = XmlHtmlConverter.GetXmlDomFromHtml(html); AssertThatXmlIn.Dom(htmlDom) .HasSpecifiedNumberOfMatchesForXpath( "//html/head/link[@rel='stylesheet' and @href='Device-XMatter.css' and @type='text/css']", 1); AssertThatXmlIn.Dom(htmlDom) .HasNoMatchForXpath( "//html/head/link[@rel='stylesheet' and @href='Traditional-XMatter.css' and @type='text/css']"); }); } class StubProgress : IWebSocketProgress { public List<string> MessagesNotLocalized = new List<string>(); public void MessageWithoutLocalizing(string message, params object[] args) { MessagesNotLocalized.Add(message); } public List<string> ErrorsNotLocalized = new List<string>(); public void ErrorWithoutLocalizing(string message, params object[] args) { ErrorsNotLocalized.Add(message); } public void MessageWithParams(string id, string comment, string message, params object[] parameters) { MessagesNotLocalized.Add(string.Format(message, parameters)); } public void ErrorWithParams(string id, string comment, string message, params object[] parameters) { ErrorsNotLocalized.Add(string.Format(message, parameters)); } public void MessageWithColorAndParams(string id, string comment, string color, string message, params object[] parameters) { MessagesNotLocalized.Add("<span style='color:" + color + "'>" + string.Format(message, parameters) + "</span>"); } } class StubFontFinder : IFontFinder { public StubFontFinder() { FontsWeCantInstall = new HashSet<string>(); } public Dictionary<string, string[]> FilesForFont = new Dictionary<string, string[]>(); public IEnumerable<string> GetFilesForFont(string fontName) { string[] result; FilesForFont.TryGetValue(fontName, out result); if (result == null) result = new string[0]; return result; } public bool NoteFontsWeCantInstall { get; set; } public HashSet<string> FontsWeCantInstall { get; } public Dictionary<string, FontGroup> FontGroups = new Dictionary<string, FontGroup>(); public FontGroup GetGroupForFont(string fontName) { FontGroup result; FontGroups.TryGetValue(fontName, out result); return result; } } [Test] public void EmbedFonts_EmbedsExpectedFontsAndReportsOthers() { var bookHtml = @"<html><head> <link rel='stylesheet' href='Basic Book.css' type='text/css'></link> <link rel='stylesheet' href='Traditional-XMatter.css' type='text/css'></link> <link rel='stylesheet' href='CustomBookStyles.css' type='text/css'></link> <style type='text/css' title='userModifiedStyles'> /*<![CDATA[*/ .Times-style[lang='tpi'] { font-family: Times New Roman ! important; font-size: 12pt } /*]]>*/ </style> </head><body> <div class='bloom-page' id='guid1'></div> </body></html>"; var testBook = CreateBookWithPhysicalFile(bookHtml, bringBookUpToDate: false); var fontFileFinder = new StubFontFinder(); using (var tempFontFolder = new TemporaryFolder("EmbedFonts_EmbedsExpectedFontsAndReportsOthers")) { fontFileFinder.NoteFontsWeCantInstall = true; // Font called for in HTML var timesNewRomanFileName = "Times New Roman R.ttf"; var tnrPath = Path.Combine(tempFontFolder.Path, timesNewRomanFileName); File.WriteAllText(tnrPath, "This is phony TNR"); // Font called for in custom styles CSS var calibreFileName = "Calibre R.ttf"; var calibrePath = Path.Combine(tempFontFolder.Path, calibreFileName); File.WriteAllBytes(calibrePath, new byte[200008]); // we want something with a size greater than zero in megs fontFileFinder.FilesForFont["Times New Roman"] = new[] { tnrPath }; fontFileFinder.FilesForFont["Calibre"] = new [] { calibrePath }; fontFileFinder.FontsWeCantInstall.Add("NotAllowed"); // And "NotFound" just doesn't get a mention anywhere. var stubProgress = new StubProgress(); var customStylesPath = Path.Combine(testBook.FolderPath, "CustomBookStyles.css"); File.WriteAllText(customStylesPath, ".someStyle {font-family:Calibre} .otherStyle {font-family: NotFound} .yetAnother {font-family:NotAllowed}"); var tnrGroup = new FontGroup(); tnrGroup.Normal = tnrPath; fontFileFinder.FontGroups["Times New Roman"] = tnrGroup; var calibreGroup = new FontGroup(); calibreGroup.Normal = calibrePath; fontFileFinder.FontGroups["Calibre"] = calibreGroup; BloomReaderFileMaker.EmbedFonts(testBook, stubProgress, fontFileFinder); Assert.That(File.Exists(Path.Combine(testBook.FolderPath, timesNewRomanFileName))); Assert.That(File.Exists(Path.Combine(testBook.FolderPath, calibreFileName))); Assert.That(stubProgress.MessagesNotLocalized, Has.Member("Checking Times New Roman font: License OK for embedding.")); Assert.That(stubProgress.MessagesNotLocalized, Has.Member("<span style='color:blue'>Embedding font Times New Roman at a cost of 0.0 megs</span>")); Assert.That(stubProgress.MessagesNotLocalized, Has.Member("Checking Calibre font: License OK for embedding.")); Assert.That(stubProgress.MessagesNotLocalized, Has.Member("<span style='color:blue'>Embedding font Calibre at a cost of 0.2 megs</span>")); Assert.That(stubProgress.ErrorsNotLocalized, Has.Member("Checking NotAllowed font: License does not permit embedding.")); Assert.That(stubProgress.ErrorsNotLocalized, Has.Member("Substituting \"Andika New Basic\" for \"NotAllowed\"")); Assert.That(stubProgress.ErrorsNotLocalized, Has.Member("Checking NotFound font: No font found to embed.")); Assert.That(stubProgress.ErrorsNotLocalized, Has.Member("Substituting \"Andika New Basic\" for \"NotFound\"")); var fontSourceRulesPath = Path.Combine(testBook.FolderPath, "fonts.css"); var fontSource = RobustFile.ReadAllText(fontSourceRulesPath); // We're OK with these in either order. string lineTimes = "@font-face {font-family:'Times New Roman'; font-weight:normal; font-style:normal; src:url(Times New Roman R.ttf) format('opentype');}" + Environment.NewLine; string lineCalibre = "@font-face {font-family:'Calibre'; font-weight:normal; font-style:normal; src:url(Calibre R.ttf) format('opentype');}" + Environment.NewLine; Assert.That(fontSource, Is.EqualTo(lineTimes + lineCalibre).Or.EqualTo(lineCalibre + lineTimes)); AssertThatXmlIn.Dom(testBook.RawDom).HasSpecifiedNumberOfMatchesForXpath("//link[@href='fonts.css']", 1); } } private void TestHtmlAfterCompression(string originalBookHtml, Action<string> actionsOnFolderBeforeCompressing = null, Action<string> assertionsOnResultingHtmlString = null, Action<ZipFile> assertionsOnZipArchive = null, Action<ZipFile> assertionsOnRepeat = null) { var testBook = CreateBookWithPhysicalFile(originalBookHtml, bringBookUpToDate: true); var bookFileName = Path.GetFileName(testBook.GetPathHtmlFile()); actionsOnFolderBeforeCompressing?.Invoke(testBook.FolderPath); using (var bloomdTempFile = TempFile.WithFilenameInTempFolder(testBook.Title + BookCompressor.ExtensionForDeviceBloomBook)) { BookCompressor.CompressBookForDevice(bloomdTempFile.Path, testBook, _bookServer, Color.Azure, new NullWebSocketProgress()); var zip = new ZipFile(bloomdTempFile.Path); assertionsOnZipArchive?.Invoke(zip); var newHtml = GetEntryContents(zip, bookFileName); assertionsOnResultingHtmlString?.Invoke(newHtml); if (assertionsOnRepeat != null) { // compress it again! Used for checking important repeatable results using (var extraTempFile = TempFile.WithFilenameInTempFolder(testBook.Title + "2" + BookCompressor.ExtensionForDeviceBloomBook)) { BookCompressor.CompressBookForDevice(extraTempFile.Path, testBook, _bookServer, Color.Azure, new NullWebSocketProgress()); zip = new ZipFile(extraTempFile.Path); assertionsOnRepeat(zip); } } } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace api.securecall.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; } } }
// 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.InteropServices; using System.Runtime.CompilerServices; using static System.Buffers.Binary.BinaryPrimitives; namespace System { public static class TestHelpers { public static void Validate<T>(this Span<T> span, params T[] expected) where T : struct, IEquatable<T> { Assert.True(span.SequenceEqual(expected)); } public static void ValidateReferenceType<T>(this Span<T> span, params T[] expected) { Assert.Equal(span.Length, expected.Length); for (int i = 0; i < expected.Length; i++) { T actual = span[i]; Assert.Same(expected[i], actual); } T ignore; AssertThrows<IndexOutOfRangeException, T>(span, (_span) => ignore = _span[expected.Length]); } public delegate void AssertThrowsAction<T>(Span<T> span); // Cannot use standard Assert.Throws() when testing Span - Span and closures don't get along. public static void AssertThrows<E, T>(Span<T> span, AssertThrowsAction<T> action) where E:Exception { try { action(span); Assert.False(true, "Expected exception: " + typeof(E).GetType()); } catch (E) { } catch (Exception wrongException) { Assert.False(true, "Wrong exception thrown: Expected " + typeof(E).GetType() + ": Actual: " + wrongException.GetType()); } } // // The innocent looking construct: // // Assert.Throws<E>( () => new Span() ); // // generates a hidden box of the Span as the return value of the lambda. This makes the IL illegal and unloadable on // runtimes that enforce the actual Span rules (never mind that we expect never to reach the box instruction...) // // The workaround is to code it like this: // // Assert.Throws<E>( () => new Span().DontBox() ); // // which turns the lambda return type back to "void" and eliminates the troublesome box instruction. // public static void DontBox<T>(this Span<T> span) { // This space intentionally left blank. } public static void Validate<T>(this ReadOnlySpan<T> span, params T[] expected) where T : struct, IEquatable<T> { Assert.True(span.SequenceEqual(expected)); } public static void ValidateReferenceType<T>(this ReadOnlySpan<T> span, params T[] expected) { Assert.Equal(span.Length, expected.Length); for (int i = 0; i < expected.Length; i++) { T actual = span[i]; Assert.Same(expected[i], actual); } T ignore; AssertThrows<IndexOutOfRangeException, T>(span, (_span) => ignore = _span[expected.Length]); } public delegate void AssertThrowsActionReadOnly<T>(ReadOnlySpan<T> span); // Cannot use standard Assert.Throws() when testing Span - Span and closures don't get along. public static void AssertThrows<E, T>(ReadOnlySpan<T> span, AssertThrowsActionReadOnly<T> action) where E:Exception { try { action(span); Assert.False(true, "Expected exception: " + typeof(E).GetType()); } catch (E) { } catch (Exception wrongException) { Assert.False(true, "Wrong exception thrown: Expected " + typeof(E).GetType() + ": Actual: " + wrongException.GetType()); } } // // The innocent looking construct: // // Assert.Throws<E>( () => new Span() ); // // generates a hidden box of the Span as the return value of the lambda. This makes the IL illegal and unloadable on // runtimes that enforce the actual Span rules (never mind that we expect never to reach the box instruction...) // // The workaround is to code it like this: // // Assert.Throws<E>( () => new Span().DontBox() ); // // which turns the lambda return type back to "void" and eliminates the troublesome box instruction. // public static void DontBox<T>(this ReadOnlySpan<T> span) { // This space intentionally left blank. } public static void Validate<T>(this Memory<T> memory, params T[] expected) where T : struct, IEquatable<T> { Assert.True(memory.Span.SequenceEqual(expected)); } public static void ValidateReferenceType<T>(this Memory<T> memory, params T[] expected) { T[] bufferArray = memory.ToArray(); Assert.Equal(memory.Length, expected.Length); for (int i = 0; i < expected.Length; i++) { T actual = bufferArray[i]; Assert.Same(expected[i], actual); } } public static void Validate<T>(this ReadOnlyMemory<T> memory, params T[] expected) where T : struct, IEquatable<T> { Assert.True(memory.Span.SequenceEqual(expected)); } public static void ValidateReferenceType<T>(this ReadOnlyMemory<T> memory, params T[] expected) { T[] bufferArray = memory.ToArray(); Assert.Equal(memory.Length, expected.Length); for (int i = 0; i < expected.Length; i++) { T actual = bufferArray[i]; Assert.Same(expected[i], actual); } } public static void Validate<T>(Span<byte> span, T value) where T : struct { T read = ReadMachineEndian<T>(span); Assert.Equal(value, read); span.Clear(); } public static TestStructExplicit testExplicitStruct = new TestStructExplicit { S0 = short.MaxValue, I0 = int.MaxValue, L0 = long.MaxValue, US0 = ushort.MaxValue, UI0 = uint.MaxValue, UL0 = ulong.MaxValue, S1 = short.MinValue, I1 = int.MinValue, L1 = long.MinValue, US1 = ushort.MinValue, UI1 = uint.MinValue, UL1 = ulong.MinValue }; public static Span<byte> GetSpanBE() { Span<byte> spanBE = new byte[Unsafe.SizeOf<TestStructExplicit>()]; WriteInt16BigEndian(spanBE, testExplicitStruct.S0); WriteInt32BigEndian(spanBE.Slice(2), testExplicitStruct.I0); WriteInt64BigEndian(spanBE.Slice(6), testExplicitStruct.L0); WriteUInt16BigEndian(spanBE.Slice(14), testExplicitStruct.US0); WriteUInt32BigEndian(spanBE.Slice(16), testExplicitStruct.UI0); WriteUInt64BigEndian(spanBE.Slice(20), testExplicitStruct.UL0); WriteInt16BigEndian(spanBE.Slice(28), testExplicitStruct.S1); WriteInt32BigEndian(spanBE.Slice(30), testExplicitStruct.I1); WriteInt64BigEndian(spanBE.Slice(34), testExplicitStruct.L1); WriteUInt16BigEndian(spanBE.Slice(42), testExplicitStruct.US1); WriteUInt32BigEndian(spanBE.Slice(44), testExplicitStruct.UI1); WriteUInt64BigEndian(spanBE.Slice(48), testExplicitStruct.UL1); Assert.Equal(56, spanBE.Length); return spanBE; } public static Span<byte> GetSpanLE() { Span<byte> spanLE = new byte[Unsafe.SizeOf<TestStructExplicit>()]; WriteInt16LittleEndian(spanLE, testExplicitStruct.S0); WriteInt32LittleEndian(spanLE.Slice(2), testExplicitStruct.I0); WriteInt64LittleEndian( spanLE.Slice(6), testExplicitStruct.L0); WriteUInt16LittleEndian(spanLE.Slice(14), testExplicitStruct.US0); WriteUInt32LittleEndian(spanLE.Slice(16), testExplicitStruct.UI0); WriteUInt64LittleEndian(spanLE.Slice(20), testExplicitStruct.UL0); WriteInt16LittleEndian(spanLE.Slice(28), testExplicitStruct.S1); WriteInt32LittleEndian(spanLE.Slice(30), testExplicitStruct.I1); WriteInt64LittleEndian(spanLE.Slice(34), testExplicitStruct.L1); WriteUInt16LittleEndian(spanLE.Slice(42), testExplicitStruct.US1); WriteUInt32LittleEndian(spanLE.Slice(44), testExplicitStruct.UI1); WriteUInt64LittleEndian(spanLE.Slice(48), testExplicitStruct.UL1); Assert.Equal(56, spanLE.Length); return spanLE; } [StructLayout(LayoutKind.Explicit)] public struct TestStructExplicit { [FieldOffset(0)] public short S0; [FieldOffset(2)] public int I0; [FieldOffset(6)] public long L0; [FieldOffset(14)] public ushort US0; [FieldOffset(16)] public uint UI0; [FieldOffset(20)] public ulong UL0; [FieldOffset(28)] public short S1; [FieldOffset(30)] public int I1; [FieldOffset(34)] public long L1; [FieldOffset(42)] public ushort US1; [FieldOffset(44)] public uint UI1; [FieldOffset(48)] public ulong UL1; } [StructLayout(LayoutKind.Sequential)] public sealed class TestClass { private double _d; public char C0; public char C1; public char C2; public char C3; public char C4; } [StructLayout(LayoutKind.Sequential)] public struct TestValueTypeWithReference { public int I; public string S; } public enum TestEnum { e0, e1, e2, e3, e4, } } }
using System.Collections; using System.Globalization; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.CryptoPro; using Org.BouncyCastle.Asn1.Iana; using Org.BouncyCastle.Asn1.Kisa; using Org.BouncyCastle.Asn1.Nist; using Org.BouncyCastle.Asn1.Ntt; using Org.BouncyCastle.Asn1.Oiw; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Security { public sealed class GeneratorUtilities { private GeneratorUtilities() { } private static readonly IDictionary kgAlgorithms = Platform.CreateHashtable(); private static readonly IDictionary kpgAlgorithms = Platform.CreateHashtable(); private static readonly IDictionary defaultKeySizes = Platform.CreateHashtable(); static GeneratorUtilities() { // // key generators. // AddKgAlgorithm("AES", "AESWRAP"); AddKgAlgorithm("AES128", "2.16.840.1.101.3.4.2", NistObjectIdentifiers.IdAes128Cbc, NistObjectIdentifiers.IdAes128Cfb, NistObjectIdentifiers.IdAes128Ecb, NistObjectIdentifiers.IdAes128Ofb, NistObjectIdentifiers.IdAes128Wrap); AddKgAlgorithm("AES192", "2.16.840.1.101.3.4.22", NistObjectIdentifiers.IdAes192Cbc, NistObjectIdentifiers.IdAes192Cfb, NistObjectIdentifiers.IdAes192Ecb, NistObjectIdentifiers.IdAes192Ofb, NistObjectIdentifiers.IdAes192Wrap); AddKgAlgorithm("AES256", "2.16.840.1.101.3.4.42", NistObjectIdentifiers.IdAes256Cbc, NistObjectIdentifiers.IdAes256Cfb, NistObjectIdentifiers.IdAes256Ecb, NistObjectIdentifiers.IdAes256Ofb, NistObjectIdentifiers.IdAes256Wrap); AddKgAlgorithm("BLOWFISH", "1.3.6.1.4.1.3029.1.2"); AddKgAlgorithm("CAMELLIA", "CAMELLIAWRAP"); AddKgAlgorithm("CAMELLIA128", NttObjectIdentifiers.IdCamellia128Cbc, NttObjectIdentifiers.IdCamellia128Wrap); AddKgAlgorithm("CAMELLIA192", NttObjectIdentifiers.IdCamellia192Cbc, NttObjectIdentifiers.IdCamellia192Wrap); AddKgAlgorithm("CAMELLIA256", NttObjectIdentifiers.IdCamellia256Cbc, NttObjectIdentifiers.IdCamellia256Wrap); AddKgAlgorithm("CAST5", "1.2.840.113533.7.66.10"); AddKgAlgorithm("CAST6"); AddKgAlgorithm("DES", OiwObjectIdentifiers.DesCbc, OiwObjectIdentifiers.DesCfb, OiwObjectIdentifiers.DesEcb, OiwObjectIdentifiers.DesOfb); AddKgAlgorithm("DESEDE", "DESEDEWRAP", OiwObjectIdentifiers.DesEde); AddKgAlgorithm("DESEDE3", PkcsObjectIdentifiers.DesEde3Cbc, PkcsObjectIdentifiers.IdAlgCms3DesWrap); AddKgAlgorithm("GOST28147", "GOST", "GOST-28147", CryptoProObjectIdentifiers.GostR28147Cbc); AddKgAlgorithm("HC128"); AddKgAlgorithm("HC256"); AddKgAlgorithm("IDEA", "1.3.6.1.4.1.188.7.1.1.2"); AddKgAlgorithm("NOEKEON"); AddKgAlgorithm("RC2", PkcsObjectIdentifiers.RC2Cbc, PkcsObjectIdentifiers.IdAlgCmsRC2Wrap); AddKgAlgorithm("RC4", "ARC4", "1.2.840.113549.3.4"); AddKgAlgorithm("RC5", "RC5-32"); AddKgAlgorithm("RC5-64"); AddKgAlgorithm("RC6"); AddKgAlgorithm("RIJNDAEL"); AddKgAlgorithm("SALSA20"); AddKgAlgorithm("SEED", KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap, KisaObjectIdentifiers.IdSeedCbc); AddKgAlgorithm("SERPENT"); AddKgAlgorithm("SKIPJACK"); AddKgAlgorithm("TEA"); AddKgAlgorithm("TWOFISH"); AddKgAlgorithm("VMPC"); AddKgAlgorithm("VMPC-KSA3"); AddKgAlgorithm("XTEA"); // // HMac key generators // AddHMacKeyGenerator("MD2"); AddHMacKeyGenerator("MD4"); AddHMacKeyGenerator("MD5", IanaObjectIdentifiers.HmacMD5); AddHMacKeyGenerator("SHA1", PkcsObjectIdentifiers.IdHmacWithSha1, IanaObjectIdentifiers.HmacSha1); AddHMacKeyGenerator("SHA224", PkcsObjectIdentifiers.IdHmacWithSha224); AddHMacKeyGenerator("SHA256", PkcsObjectIdentifiers.IdHmacWithSha256); AddHMacKeyGenerator("SHA384", PkcsObjectIdentifiers.IdHmacWithSha384); AddHMacKeyGenerator("SHA512", PkcsObjectIdentifiers.IdHmacWithSha512); AddHMacKeyGenerator("RIPEMD128"); AddHMacKeyGenerator("RIPEMD160", IanaObjectIdentifiers.HmacRipeMD160); AddHMacKeyGenerator("TIGER", IanaObjectIdentifiers.HmacTiger); // // key pair generators. // AddKpgAlgorithm("DH", "DIFFIEHELLMAN"); AddKpgAlgorithm("DSA"); AddKpgAlgorithm("EC", // TODO Should this be an alias for ECDH? X9ObjectIdentifiers.DHSinglePassStdDHSha1KdfScheme); AddKpgAlgorithm("ECDH", "ECIES"); AddKpgAlgorithm("ECDHC"); AddKpgAlgorithm("ECMQV", X9ObjectIdentifiers.MqvSinglePassSha1KdfScheme); AddKpgAlgorithm("ECDSA"); AddKpgAlgorithm("ECGOST3410", "ECGOST-3410", "GOST-3410-2001"); AddKpgAlgorithm("ELGAMAL"); AddKpgAlgorithm("GOST3410", "GOST-3410", "GOST-3410-94"); AddKpgAlgorithm("RSA", "1.2.840.113549.1.1.1"); AddDefaultKeySizeEntries(64, "DES"); AddDefaultKeySizeEntries(80, "SKIPJACK"); AddDefaultKeySizeEntries(128, "AES128", "BLOWFISH", "CAMELLIA128", "CAST5", "DESEDE", "HC128", "HMACMD2", "HMACMD4", "HMACMD5", "HMACRIPEMD128", "IDEA", "NOEKEON", "RC2", "RC4", "RC5", "SALSA20", "SEED", "TEA", "XTEA", "VMPC", "VMPC-KSA3"); AddDefaultKeySizeEntries(160, "HMACRIPEMD160", "HMACSHA1"); AddDefaultKeySizeEntries(192, "AES", "AES192", "CAMELLIA192", "DESEDE3", "HMACTIGER", "RIJNDAEL", "SERPENT"); AddDefaultKeySizeEntries(224, "HMACSHA224"); AddDefaultKeySizeEntries(256, "AES256", "CAMELLIA", "CAMELLIA256", "CAST6", "GOST28147", "HC256", "HMACSHA256", "RC5-64", "RC6", "TWOFISH"); AddDefaultKeySizeEntries(384, "HMACSHA384"); AddDefaultKeySizeEntries(512, "HMACSHA512"); } private static void AddDefaultKeySizeEntries(int size, params string[] algorithms) { foreach (string algorithm in algorithms) { defaultKeySizes.Add(algorithm, size); } } private static void AddKgAlgorithm( string canonicalName, params object[] aliases) { kgAlgorithms[canonicalName] = canonicalName; foreach (object alias in aliases) { kgAlgorithms[alias.ToString()] = canonicalName; } } private static void AddKpgAlgorithm( string canonicalName, params object[] aliases) { kpgAlgorithms[canonicalName] = canonicalName; foreach (object alias in aliases) { kpgAlgorithms[alias.ToString()] = canonicalName; } } private static void AddHMacKeyGenerator( string algorithm, params object[] aliases) { string mainName = "HMAC" + algorithm; kgAlgorithms[mainName] = mainName; kgAlgorithms["HMAC-" + algorithm] = mainName; kgAlgorithms["HMAC/" + algorithm] = mainName; foreach (object alias in aliases) { kgAlgorithms[alias.ToString()] = mainName; } } // TODO Consider making this public internal static string GetCanonicalKeyGeneratorAlgorithm( string algorithm) { return (string) kgAlgorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)]; } // TODO Consider making this public internal static string GetCanonicalKeyPairGeneratorAlgorithm( string algorithm) { return (string) kpgAlgorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)]; } public static CipherKeyGenerator GetKeyGenerator( DerObjectIdentifier oid) { return GetKeyGenerator(oid.Id); } public static CipherKeyGenerator GetKeyGenerator( string algorithm) { string canonicalName = GetCanonicalKeyGeneratorAlgorithm(algorithm); if (canonicalName == null) throw new SecurityUtilityException("KeyGenerator " + algorithm + " not recognised."); int defaultKeySize = FindDefaultKeySize(canonicalName); if (defaultKeySize == -1) throw new SecurityUtilityException("KeyGenerator " + algorithm + " (" + canonicalName + ") not supported."); if (canonicalName == "DES") return new DesKeyGenerator(defaultKeySize); if (canonicalName == "DESEDE" || canonicalName == "DESEDE3") return new DesEdeKeyGenerator(defaultKeySize); return new CipherKeyGenerator(defaultKeySize); } public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator( DerObjectIdentifier oid) { return GetKeyPairGenerator(oid.Id); } public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator( string algorithm) { string canonicalName = GetCanonicalKeyPairGeneratorAlgorithm(algorithm); if (canonicalName == null) throw new SecurityUtilityException("KeyPairGenerator " + algorithm + " not recognised."); if (canonicalName == "DH") return new DHKeyPairGenerator(); if (canonicalName == "DSA") return new DsaKeyPairGenerator(); // "EC", "ECDH", "ECDHC", "ECDSA", "ECGOST3410", "ECMQV" if (canonicalName.StartsWith("EC")) return new ECKeyPairGenerator(canonicalName); if (canonicalName == "ELGAMAL") return new ElGamalKeyPairGenerator(); if (canonicalName == "GOST3410") return new Gost3410KeyPairGenerator(); if (canonicalName == "RSA") return new RsaKeyPairGenerator(); throw new SecurityUtilityException("KeyPairGenerator " + algorithm + " (" + canonicalName + ") not supported."); } internal static int GetDefaultKeySize( DerObjectIdentifier oid) { return GetDefaultKeySize(oid.Id); } internal static int GetDefaultKeySize( string algorithm) { string canonicalName = GetCanonicalKeyGeneratorAlgorithm(algorithm); if (canonicalName == null) throw new SecurityUtilityException("KeyGenerator " + algorithm + " not recognised."); int defaultKeySize = FindDefaultKeySize(canonicalName); if (defaultKeySize == -1) throw new SecurityUtilityException("KeyGenerator " + algorithm + " (" + canonicalName + ") not supported."); return defaultKeySize; } private static int FindDefaultKeySize( string canonicalName) { if (!defaultKeySizes.Contains(canonicalName)) return -1; return (int)defaultKeySizes[canonicalName]; } } }
//------------------------------------------------------------------------------ // <copyright file="SmtpNetworkElement.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net.Configuration { using System; using System.Configuration; using System.Net; using System.Net.Mail; using System.Reflection; using System.Security.Permissions; public sealed class SmtpNetworkElement : ConfigurationElement { public SmtpNetworkElement() { this.properties.Add(this.defaultCredentials); this.properties.Add(this.host); this.properties.Add(this.clientDomain); this.properties.Add(this.password); this.properties.Add(this.port); this.properties.Add(this.userName); this.properties.Add(this.targetName); this.properties.Add(this.enableSsl); } 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; PropertyInformation portPropertyInfo = ElementInformation.Properties[ConfigurationStrings.Port]; if (portPropertyInfo.ValueOrigin == PropertyValueOrigin.SetHere && (int)portPropertyInfo.Value != (int)portPropertyInfo.DefaultValue) { try { (new SmtpPermission(SmtpAccess.ConnectToUnrestrictedPort)).Demand(); } catch (Exception exception) { throw new ConfigurationErrorsException( SR.GetString(SR.net_config_property_permission, portPropertyInfo.Name), exception); } } } protected override ConfigurationPropertyCollection Properties { get { return this.properties; } } [ConfigurationProperty(ConfigurationStrings.DefaultCredentials, DefaultValue = false)] public bool DefaultCredentials { get { return (bool)this[this.defaultCredentials]; } set { this[this.defaultCredentials] = value; } } [ConfigurationProperty(ConfigurationStrings.Host)] public string Host { get { return (string)this[this.host]; } set { this[this.host] = value; } } [ConfigurationProperty(ConfigurationStrings.TargetName)] public string TargetName { get { return (string)this[this.targetName]; } set { this[this.targetName] = value; } } [ConfigurationProperty(ConfigurationStrings.ClientDomain)] public string ClientDomain { get { return (string)this[this.clientDomain]; } set { this[this.clientDomain] = value; } } [ConfigurationProperty(ConfigurationStrings.Password)] public string Password { get { return (string)this[this.password]; } set { this[this.password] = value; } } [ConfigurationProperty(ConfigurationStrings.Port, DefaultValue = 25)] public int Port { get { return (int)this[this.port]; } set { // this[this.port] = value; } } [ConfigurationProperty(ConfigurationStrings.UserName)] public string UserName { get { return (string)this[this.userName]; } set { this[this.userName] = value; } } [ConfigurationProperty(ConfigurationStrings.EnableSsl, DefaultValue = false)] public bool EnableSsl { get { return (bool)this[this.enableSsl]; } set { this[this.enableSsl] = value; } } // ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection(); readonly ConfigurationProperty defaultCredentials = new ConfigurationProperty(ConfigurationStrings.DefaultCredentials, typeof(bool), false, ConfigurationPropertyOptions.None); readonly ConfigurationProperty host = new ConfigurationProperty(ConfigurationStrings.Host, typeof(string), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty clientDomain = new ConfigurationProperty(ConfigurationStrings.ClientDomain, typeof(string), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty password = new ConfigurationProperty(ConfigurationStrings.Password, typeof(string), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty port = new ConfigurationProperty(ConfigurationStrings.Port, typeof(int), 25, null, new IntegerValidator(IPEndPoint.MinPort+1, IPEndPoint.MaxPort), ConfigurationPropertyOptions.None); readonly ConfigurationProperty userName = new ConfigurationProperty(ConfigurationStrings.UserName, typeof(string), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty targetName = new ConfigurationProperty(ConfigurationStrings.TargetName, typeof(string), null, ConfigurationPropertyOptions.None); readonly ConfigurationProperty enableSsl = new ConfigurationProperty(ConfigurationStrings.EnableSsl, typeof(bool), false, ConfigurationPropertyOptions.None); } internal sealed class SmtpNetworkElementInternal { internal SmtpNetworkElementInternal(SmtpNetworkElement element) { this.host = element.Host; this.port = element.Port; this.targetname = element.TargetName; this.clientDomain = element.ClientDomain; this.enableSsl = element.EnableSsl; if (element.DefaultCredentials) { this.credential = (NetworkCredential)CredentialCache.DefaultCredentials; } else if (element.UserName != null && element.UserName.Length > 0) { this.credential = new NetworkCredential(element.UserName, element.Password); } } internal NetworkCredential Credential { get { return this.credential; } } internal string Host { get { return this.host; } } internal string ClientDomain { get { return this.clientDomain; } } internal int Port { get { return this.port; } } internal string TargetName { get { return this.targetname; } } internal bool EnableSsl { get { return this.enableSsl; } } string targetname; string host; string clientDomain; int port; NetworkCredential credential = null; bool enableSsl; } }
/* * 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 Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Agent.AssetTransaction { public class AssetTransactionModule : IRegionModule, IAgentAssetTransactions { private readonly Dictionary<UUID, Scene> RegisteredScenes = new Dictionary<UUID, Scene>(); private bool m_dumpAssetsToFile = false; private Scene m_scene = null; [Obsolete] public Scene MyScene { get{ return m_scene;} } /// <summary> /// Each agent has its own singleton collection of transactions /// </summary> private Dictionary<UUID, AgentAssetTransactions> AgentTransactions = new Dictionary<UUID, AgentAssetTransactions>(); public AssetTransactionModule() { //m_log.Debug("creating AgentAssetTransactionModule"); } #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID)) { // m_log.Debug("initialising AgentAssetTransactionModule"); RegisteredScenes.Add(scene.RegionInfo.RegionID, scene); scene.RegisterModuleInterface<IAgentAssetTransactions>(this); scene.EventManager.OnNewClient += NewClient; } // EVIL HACK! // This needs killing! // if (m_scene == null) m_scene = scene; } public void PostInitialise() { } public void Close() { } public string Name { get { return "AgentTransactionModule"; } } public bool IsSharedModule { get { return true; } } #endregion public void NewClient(IClientAPI client) { client.OnAssetUploadRequest += HandleUDPUploadRequest; client.OnXferReceive += HandleXfer; } #region AgentAssetTransactions /// <summary> /// Get the collection of asset transactions for the given user. If one does not already exist, it /// is created. /// </summary> /// <param name="userID"></param> /// <returns></returns> private AgentAssetTransactions GetUserTransactions(UUID userID) { lock (AgentTransactions) { if (!AgentTransactions.ContainsKey(userID)) { AgentAssetTransactions transactions = new AgentAssetTransactions(userID, this, m_dumpAssetsToFile); AgentTransactions.Add(userID, transactions); } return AgentTransactions[userID]; } } /// <summary> /// Remove the given agent asset transactions. This should be called when a client is departing /// from a scene (and hence won't be making any more transactions here). /// </summary> /// <param name="userID"></param> public void RemoveAgentAssetTransactions(UUID userID) { // m_log.DebugFormat("Removing agent asset transactions structure for agent {0}", userID); lock (AgentTransactions) { AgentTransactions.Remove(userID); } } /// <summary> /// Create an inventory item from data that has been received through a transaction. /// /// This is called when new clothing or body parts are created. It may also be called in other /// situations. /// </summary> /// <param name="remoteClient"></param> /// <param name="transactionID"></param> /// <param name="folderID"></param> /// <param name="callbackID"></param> /// <param name="description"></param> /// <param name="name"></param> /// <param name="invType"></param> /// <param name="type"></param> /// <param name="wearableType"></param> /// <param name="nextOwnerMask"></param> public void HandleItemCreationFromTransaction(IClientAPI remoteClient, UUID transactionID, UUID folderID, uint callbackID, string description, string name, sbyte invType, sbyte type, byte wearableType, uint nextOwnerMask) { // m_log.DebugFormat( // "[TRANSACTIONS MANAGER] Called HandleItemCreationFromTransaction with item {0}", name); AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId); transactions.RequestCreateInventoryItem( remoteClient, transactionID, folderID, callbackID, description, name, invType, type, wearableType, nextOwnerMask); } /// <summary> /// Update an inventory item with data that has been received through a transaction. /// /// This is called when clothing or body parts are updated (for instance, with new textures or /// colours). It may also be called in other situations. /// </summary> /// <param name="remoteClient"></param> /// <param name="transactionID"></param> /// <param name="item"></param> public void HandleItemUpdateFromTransaction(IClientAPI remoteClient, UUID transactionID, InventoryItemBase item) { // m_log.DebugFormat( // "[TRANSACTIONS MANAGER] Called HandleItemUpdateFromTransaction with item {0}", // item.Name); AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId); transactions.RequestUpdateInventoryItem(remoteClient, transactionID, item); } /// <summary> /// Update a task inventory item with data that has been received through a transaction. /// /// This is currently called when, for instance, a notecard in a prim is saved. The data is sent /// up through a single AssetUploadRequest. A subsequent UpdateTaskInventory then references the transaction /// and comes through this method. /// </summary> /// <param name="remoteClient"></param> /// <param name="transactionID"></param> /// <param name="item"></param> public void HandleTaskItemUpdateFromTransaction( IClientAPI remoteClient, SceneObjectPart part, UUID transactionID, TaskInventoryItem item) { // m_log.DebugFormat( // "[TRANSACTIONS MANAGER] Called HandleTaskItemUpdateFromTransaction with item {0}", // item.Name); AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId); transactions.RequestUpdateTaskInventoryItem(remoteClient, part, transactionID, item); } /// <summary> /// Request that a client (agent) begin an asset transfer. /// </summary> /// <param name="remoteClient"></param> /// <param name="assetID"></param> /// <param name="transaction"></param> /// <param name="type"></param> /// <param name="data"></param></param> /// <param name="tempFile"></param> public void HandleUDPUploadRequest(IClientAPI remoteClient, UUID assetID, UUID transaction, sbyte type, byte[] data, bool storeLocal, bool tempFile) { //m_log.Debug("HandleUDPUploadRequest - assetID: " + assetID.ToString() + " transaction: " + transaction.ToString() + " type: " + type.ToString() + " storelocal: " + storeLocal + " tempFile: " + tempFile); if (((AssetType)type == AssetType.Texture || (AssetType)type == AssetType.Sound || (AssetType)type == AssetType.TextureTGA || (AssetType)type == AssetType.Animation) && tempFile == false) { Scene scene = (Scene)remoteClient.Scene; IMoneyModule mm = scene.RequestModuleInterface<IMoneyModule>(); if (mm != null) { if (!mm.UploadCovered(remoteClient)) { remoteClient.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false); return; } } } //m_log.Debug("asset upload of " + assetID); AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId); AssetXferUploader uploader = transactions.RequestXferUploader(transaction); if (uploader != null) { uploader.Initialise(remoteClient, assetID, transaction, type, data, storeLocal, tempFile); } } /// <summary> /// Handle asset transfer data packets received in response to the asset upload request in /// HandleUDPUploadRequest() /// </summary> /// <param name="remoteClient"></param> /// <param name="xferID"></param> /// <param name="packetID"></param> /// <param name="data"></param> public void HandleXfer(IClientAPI remoteClient, ulong xferID, uint packetID, byte[] data) { //m_log.Debug("xferID: " + xferID + " packetID: " + packetID + " data!"); AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId); transactions.HandleXfer(xferID, packetID, data); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Threading.Tests { public static class ReaderWriterLockTests { private const int UnexpectedTimeoutMilliseconds = ThreadTestHelpers.UnexpectedTimeoutMilliseconds; private const int TimeoutExceptionHResult = unchecked((int)0x800705B4); // ERROR_TIMEOUT private const int NotOwnerExceptionHResult = 0x120; // this is not an HResult, see ReaderWriterLock.GetNotOwnerException private const int InvalidLockCookieExceptionHResult = unchecked((int)0x80070057); // E_INVALIDARG [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // desktop framework treats the timeout as an unsigned value public static void InvalidTimeoutTest_ChangedInDotNetCore() { var rwl = new ReaderWriterLock(); Assert.Throws<ArgumentOutOfRangeException>(() => rwl.AcquireReaderLock(-2)); Assert.Throws<ArgumentOutOfRangeException>(() => rwl.AcquireReaderLock(TimeSpan.FromMilliseconds(-2))); Assert.Throws<ArgumentOutOfRangeException>( () => rwl.AcquireReaderLock(TimeSpan.FromMilliseconds((uint)int.MaxValue + 1))); Assert.Throws<ArgumentOutOfRangeException>(() => rwl.AcquireWriterLock(-2)); Assert.Throws<ArgumentOutOfRangeException>(() => rwl.AcquireWriterLock(TimeSpan.FromMilliseconds(-2))); Assert.Throws<ArgumentOutOfRangeException>( () => rwl.AcquireWriterLock(TimeSpan.FromMilliseconds((uint)int.MaxValue + 1))); Assert.Throws<ArgumentOutOfRangeException>(() => rwl.UpgradeToWriterLock(-2)); Assert.Throws<ArgumentOutOfRangeException>(() => rwl.UpgradeToWriterLock(TimeSpan.FromMilliseconds(-2))); Assert.Throws<ArgumentOutOfRangeException>( () => rwl.UpgradeToWriterLock(TimeSpan.FromMilliseconds((uint)int.MaxValue + 1))); } [Fact] public static void NotOwnerTest() { var trwl = new TestReaderWriterLock(); trwl.ReleaseReaderLock(NotOwnerExceptionHResult); trwl.ReleaseWriterLock(NotOwnerExceptionHResult); trwl.DowngradeFromWriterLock(new TestLockCookie(), NotOwnerExceptionHResult); { trwl.AcquireReaderLock(); trwl.ReleaseWriterLock(NotOwnerExceptionHResult); TestLockCookie tlc = trwl.UpgradeToWriterLock(); TestLockCookie tlc2 = tlc.Clone(); trwl.DowngradeFromWriterLock(tlc); // tlc is invalid, tlc2 is valid trwl.DowngradeFromWriterLock(tlc2, NotOwnerExceptionHResult); trwl.ReleaseReaderLock(); } trwl.Dispose(); } [Fact] public static void ShouldNotBeOwnerForRestoreLockTest() { var trwl = new TestReaderWriterLock(); trwl.AcquireReaderLock(); TestLockCookie restoreReadLockTlc = trwl.ReleaseLock(); trwl.AcquireWriterLock(); TestLockCookie restoreWriteLockTlc = trwl.ReleaseLock(); Action verifyCannotRestore = () => { Assert.Throws<SynchronizationLockException>(() => trwl.RestoreLock(restoreReadLockTlc)); Assert.Throws<SynchronizationLockException>(() => trwl.RestoreLock(restoreWriteLockTlc)); }; trwl.AcquireReaderLock(); verifyCannotRestore(); trwl.ReleaseReaderLock(); trwl.AcquireWriterLock(); verifyCannotRestore(); trwl.ReleaseWriterLock(); trwl.Dispose(); } [Fact] public static void InvalidLockCookieTest() { // Invalid lock cookie created by using one up with Upgrade/Downgrade var trwl = new TestReaderWriterLock(); TestLockCookie tlc = trwl.UpgradeToWriterLock(); trwl.DowngradeFromWriterLock(tlc); trwl.AcquireWriterLock(); trwl.DowngradeFromWriterLock(tlc, InvalidLockCookieExceptionHResult); trwl.ReleaseWriterLock(); trwl.RestoreLock(tlc, InvalidLockCookieExceptionHResult); // Invalid lock cookie created by using one up with Release/Restore tlc = trwl.ReleaseLock(); trwl.RestoreLock(tlc); trwl.AcquireWriterLock(); trwl.DowngradeFromWriterLock(tlc, InvalidLockCookieExceptionHResult); trwl.ReleaseWriterLock(); trwl.RestoreLock(tlc, InvalidLockCookieExceptionHResult); // Lock cookie owned by another thread ThreadTestHelpers.RunTestInBackgroundThread(() => { TestLockCookie tlc2 = trwl.UpgradeToWriterLock(); tlc = tlc2.Clone(); trwl.DowngradeFromWriterLock(tlc2); }); trwl.AcquireWriterLock(); trwl.DowngradeFromWriterLock(tlc, InvalidLockCookieExceptionHResult); trwl.ReleaseWriterLock(); trwl.RestoreLock(tlc, InvalidLockCookieExceptionHResult); trwl.Dispose(); } [Fact] public static void BasicLockTest() { var trwl = new TestReaderWriterLock(); TestLockCookie tlc; var threadReady = new AutoResetEvent(false); var continueThread = new AutoResetEvent(false); Action checkForThreadErrors, waitForThread; Thread t = ThreadTestHelpers.CreateGuardedThread(out checkForThreadErrors, out waitForThread, () => { TestLockCookie tlc2; Action switchToMainThread = () => { threadReady.Set(); continueThread.CheckedWait(); }; switchToMainThread(); // Multiple readers from multiple threads { trwl.AcquireReaderLock(); trwl.AcquireReaderLock(); switchToMainThread(); trwl.ReleaseReaderLock(); switchToMainThread(); trwl.ReleaseReaderLock(); switchToMainThread(); trwl.AcquireReaderLock(); trwl.ReleaseReaderLock(); switchToMainThread(); } // What can be done when a read lock is held { trwl.AcquireReaderLock(); switchToMainThread(); // Any thread can take a read lock trwl.AcquireReaderLock(); trwl.ReleaseReaderLock(); switchToMainThread(); // No thread can take a write lock trwl.AcquireWriterLock(TimeoutExceptionHResult); trwl.AcquireReaderLock(); trwl.UpgradeToWriterLock(TimeoutExceptionHResult); trwl.ReleaseReaderLock(); switchToMainThread(); trwl.ReleaseReaderLock(); switchToMainThread(); // Owning thread releases read lock when upgrading trwl.AcquireWriterLock(); trwl.ReleaseWriterLock(); switchToMainThread(); // Owning thread cannot upgrade if there are other readers or writers trwl.AcquireReaderLock(); switchToMainThread(); trwl.ReleaseReaderLock(); trwl.AcquireWriterLock(); switchToMainThread(); trwl.ReleaseWriterLock(); switchToMainThread(); } // What can be done when a write lock is held { // Write lock acquired through AcquireWriteLock is exclusive trwl.AcquireWriterLock(); switchToMainThread(); trwl.ReleaseWriterLock(); switchToMainThread(); // Write lock acquired through upgrading is also exclusive trwl.AcquireReaderLock(); tlc2 = trwl.UpgradeToWriterLock(); switchToMainThread(); trwl.DowngradeFromWriterLock(tlc2); trwl.ReleaseReaderLock(); switchToMainThread(); // Write lock acquired through restore is also exclusive trwl.AcquireWriterLock(); tlc = trwl.ReleaseLock(); trwl.RestoreLock(tlc); switchToMainThread(); trwl.ReleaseWriterLock(); switchToMainThread(); } }); t.IsBackground = true; t.Start(); Action beginSwitchToBackgroundThread = () => continueThread.Set(); Action endSwitchToBackgroundThread = () => { try { threadReady.CheckedWait(); } finally { checkForThreadErrors(); } }; Action switchToBackgroundThread = () => { beginSwitchToBackgroundThread(); endSwitchToBackgroundThread(); }; endSwitchToBackgroundThread(); // Multiple readers from muliple threads { trwl.AcquireReaderLock(); trwl.AcquireReaderLock(); switchToBackgroundThread(); // AcquireReaderLock * 2 trwl.ReleaseReaderLock(); switchToBackgroundThread(); // ReleaseReaderLock // Release/restore the read lock while a read lock is held by another thread tlc = trwl.ReleaseLock(); trwl.RestoreLock(tlc); switchToBackgroundThread(); // ReleaseReaderLock // Downgrade to read lock allows another thread to acquire read lock tlc = trwl.UpgradeToWriterLock(); trwl.DowngradeFromWriterLock(tlc); switchToBackgroundThread(); // AcquireReaderLock, ReleaseReaderLock trwl.ReleaseReaderLock(); } // What can be done when a read lock is held { switchToBackgroundThread(); // AcquireReaderLock { // Any thread can take a read lock trwl.AcquireReaderLock(); trwl.ReleaseReaderLock(); switchToBackgroundThread(); // same as above // No thread can take a write lock trwl.AcquireWriterLock(TimeoutExceptionHResult); trwl.AcquireReaderLock(); trwl.UpgradeToWriterLock(TimeoutExceptionHResult); switchToBackgroundThread(); // same as above trwl.ReleaseReaderLock(); // Other threads cannot upgrade to a write lock, but the owning thread can trwl.AcquireReaderLock(); trwl.UpgradeToWriterLock(TimeoutExceptionHResult); trwl.ReleaseReaderLock(); } switchToBackgroundThread(); // ReleaseReaderLock // Owning thread releases read lock when upgrading trwl.AcquireReaderLock(); beginSwitchToBackgroundThread(); // AcquireWriterLock: background thread gets blocked trwl.UpgradeToWriterLock(); // unblocks background thread: ReleaseWriterLock trwl.ReleaseWriterLock(); endSwitchToBackgroundThread(); // Owning thread cannot upgrade if there are other readers or writers trwl.AcquireReaderLock(); switchToBackgroundThread(); // AcquireReaderLock trwl.UpgradeToWriterLock(TimeoutExceptionHResult); trwl.ReleaseReaderLock(); switchToBackgroundThread(); // ReleaseReaderLock, AcquireWriterLock trwl.UpgradeToWriterLock(TimeoutExceptionHResult); switchToBackgroundThread(); // ReleaseWriterLock } // What can be done when a write lock is held { trwl.AcquireWriterLock(); TestLockCookie restoreToWriteLockTlc = trwl.ReleaseLock(); Action verifyCannotAcquireLock = () => { trwl.AcquireReaderLock(TimeoutExceptionHResult); trwl.AcquireWriterLock(TimeoutExceptionHResult); trwl.UpgradeToWriterLock(TimeoutExceptionHResult); }; Action verifyCanAcquireLock = () => { trwl.AcquireReaderLock(); tlc = trwl.UpgradeToWriterLock(); trwl.DowngradeFromWriterLock(tlc); trwl.ReleaseReaderLock(); trwl.AcquireWriterLock(); trwl.ReleaseWriterLock(); trwl.RestoreLock(restoreToWriteLockTlc.Clone()); trwl.ReleaseWriterLock(); }; // Write lock acquired through AcquireWriteLock is exclusive switchToBackgroundThread(); // AcquireWriterLock verifyCannotAcquireLock(); switchToBackgroundThread(); // ReleaseWriterLock verifyCanAcquireLock(); // Write lock acquired through upgrading is also exclusive switchToBackgroundThread(); // AcquireReaderLock, UpgradeToWriterLock verifyCannotAcquireLock(); switchToBackgroundThread(); // DowngradeFromWriterLock, ReleaseReaderLock verifyCanAcquireLock(); // Write lock acquired through restore is also exclusive switchToBackgroundThread(); // AcquireWriterLock, ReleaseLock, RestoreLock verifyCannotAcquireLock(); switchToBackgroundThread(); // ReleaseWriterLock verifyCanAcquireLock(); } beginSwitchToBackgroundThread(); waitForThread(); trwl.Dispose(); } [Fact] public static void SingleThreadLockOwnerMiscellaneousTest() { var trwl = new TestReaderWriterLock(); TestLockCookie tlc, tlc2; // Read lock owner can upgrade to a write lock trwl.AcquireReaderLock(); tlc = trwl.UpgradeToWriterLock(); trwl.DowngradeFromWriterLock(tlc); trwl.ReleaseReaderLock(); // Can acquire and release a recursive write lock in multiple ways trwl.AcquireWriterLock(); trwl.AcquireWriterLock(); trwl.ReleaseWriterLock(); trwl.AcquireReaderLock(); trwl.ReleaseReaderLock(); trwl.UpgradeToWriterLock(); trwl.ReleaseWriterLock(); trwl.ReleaseWriterLock(); // Typical upgrade with single read lock trwl.AcquireReaderLock(); tlc = trwl.UpgradeToWriterLock(); trwl.DowngradeFromWriterLock(tlc); trwl.ReleaseReaderLock(); // Write lock can be taken with UpgradeToWriterLock when no read lock is held, and with that lock cookie, // DowngradeFromWriterLock does not acquire a read lock tlc = trwl.UpgradeToWriterLock(); tlc2 = trwl.UpgradeToWriterLock(); trwl.DowngradeFromWriterLock(tlc2); trwl.DowngradeFromWriterLock(tlc); // Upgrading from recursive read lock downgrades back to recursive read lock trwl.AcquireReaderLock(); trwl.AcquireReaderLock(); tlc = trwl.UpgradeToWriterLock(); trwl.DowngradeFromWriterLock(tlc); trwl.ReleaseReaderLock(); trwl.ReleaseReaderLock(); // Can downgrade from any write lock level, and to any read lock level with lock cookie from ReleaseLock trwl.AcquireReaderLock(); trwl.AcquireReaderLock(); tlc = trwl.ReleaseLock(); trwl.AcquireWriterLock(); trwl.AcquireWriterLock(); trwl.DowngradeFromWriterLock(tlc); trwl.ReleaseReaderLock(); trwl.ReleaseReaderLock(); // Typical release/restore { trwl.AcquireReaderLock(); trwl.AcquireReaderLock(); tlc = trwl.ReleaseLock(); trwl.RestoreLock(tlc); trwl.ReleaseReaderLock(); trwl.ReleaseReaderLock(); trwl.AcquireWriterLock(); trwl.AcquireWriterLock(); tlc = trwl.ReleaseLock(); trwl.RestoreLock(tlc); trwl.ReleaseWriterLock(); trwl.ReleaseWriterLock(); } // Can restore to any read lock level with lock cookie from UpgradeToWriterLock trwl.AcquireReaderLock(); trwl.AcquireReaderLock(); tlc = trwl.UpgradeToWriterLock(); trwl.ReleaseWriterLock(); trwl.RestoreLock(tlc); trwl.ReleaseReaderLock(); trwl.ReleaseReaderLock(); trwl.Dispose(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void DowngradeQuirks_ChangedInDotNetCore() { var trwl = new TestReaderWriterLock(); TestLockCookie tlc; // Downgrade quirk when downgrading from a state where multiple recursive write locks are held, when the lock cookie // was obtained from a state where: // - No lock was held // - When any number of recursive write locks are held // The expectation in both cases is that a downgrade respects the lock cookie and restores the write lock recursion // level to the point indicated by the lock cookie. { // Lock cookie obtained when no lock is held tlc = trwl.UpgradeToWriterLock(); trwl.AcquireWriterLock(); trwl.DowngradeFromWriterLock(tlc); trwl.VerifyIsReaderLockHeld(false); trwl.VerifyIsWriterLockHeld(false); // Lock cookie obtained when write locks are held trwl.AcquireWriterLock(); tlc = trwl.UpgradeToWriterLock(); trwl.AcquireWriterLock(); trwl.DowngradeFromWriterLock(tlc); trwl.VerifyIsReaderLockHeld(false); trwl.VerifyIsWriterLockHeld(true); trwl.ReleaseWriterLock(); trwl.VerifyIsWriterLockHeld(false); } // Cannot downgrade to a recursive write lock level greater than or equal to the current trwl.AcquireWriterLock(); trwl.AcquireWriterLock(); tlc = trwl.UpgradeToWriterLock(); trwl.ReleaseWriterLock(); trwl.DowngradeFromWriterLock(tlc, InvalidLockCookieExceptionHResult); trwl.ReleaseWriterLock(); trwl.DowngradeFromWriterLock(tlc, InvalidLockCookieExceptionHResult); trwl.ReleaseWriterLock(); trwl.VerifyIsReaderLockHeld(false); trwl.VerifyIsWriterLockHeld(false); trwl.Dispose(); } [Fact] public static void WaitingReadersTest() { var trwl = new TestReaderWriterLock(); trwl.AcquireWriterLock(); Action acquireReleaseReaderLock = () => { trwl.AcquireReaderLock(); trwl.ReleaseReaderLock(); }; Action waitForWaitingReader1, waitForWaitingReader2; Thread waitingReader1 = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingReader1, acquireReleaseReaderLock); Thread waitingReader2 = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingReader2, acquireReleaseReaderLock); waitingReader1.IsBackground = true; waitingReader2.IsBackground = true; waitingReader1.Start(); waitingReader2.Start(); ThreadTestHelpers.WaitForCondition(() => (waitingReader1.ThreadState & ThreadState.WaitSleepJoin) != 0); ThreadTestHelpers.WaitForCondition(() => (waitingReader2.ThreadState & ThreadState.WaitSleepJoin) != 0); // Releasing the write lock releases all waiting readers trwl.ReleaseWriterLock(); waitForWaitingReader1(); waitForWaitingReader2(); trwl.Dispose(); } [Fact] public static void WaitingWritersTest() { var trwl = new TestReaderWriterLock(); trwl.AcquireReaderLock(); Action acquireReleaseWriterLock = () => { trwl.AcquireWriterLock(); trwl.ReleaseWriterLock(); }; Action waitForWaitingWriter1, waitForWaitingWriter2; Thread waitingWriter1 = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingWriter1, acquireReleaseWriterLock); Thread waitingWriter2 = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingWriter2, acquireReleaseWriterLock); waitingWriter1.IsBackground = true; waitingWriter2.IsBackground = true; waitingWriter1.Start(); waitingWriter2.Start(); ThreadTestHelpers.WaitForCondition(() => (waitingWriter1.ThreadState & ThreadState.WaitSleepJoin) != 0); ThreadTestHelpers.WaitForCondition(() => (waitingWriter2.ThreadState & ThreadState.WaitSleepJoin) != 0); // Releasing the read lock releases a waiting writer, that writer releases its write lock, in turn releasing the // other writer trwl.ReleaseReaderLock(); waitForWaitingWriter1(); waitForWaitingWriter2(); trwl.Dispose(); } [Fact] public static void ReadersWaitingOnWaitingWriterTest() { var trwl = new TestReaderWriterLock(); trwl.AcquireReaderLock(); var waitingWriterReady = new AutoResetEvent(false); var continueWaitingWriter = new AutoResetEvent(false); Action waitForWaitingWriter; Thread waitingWriter = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingWriter, () => { trwl.AcquireWriterLock(); waitingWriterReady.Set(); continueWaitingWriter.CheckedWait(); trwl.ReleaseWriterLock(); }); waitingWriter.IsBackground = true; waitingWriter.Start(); ThreadTestHelpers.WaitForCondition(() => (waitingWriter.ThreadState & ThreadState.WaitSleepJoin) != 0); Action acquireReleaseReaderLock = () => { trwl.AcquireReaderLock(); trwl.ReleaseReaderLock(); }; Action waitForWaitingReader1, waitForWaitingReader2; Thread waitingReader1 = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingReader1, acquireReleaseReaderLock); Thread waitingReader2 = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingReader2, acquireReleaseReaderLock); waitingReader1.IsBackground = true; waitingReader2.IsBackground = true; waitingReader1.Start(); waitingReader2.Start(); ThreadTestHelpers.WaitForCondition(() => (waitingReader1.ThreadState & ThreadState.WaitSleepJoin) != 0); ThreadTestHelpers.WaitForCondition(() => (waitingReader2.ThreadState & ThreadState.WaitSleepJoin) != 0); // Releasing the read lock releases the waiting writer trwl.ReleaseReaderLock(); waitingWriterReady.CheckedWait(); // Releasing the now-writer's write lock releases all waiting readers continueWaitingWriter.Set(); waitForWaitingWriter(); waitForWaitingReader1(); waitForWaitingReader2(); trwl.Dispose(); } [Fact] public static void ReadersWaitingOnWaitingUpgraderTest() { var trwl = new TestReaderWriterLock(); trwl.AcquireReaderLock(); var waitingUpgraderReady = new AutoResetEvent(false); var continueWaitingUpgrader = new AutoResetEvent(false); Action waitForWaitingUpgrader; Thread waitingUpgrader = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingUpgrader, () => { trwl.AcquireReaderLock(); trwl.UpgradeToWriterLock(); waitingUpgraderReady.Set(); continueWaitingUpgrader.CheckedWait(); trwl.ReleaseWriterLock(); trwl.VerifyIsReaderLockHeld(false); trwl.VerifyIsWriterLockHeld(false); }); waitingUpgrader.IsBackground = true; waitingUpgrader.Start(); ThreadTestHelpers.WaitForCondition(() => (waitingUpgrader.ThreadState & ThreadState.WaitSleepJoin) != 0); Action acquireReleaseReaderLock = () => { trwl.AcquireReaderLock(); trwl.ReleaseReaderLock(); }; Action waitForWaitingReader1, waitForWaitingReader2; Thread waitingReader1 = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingReader1, acquireReleaseReaderLock); Thread waitingReader2 = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingReader2, acquireReleaseReaderLock); waitingReader1.IsBackground = true; waitingReader2.IsBackground = true; waitingReader1.Start(); waitingReader2.Start(); ThreadTestHelpers.WaitForCondition(() => (waitingReader1.ThreadState & ThreadState.WaitSleepJoin) != 0); ThreadTestHelpers.WaitForCondition(() => (waitingReader2.ThreadState & ThreadState.WaitSleepJoin) != 0); // Releasing the read lock releases the waiting upgrader trwl.ReleaseReaderLock(); waitingUpgraderReady.CheckedWait(); // Releasing the now-writer's write lock releases all waiting readers continueWaitingUpgrader.Set(); waitForWaitingUpgrader(); waitForWaitingReader1(); waitForWaitingReader2(); trwl.Dispose(); } [Fact] public static void WaitingUpgradersTest() { var trwl = new TestReaderWriterLock(); trwl.AcquireReaderLock(); var waitingUpgrader1AcquiredReadLock = new ManualResetEvent(false); Action waitForWaitingUpgrader1, waitForWaitingUpgrader2, waitForWaitingUpgrader3; Thread waitingUpgrader1 = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingUpgrader1, () => { trwl.AcquireReaderLock(); waitingUpgrader1AcquiredReadLock.Set(); TestLockCookie tlc = trwl.UpgradeToWriterLock(); trwl.DowngradeFromWriterLock(tlc); trwl.ReleaseReaderLock(); }); Action upgradeDowngradeLock = () => { TestLockCookie tlc = trwl.UpgradeToWriterLock(); trwl.DowngradeFromWriterLock(tlc); }; Thread waitingUpgrader2 = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingUpgrader2, upgradeDowngradeLock); Thread waitingUpgrader3 = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingUpgrader3, upgradeDowngradeLock); waitingUpgrader1.IsBackground = true; waitingUpgrader2.IsBackground = true; waitingUpgrader1.Start(); waitingUpgrader1AcquiredReadLock.CheckedWait(); waitingUpgrader2.Start(); waitingUpgrader3.Start(); ThreadTestHelpers.WaitForCondition(() => (waitingUpgrader1.ThreadState & ThreadState.WaitSleepJoin) != 0); ThreadTestHelpers.WaitForCondition(() => (waitingUpgrader2.ThreadState & ThreadState.WaitSleepJoin) != 0); ThreadTestHelpers.WaitForCondition(() => (waitingUpgrader3.ThreadState & ThreadState.WaitSleepJoin) != 0); // Releasing the read lock releases a waiting upgrader, that writer downgrades its write lock, in turn releasing the // other upgrader, and so on trwl.ReleaseReaderLock(); waitForWaitingUpgrader1(); waitForWaitingUpgrader2(); waitForWaitingUpgrader3(); trwl.Dispose(); } [Fact] public static void AtomicRecursiveReaderTest() { var trwl = new TestReaderWriterLock(); trwl.AcquireReaderLock(); Action waitForWaitingWriter; Thread waitingWriter = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingWriter, () => { trwl.AcquireWriterLock(); trwl.ReleaseWriterLock(); }); waitingWriter.Start(); ThreadTestHelpers.WaitForCondition(() => (waitingWriter.ThreadState & ThreadState.WaitSleepJoin) != 0); // Acquire a recursive read lock successfully while there is a waiting writer trwl.AcquireReaderLock(); // Releasing both read locks releases the waiting writer trwl.ReleaseLock(); waitForWaitingWriter(); trwl.Dispose(); } [Fact] public static void AtomicDowngradeTest() { var trwl = new TestReaderWriterLock(); trwl.AcquireReaderLock(); TestLockCookie tlc = trwl.UpgradeToWriterLock(); Action waitForWaitingWriter; Thread waitingWriter = ThreadTestHelpers.CreateGuardedThread(out waitForWaitingWriter, () => { trwl.AcquireWriterLock(); trwl.ReleaseWriterLock(); }); waitingWriter.Start(); ThreadTestHelpers.WaitForCondition(() => (waitingWriter.ThreadState & ThreadState.WaitSleepJoin) != 0); // Downgrade to a read lock successfully while there is a waiting writer trwl.DowngradeFromWriterLock(tlc); // Releasing the read lock releases the waiting writer trwl.ReleaseReaderLock(); waitForWaitingWriter(); trwl.Dispose(); } [Fact] public static void OverflowOnExcessiveNestedReaderLock() { ReaderWriterLock rwl = new ReaderWriterLock(); for (int i = 0; i != ushort.MaxValue; ++i) { rwl.AcquireReaderLock(0); } Assert.Throws<OverflowException>(() => rwl.AcquireReaderLock(0)); } [Fact] public static void OverflowOnExcessiveNestedWriterLock() { ReaderWriterLock rwl = new ReaderWriterLock(); for (int i = 0; i != ushort.MaxValue; ++i) { rwl.AcquireWriterLock(0); } Assert.Throws<OverflowException>(() => rwl.AcquireWriterLock(0)); } private class TestReaderWriterLock : IDisposable { private const int InvalidThreadID = -1; [ThreadStatic] private static Dictionary<TestReaderWriterLock, int> t_readerLevels; private readonly ReaderWriterLock _rwl; private int _writerThreadID = InvalidThreadID; private int _writerLevel; private int _writerSeqNum = 1; // When there are pending changes, the state of the ReaderWriterLock may be manipulated in parallel // nondeterministically, so only verify the state once all pending state changes have been made and are reflected by // the state of this instance. private int _pendingStateChanges; public TestReaderWriterLock() { _rwl = new ReaderWriterLock(); VerifyState(); } public void Dispose() { GC.SuppressFinalize(this); Assert.Equal(0, ThreadReaderLevel); Assert.False(RemoveFromThreadReaderLevels()); Assert.Equal(InvalidThreadID, _writerThreadID); Assert.Equal(0, _writerLevel); } private Dictionary<TestReaderWriterLock, int> EnsureThreadReaderLevels() { Dictionary<TestReaderWriterLock, int> threadReaderLevels = t_readerLevels; if (threadReaderLevels == null) { t_readerLevels = threadReaderLevels = new Dictionary<TestReaderWriterLock, int>(); } return threadReaderLevels; } private bool RemoveFromThreadReaderLevels() { Dictionary<TestReaderWriterLock, int> threadReaderLevels = t_readerLevels; if (threadReaderLevels == null) { return false; } bool removed = threadReaderLevels.Remove(this); if (threadReaderLevels.Count == 0) { t_readerLevels = null; } return removed; } private int ThreadReaderLevel { get { Dictionary<TestReaderWriterLock, int> threadReaderLevels = t_readerLevels; if (threadReaderLevels == null) { return 0; } int readerLevel; if (!threadReaderLevels.TryGetValue(this, out readerLevel)) { return 0; } Assert.NotEqual(0, readerLevel); return readerLevel; } set { if (value == 0) { RemoveFromThreadReaderLevels(); } else { EnsureThreadReaderLevels()[this] = value; } } } public void VerifyIsReaderLockHeld(bool expectedToBeHeld) { lock (_rwl) { if (_pendingStateChanges != 0) { return; } if (expectedToBeHeld) { Assert.NotEqual(0, ThreadReaderLevel); Assert.True(_rwl.IsReaderLockHeld); } else { Assert.Equal(0, ThreadReaderLevel); Assert.False(_rwl.IsReaderLockHeld); } } } public void VerifyIsWriterLockHeld(bool expectedToBeHeld) { lock (_rwl) { if (_pendingStateChanges != 0) { return; } if (expectedToBeHeld) { Assert.Equal(Environment.CurrentManagedThreadId, _writerThreadID); Assert.NotEqual(0, _writerLevel); Assert.True(_rwl.IsWriterLockHeld); } else { Assert.NotEqual(Environment.CurrentManagedThreadId, _writerThreadID); Assert.Equal(0, _writerLevel); Assert.False(_rwl.IsWriterLockHeld); } } } private void VerifyState() { Assert.Equal(0, _pendingStateChanges); Assert.False(ThreadReaderLevel != 0 && _writerLevel != 0); Assert.Equal(ThreadReaderLevel != 0, _rwl.IsReaderLockHeld); Assert.Equal(_writerThreadID == Environment.CurrentManagedThreadId, _rwl.IsWriterLockHeld); Assert.Equal(_writerSeqNum, _rwl.WriterSeqNum); } private int GetTimeoutMilliseconds(int expectedFailureHResult) { return expectedFailureHResult == 0 ? UnexpectedTimeoutMilliseconds : 0; } private void PerformLockAction( int expectedFailureHResult, bool isBlockingOperation, Action rwlAction, Action makeStateChangesOnSuccess) { // Blocking operations are inherently nondeterministic in the order in which they are performed, so record a // pending change before performing the operation. Since the state changes following some blocking operations // may occur in any order, state verification is only done once there are no pending state changes. Non-blocking // operations appear atomic and the relevant state changes need to occur in the requested order, so take a // single lock over the operation and state changes. if (isBlockingOperation) { lock (_rwl) { ++_pendingStateChanges; } } else { Monitor.Enter(_rwl); } try { ApplicationException ex = null; bool isHandledCase = false; try { rwlAction(); isHandledCase = true; } catch (ApplicationException ex2) { ex = ex2; isHandledCase = true; } finally { if (!isHandledCase && isBlockingOperation) { // Some exception other than ones handled above occurred. Decrement the pending state changes. For // handled cases, the decrement needs to occur in the same lock that also verifies the exception, // makes state changes, and verifies the state. lock (_rwl) { --_pendingStateChanges; // This exception will cause the test to fail, so don't verify state } } } if (isBlockingOperation) { Monitor.Enter(_rwl); } try { if (isBlockingOperation) { // Decrementing the pending state changes needs to occur in the same lock that makes state changes // and verifies state, in order to guarantee that when there are no pending state changes based on // the count, all state changes are reflected in the fields as well. --_pendingStateChanges; } Assert.Equal(expectedFailureHResult, ex == null ? 0 : ex.HResult); if (ex == null) { makeStateChangesOnSuccess(); } if (_pendingStateChanges == 0) { VerifyState(); } } finally { if (isBlockingOperation) { Monitor.Exit(_rwl); } } } finally { if (!isBlockingOperation) { Monitor.Exit(_rwl); } } } public void AcquireReaderLock(int expectedFailureHResult = 0) { PerformLockAction( expectedFailureHResult, true /* isBlockingOperation */, () => _rwl.AcquireReaderLock(GetTimeoutMilliseconds(expectedFailureHResult)), () => { if (_writerThreadID == Environment.CurrentManagedThreadId) { // Write lock is already held, acquire a write lock recursively instead Assert.NotEqual(0, _writerLevel); ++_writerLevel; } else { ++ThreadReaderLevel; } }); } public void AcquireWriterLock(int expectedFailureHResult = 0) { PerformLockAction( expectedFailureHResult, true /* isBlockingOperation */, () => _rwl.AcquireWriterLock(GetTimeoutMilliseconds(expectedFailureHResult)), () => { if (_writerLevel == 0) { Assert.Equal(InvalidThreadID, _writerThreadID); _writerThreadID = Environment.CurrentManagedThreadId; ++_writerSeqNum; } else { Assert.Equal(Environment.CurrentManagedThreadId, _writerThreadID); } ++_writerLevel; }); } public void ReleaseReaderLock(int expectedFailureHResult = 0) { PerformLockAction( expectedFailureHResult, false /* isBlockingOperation */, () => _rwl.ReleaseReaderLock(), () => { if (_writerThreadID == Environment.CurrentManagedThreadId) { // Write lock is already held, release a write lock instead Assert.NotEqual(0, _writerLevel); --_writerLevel; if (_writerLevel == 0) { _writerThreadID = InvalidThreadID; } } else { Assert.NotEqual(0, ThreadReaderLevel); --ThreadReaderLevel; } }); } public void ReleaseWriterLock(int expectedFailureHResult = 0) { PerformLockAction( expectedFailureHResult, false /* isBlockingOperation */, () => _rwl.ReleaseWriterLock(), () => { Assert.Equal(Environment.CurrentManagedThreadId, _writerThreadID); Assert.NotEqual(0, _writerLevel); --_writerLevel; if (_writerLevel == 0) { _writerThreadID = InvalidThreadID; } }); } public TestLockCookie UpgradeToWriterLock(int expectedFailureHResult = 0) { TestLockCookie tlc = null; LockCookie lockCookie = default(LockCookie); PerformLockAction( expectedFailureHResult, true /* isBlockingOperation */, () => lockCookie = _rwl.UpgradeToWriterLock(GetTimeoutMilliseconds(expectedFailureHResult)), () => { tlc = new TestLockCookie() { _lockCookie = lockCookie, _readerLevel = ThreadReaderLevel, _writerLevel = _writerLevel }; ThreadReaderLevel = 0; if (_writerLevel == 0) { Assert.Equal(InvalidThreadID, _writerThreadID); _writerThreadID = Environment.CurrentManagedThreadId; ++_writerSeqNum; } else { Assert.Equal(Environment.CurrentManagedThreadId, _writerThreadID); } ++_writerLevel; }); return tlc; } public void DowngradeFromWriterLock(TestLockCookie tlc, int expectedFailureHResult = 0) { Assert.NotNull(tlc); PerformLockAction( expectedFailureHResult, false /* isBlockingOperation */, () => _rwl.DowngradeFromWriterLock(ref tlc._lockCookie), () => { Assert.Equal(Environment.CurrentManagedThreadId, _writerThreadID); Assert.NotEqual(0, _writerLevel); if (tlc._readerLevel == 0) { Assert.True(_writerLevel > tlc._writerLevel); _writerLevel = tlc._writerLevel; if (_writerLevel == 0) { _writerThreadID = InvalidThreadID; } } else { _writerLevel = 0; _writerThreadID = InvalidThreadID; Assert.True(ThreadReaderLevel == 0); ThreadReaderLevel = tlc._readerLevel; } }); } public TestLockCookie ReleaseLock() { TestLockCookie tlc = null; LockCookie lockCookie = default(LockCookie); PerformLockAction( 0 /* expectedFailureHResult */, false /* isBlockingOperation */, () => lockCookie = _rwl.ReleaseLock(), () => { tlc = new TestLockCookie() { _lockCookie = lockCookie, _readerLevel = ThreadReaderLevel, _writerLevel = _writerLevel }; if (_writerLevel != 0) { Assert.Equal(Environment.CurrentManagedThreadId, _writerThreadID); } ThreadReaderLevel = 0; _writerLevel = 0; _writerThreadID = InvalidThreadID; }); return tlc; } public void RestoreLock(TestLockCookie tlc, int expectedFailureHResult = 0) { Assert.NotNull(tlc); Assert.NotEqual(TimeoutExceptionHResult, expectedFailureHResult); PerformLockAction( expectedFailureHResult, true /* isBlockingOperation */, () => _rwl.RestoreLock(ref tlc._lockCookie), () => { Assert.Equal(0, ThreadReaderLevel); Assert.Equal(InvalidThreadID, _writerThreadID); Assert.Equal(0, _writerLevel); ThreadReaderLevel = tlc._readerLevel; _writerLevel = tlc._writerLevel; if (_writerLevel != 0) { Assert.Equal(InvalidThreadID, _writerThreadID); _writerThreadID = Environment.CurrentManagedThreadId; ++_writerSeqNum; } }); } } private class TestLockCookie { public LockCookie _lockCookie; public int _readerLevel; public int _writerLevel; public TestLockCookie Clone() { return (TestLockCookie)MemberwiseClone(); } } } }
#region Copyright (c) 2003, newtelligence AG. All rights reserved. /* // Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com) // Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.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: // // (1) Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // (2) Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // (3) Neither the name of the newtelligence AG 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. // ------------------------------------------------------------------------- // // Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com) // // newtelligence is a registered trademark of newtelligence Aktiengesellschaft. // // For portions of this software, the some additional copyright notices may apply // which can either be found in the license.txt file included in the source distribution // or following this notice. // */ #endregion using System; using CookComputing.XmlRpc; namespace newtelligence.DasBlog.Runtime.Proxies { /// <summary> /// /// </summary> public struct mtCategory { /// <summary> /// /// </summary> public string categoryId; /// <summary> /// /// </summary> [XmlRpcMissingMapping(MappingAction.Ignore)] public string categoryName; [XmlRpcMissingMapping(MappingAction.Ignore)] public bool isPrimary; } /// <summary> /// /// </summary> public struct mtPostTitle { /// <summary> /// /// </summary> [XmlRpcMember(Description="This is in the timezone of the weblog blogid.")] public DateTime created; /// <summary> /// /// </summary> public string postid; /// <summary> /// /// </summary> public string userid; /// <summary> /// /// </summary> public string title; } /// <summary> /// /// </summary> public struct mtTrackbackPing { /// <summary> /// /// </summary> [XmlRpcMember(Description="The title of the entry sent in the ping.")] public string pingTitle; /// <summary> /// /// </summary> [XmlRpcMember(Description="The URL of the entry.")] public string pingURL; /// <summary> /// /// </summary> [XmlRpcMember(Description="The IP address of the host that sent the ping.")] public string pingIP; } /// <summary> /// /// </summary> public struct mtTextFilter { /// <summary> /// /// </summary> [XmlRpcMember(Description="unique string identifying a text formatting plugin")] public string key; /// <summary> /// /// </summary> [XmlRpcMember(Description="readable description to be displayed to a user")] public string value; } /// <summary> /// /// </summary> [XmlRpcMissingMapping(MappingAction.Ignore)] public struct mwEnclosure { /// <summary> /// /// </summary> public int length; /// <summary> /// /// </summary> public string type; /// <summary> /// /// </summary> public string url; } /// <summary> /// /// </summary> [XmlRpcMissingMapping(MappingAction.Ignore)] public struct mwSource { /// <summary> /// /// </summary> public string name; /// <summary> /// /// </summary> public string url; } /// <summary> /// /// </summary> [XmlRpcMissingMapping(MappingAction.Ignore)] public struct mwPost { /// <summary> /// /// </summary> [XmlRpcMissingMapping(MappingAction.Error)] [XmlRpcMember(Description="Required when posting.")] public DateTime dateCreated; /// <summary> /// /// </summary> [XmlRpcMissingMapping(MappingAction.Error)] [XmlRpcMember(Description="Required when posting.")] public string description; /// <summary> /// /// </summary> [XmlRpcMissingMapping(MappingAction.Error)] [XmlRpcMember(Description="Required when posting.")] public string title; [XmlRpcMember][XmlRpcMissingMapping(MappingAction.Ignore)] public string[] categories; [XmlRpcMember][XmlRpcMissingMapping(MappingAction.Ignore)] public mwEnclosure enclosure; /// <summary> /// /// </summary> [XmlRpcMember][XmlRpcMissingMapping(MappingAction.Ignore)] public string link; /// <summary> /// /// </summary> [XmlRpcMember][XmlRpcMissingMapping(MappingAction.Ignore)] public string permalink; [XmlRpcMember( Description="Not required when posting. Depending on server may " + "be either string or integer. " + "Use Convert.ToInt32(postid) to treat as integer or " + "Convert.ToString(postid) to treat as string")] [XmlRpcMissingMapping(MappingAction.Ignore)] public string postid; [XmlRpcMember][XmlRpcMissingMapping(MappingAction.Ignore)] public mwSource source; [XmlRpcMember][XmlRpcMissingMapping(MappingAction.Ignore)] public string userid; [XmlRpcMember][XmlRpcMissingMapping(MappingAction.Ignore)] public string mt_allow_comments; [XmlRpcMember][XmlRpcMissingMapping(MappingAction.Ignore)] public int mt_allow_pings; [XmlRpcMember][XmlRpcMissingMapping(MappingAction.Ignore)] public string mt_convert_breaks; [XmlRpcMember][XmlRpcMissingMapping(MappingAction.Ignore)] public string mt_text_more; [XmlRpcMember][XmlRpcMissingMapping(MappingAction.Ignore)] public string mt_excerpt; } /// <summary> /// /// </summary> public struct mwCategoryInfo { /// <summary> /// /// </summary> public string description; /// <summary> /// /// </summary> public string htmlUrl; /// <summary> /// /// </summary> public string rssUrl; /// <summary> /// /// </summary> public string title; /// <summary> /// /// </summary> public string categoryid; } /// <summary> /// /// </summary> public struct mwCategory { /// <summary> /// /// </summary> public string categoryId; /// <summary> /// /// </summary> public string categoryName; } /// <summary> /// /// </summary> public struct bgCategory { /// <summary> /// /// </summary> public string categoryid; /// <summary> /// /// </summary> public string title; /// <summary> /// /// </summary> public string description; /// <summary> /// /// </summary> public string htmlUrl; /// <summary> /// /// </summary> public string rssUrl; } /// <summary> /// /// </summary> public struct bgPost { /// <summary> /// /// </summary> public System.DateTime dateCreated; /// <summary> /// /// </summary> [XmlRpcMember( Description="Depending on server may be either string or integer. " + "Use Convert.ToInt32(userid) to treat as integer or " + "Convert.ToString(userid) to treat as string")] public object userid; /// <summary> /// /// </summary> public string postid; /// <summary> /// /// </summary> public string content; } /// <summary> /// /// </summary> public struct bgUserInfo { /// <summary> /// /// </summary> public string url; /// <summary> /// /// </summary> public string email; /// <summary> /// /// </summary> public string nickname; /// <summary> /// /// </summary> public string lastname; /// <summary> /// /// </summary> public string firstname; } /// <summary> /// /// </summary> public struct bgBlogInfo { /// <summary> /// /// </summary> public string blogid; /// <summary> /// /// </summary> public string url; /// <summary> /// /// </summary> public string blogName; } /// <summary> /// Summary description for BloggerAPIClientProxy. /// </summary> public class BloggerAPIClientProxy : XmlRpcClientProtocol { public BloggerAPIClientProxy() { } /// <summary> /// /// </summary> /// <param name="appKey"></param> /// <param name="postid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="publish"></param> /// <returns></returns> [XmlRpcMethod("blogger.deletePost", Description="Deletes a post.")] [return: XmlRpcReturnValue(Description="Always returns true.")] public bool blogger_deletePost( string appKey, string postid, string username, string password, [XmlRpcParameter( Description="Where applicable, this specifies whether the blog " + "should be republished after the post has been deleted.")] bool publish) { return (bool)Invoke("blogger_deletePost", new object[]{appKey,postid,username,password,publish}); } /// <summary> /// /// </summary> /// <param name="appKey"></param> /// <param name="postid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="content"></param> /// <param name="publish"></param> /// <returns></returns> [XmlRpcMethod("blogger.editPost", Description="Edits a given post. Optionally, will publish the " + "blog after making the edit.")] [return: XmlRpcReturnValue(Description="Always returns true.")] public bool blogger_editPost( string appKey, string postid, string username, string password, string content, bool publish) { return (bool)Invoke("blogger_editPost", new object[]{appKey,postid,username,password,content,publish}); } /// <summary> /// /// </summary> /// <param name="blogid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> [XmlRpcMethod("blogger.getCategories", Description="Returns a list of the categories that you can use " + "to log against a post.")] public bgCategory[] blogger_getCategories( string blogid, string username, string password) { return (bgCategory[])Invoke("blogger_getCategories", new object[]{blogid,username,password}); } /// <summary> /// /// </summary> /// <param name="appKey"></param> /// <param name="postid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> [XmlRpcMethod("blogger.getPost", Description="Returns a single post.")] public bgPost blogger_getPost( string appKey, string postid, string username, string password) { return (bgPost)Invoke("blogger_getPost", new object[]{appKey,postid,username,password}); } /// <summary> /// /// </summary> /// <param name="appKey"></param> /// <param name="blogid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="numberOfPosts"></param> /// <returns></returns> [XmlRpcMethod("blogger.getRecentPosts", Description="Returns a list of the most recent posts in the system.")] public bgPost[] blogger_getRecentPosts( string appKey, string blogid, string username, string password, int numberOfPosts) { return (bgPost[])Invoke("blogger_getRecentPosts", new object[]{appKey,blogid,username,password,numberOfPosts}); } /// <summary> /// /// </summary> /// <param name="appKey"></param> /// <param name="blogid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="templateType"></param> /// <returns></returns> [XmlRpcMethod("blogger.getTemplate", Description="Returns the main or archive index template of " + "a given blog.")] public string blogger_getTemplate( string appKey, string blogid, string username, string password, string templateType) { return (string)Invoke("blogger_getTemplate", new object[]{appKey,blogid,username,password,templateType}); } /// <summary> /// /// </summary> /// <param name="appKey"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> [XmlRpcMethod("blogger.getUserInfo", Description="Authenticates a user and returns basic user info " + "(name, email, userid, etc.).")] public bgUserInfo blogger_getUserInfo( string appKey, string username, string password) { return (bgUserInfo)Invoke("blogger_getUserInfo", new object[]{appKey,username,password}); } /// <summary> /// /// </summary> /// <param name="appKey"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> [XmlRpcMethod("blogger.getUsersBlogs", Description="Returns information on all the blogs a given user " + "is a member.")] public bgBlogInfo[] blogger_getUsersBlogs( string appKey, string username, string password) { return (bgBlogInfo[])Invoke("blogger_getUsersBlogs", new object[]{appKey,username,password}); } /// <summary> /// /// </summary> /// <param name="appKey"></param> /// <param name="blogid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="content"></param> /// <param name="publish"></param> /// <returns></returns> [XmlRpcMethod("blogger.newPost", Description="Makes a new post to a designated blog. Optionally, " + "will publish the blog after making the post.")] [return: XmlRpcReturnValue(Description="Id of new post")] public string blogger_newPost( string appKey, string blogid, string username, string password, string content, bool publish) { return (string)Invoke("blogger_newPost", new object[]{appKey,blogid,username,password,content,publish}); } /// <summary> /// /// </summary> /// <param name="appKey"></param> /// <param name="blogid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="template"></param> /// <param name="templateType"></param> /// <returns></returns> [XmlRpcMethod("blogger.setTemplate", Description="Edits the main or archive index template of a given blog.")] public bool blogger_setTemplate( string appKey, string blogid, string username, string password, string template, string templateType) { return (bool)Invoke("blogger_setTemplate", new object[]{appKey,blogid,username,password,template,templateType}); } /// <summary> /// Updates an existing post to a designated blog using the metaWeblog API. Returns true if completed. /// </summary> /// <param name="postid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="post"></param> /// <param name="publish"></param> /// <returns>true if successful, false otherwise</returns> [XmlRpcMethod("metaWeblog.editPost", Description="Updates an existing post to a designated blog " + "using the metaWeblog API. Returns true if completed.")] public bool metaweblog_editPost( string postid, string username, string password, mwPost post, bool publish) { return (bool)Invoke("metaweblog_editPost", new object[]{postid,username,password,post,publish}); } /// <summary> /// Retrieves a list of valid categories for a post /// using the metaWeblog API. Returns the metaWeblog categories /// struct collection. /// </summary> /// <param name="blogid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> [XmlRpcMethod("metaWeblog.getCategories", Description="Retrieves a list of valid categories for a post " + "using the metaWeblog API. Returns the metaWeblog categories " + "struct collection.")] public mwCategoryInfo[] metaweblog_getCategories( string blogid, string username, string password) { return (mwCategoryInfo[])Invoke("metaweblog_getCategories", new object[]{blogid,username,password}); } /// <summary> /// /// </summary> /// <param name="postid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> [XmlRpcMethod("metaWeblog.getPost", Description="Retrieves an existing post using the metaWeblog " + "API. Returns the metaWeblog struct.")] public mwPost metaweblog_getPost( string postid, string username, string password) { return (mwPost)Invoke("metaweblog_getPost", new object[]{postid,username,password}); } /// <summary> /// /// </summary> /// <param name="blogid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="numberOfPosts"></param> /// <returns></returns> [XmlRpcMethod("metaWeblog.getRecentPosts", Description="Retrieves a list of the most recent existing post " + "using the metaWeblog API. Returns the metaWeblog struct collection.")] public mwPost[] metaweblog_getRecentPosts( string blogid, string username, string password, int numberOfPosts) { return (mwPost[])Invoke("metaweblog_getRecentPosts", new object[]{blogid,username,password,numberOfPosts}); } /// <summary> /// /// </summary> /// <param name="blogid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="post"></param> /// <param name="publish"></param> /// <returns></returns> [XmlRpcMethod("metaWeblog.newPost", Description="Makes a new post to a designated blog using the " + "metaWeblog API. Returns postid as a string.")] public string metaweblog_newPost( string blogid, string username, string password, mwPost post, bool publish) { return (string)Invoke("metaweblog_newPost", new object[]{blogid,username,password,post,publish}); } /// <summary> /// /// </summary> /// <param name="blogid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> [XmlRpcMethod("mt.getCategoryList", Description="Returns a list of all categories defined in the weblog.")] [return: XmlRpcReturnValue( Description="The isPrimary member of each mtCategory structs is not used.")] public mtCategory[] mt_getCategoryList( string blogid, string username, string password) { return (mtCategory[])Invoke("mt_getCategoryList", new object[]{blogid,username,password}); } /// <summary> /// /// </summary> /// <param name="postid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> [XmlRpcMethod("mt.getPostCategories", Description="Returns a list of all categories to which the post is " + "assigned.")] public mtCategory[] mt_getPostCategories( string postid, string username, string password) { return (mtCategory[])Invoke("mt_getPostCategories", new object[]{postid,username,password}); } /// <summary> /// /// </summary> /// <param name="blogid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="numberOfPosts"></param> /// <returns></returns> [XmlRpcMethod("mt.getRecentPostTitles", Description="Returns a bandwidth-friendly list of the most recent " + "posts in the system.")] public mtPostTitle[] mt_getRecentPostTitles( string blogid, string username, string password, int numberOfPosts) { return (mtPostTitle[])Invoke("mt_getRecentPostTitles", new object[]{blogid,username,password}); } /// <summary> /// /// </summary> /// <param name="postid"></param> /// <returns></returns> [XmlRpcMethod("mt.getTrackbackPings", Description="Retrieve the list of TrackBack pings posted to a " + "particular entry. This could be used to programmatically " + "retrieve the list of pings for a particular entry, then " + "iterate through each of those pings doing the same, until " + "one has built up a graph of the web of entries referencing " + "one another on a particular topic.")] public mtTrackbackPing[] mt_getTrackbackPings( string postid) { return (mtTrackbackPing[])Invoke("mt_getTrackbackPings", new object[]{postid}); } /// <summary> /// /// </summary> /// <param name="postid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> [XmlRpcMethod("mt.publishPost", Description="Publish (rebuild) all of the static files related " + "to an entry from your weblog. Equivalent to saving an entry " + "in the system (but without the ping).")] [return: XmlRpcReturnValue(Description="Always returns true.")] public bool mt_publishPost( string postid, string username, string password) { return (bool)Invoke("mt_publishPost", new object[]{postid,username,password}); } /// <summary> /// /// </summary> /// <param name="postid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="categories"></param> /// <returns></returns> [XmlRpcMethod("mt.setPostCategories", Description="Sets the categories for a post.")] [return: XmlRpcReturnValue(Description="Always returns true.")] public bool mt_setPostCategories( string postid, string username, string password, [XmlRpcParameter( Description="categoryName not required in mtCategory struct.")] mtCategory[] categories) { return (bool)Invoke("mt_setPostCategories", new object[]{postid,username,password,categories}); } /// <summary> /// /// </summary> /// <returns></returns> [XmlRpcMethod("mt.supportedMethods", Description="The method names supported by the server.")] [return: XmlRpcReturnValue( Description="The method names supported by the server.")] public string[] mt_supportedMethods() { return (string[])Invoke("mt_supportedMethods", new object[0]); } /// <summary> /// /// </summary> /// <returns></returns> [XmlRpcMethod("mt.supportedTextFilters", Description="The text filters names supported by the server.")] [return: XmlRpcReturnValue( Description="The text filters names supported by the server.")] public mtTextFilter[] mt_supportedTextFilters() { return (mtTextFilter[])Invoke("mt_supportedTextFilters", new object[0]); } } }
using System; using System.IO; using System.Collections.Generic; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; namespace IO.Swagger.Api { public interface IResourceApi { /// <summary> /// Add resource Adds a single resource /// </summary> /// <param name="body">Resource object that needs to be added to the datastorage</param> /// <returns></returns> void AddResource (Resource body); /// <summary> /// Add resource Adds a single resource /// </summary> /// <param name="body">Resource object that needs to be added to the datastorage</param> /// <returns></returns> System.Threading.Tasks.Task AddResourceAsync (Resource body); /// <summary> /// Find resource by ID Returns a single resource /// </summary> /// <param name="resourceId">ID of the resource to be returned</param> /// <returns>Resource</returns> Resource GetResource (string resourceId); /// <summary> /// Find resource by ID Returns a single resource /// </summary> /// <param name="resourceId">ID of the resource to be returned</param> /// <returns>Resource</returns> System.Threading.Tasks.Task<Resource> GetResourceAsync (string resourceId); } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public class ResourceApi : IResourceApi { /// <summary> /// Initializes a new instance of the <see cref="ResourceApi"/> class. /// </summary> /// <param name="apiClient"> an instance of ApiClient (optional)</param> /// <returns></returns> public ResourceApi(ApiClient apiClient = null) { if (apiClient == null) // use the default one in Configuration this.ApiClient = Configuration.DefaultApiClient; else this.ApiClient = apiClient; } /// <summary> /// Initializes a new instance of the <see cref="ResourceApi"/> class. /// </summary> /// <returns></returns> public ResourceApi(String basePath) { this.ApiClient = new ApiClient(basePath); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <param name="basePath">The base path</param> /// <value>The base path</value> public void SetBasePath(String basePath) { this.ApiClient.BasePath = basePath; } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.ApiClient.BasePath; } /// <summary> /// Gets or sets the API client. /// </summary> /// <value>An instance of the ApiClient</param> public ApiClient ApiClient {get; set;} /// <summary> /// Add resource Adds a single resource /// </summary> /// <param name="body">Resource object that needs to be added to the datastorage</param> /// <returns></returns> public void AddResource (Resource body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling AddResource"); var path = "/resources"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; pathParams.Add("format", "json"); postBody = ApiClient.Serialize(body); // http body (model) parameter // authentication setting, if any String[] authSettings = new String[] { }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling AddResource: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling AddResource: " + response.ErrorMessage, response.ErrorMessage); return; } /// <summary> /// Add resource Adds a single resource /// </summary> /// <param name="body">Resource object that needs to be added to the datastorage</param> /// <returns></returns> public async System.Threading.Tasks.Task AddResourceAsync (Resource body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling AddResource"); var path = "/resources"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; pathParams.Add("format", "json"); postBody = ApiClient.Serialize(body); // http body (model) parameter // authentication setting, if any String[] authSettings = new String[] { }; // make the HTTP request IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling AddResource: " + response.Content, response.Content); return; } /// <summary> /// Find resource by ID Returns a single resource /// </summary> /// <param name="resourceId">ID of the resource to be returned</param> /// <returns>Resource</returns> public Resource GetResource (string resourceId) { // verify the required parameter 'resourceId' is set if (resourceId == null) throw new ApiException(400, "Missing required parameter 'resourceId' when calling GetResource"); var path = "/resources/{resourceId}"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; pathParams.Add("format", "json"); if (resourceId != null) pathParams.Add("resourceId", ApiClient.ParameterToString(resourceId)); // path parameter // authentication setting, if any String[] authSettings = new String[] { }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetResource: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetResource: " + response.ErrorMessage, response.ErrorMessage); return (Resource) ApiClient.Deserialize(response.Content, typeof(Resource), response.Headers); } /// <summary> /// Find resource by ID Returns a single resource /// </summary> /// <param name="resourceId">ID of the resource to be returned</param> /// <returns>Resource</returns> public async System.Threading.Tasks.Task<Resource> GetResourceAsync (string resourceId) { // verify the required parameter 'resourceId' is set if (resourceId == null) throw new ApiException(400, "Missing required parameter 'resourceId' when calling GetResource"); var path = "/resources/{resourceId}"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; pathParams.Add("format", "json"); if (resourceId != null) pathParams.Add("resourceId", ApiClient.ParameterToString(resourceId)); // path parameter // authentication setting, if any String[] authSettings = new String[] { }; // make the HTTP request IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetResource: " + response.Content, response.Content); return (Resource) ApiClient.Deserialize(response.Content, typeof(Resource), response.Headers); } } }
using System; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class PageLoadingTest : DriverTestFixture { private IWebDriver localDriver; [SetUp] public void RestartOriginalDriver() { driver = EnvironmentManager.Instance.GetCurrentDriver(); } [TearDown] public void QuitAdditionalDriver() { if (localDriver != null) { localDriver.Quit(); localDriver = null; } } [Test] public void NoneStrategyShouldNotWaitForPageToLoad() { InitLocalDriver(PageLoadStrategy.None); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=5"); DateTime start = DateTime.Now; localDriver.Url = slowPage; DateTime end = DateTime.Now; TimeSpan duration = end - start; // The slow loading resource on that page takes 6 seconds to return, // but with 'none' page loading strategy 'get' operation should not wait. Assert.That(duration.TotalMilliseconds, Is.LessThan(1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] public void NoneStrategyShouldNotWaitForPageToRefresh() { InitLocalDriver(PageLoadStrategy.None); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=5"); // We discard the element, but want a check to make sure the page is loaded WaitFor(() => localDriver.FindElement(By.TagName("body")), TimeSpan.FromSeconds(10), "did not find body"); DateTime start = DateTime.Now; localDriver.Navigate().Refresh(); DateTime end = DateTime.Now; TimeSpan duration = end - start; // The slow loading resource on that page takes 6 seconds to return, // but with 'none' page loading strategy 'refresh' operation should not wait. Assert.That(duration.TotalMilliseconds, Is.LessThan(1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver does not support eager page load strategy")] public void EagerStrategyShouldNotWaitForResources() { InitLocalDriver(PageLoadStrategy.Eager); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("slowLoadingResourcePage.html"); DateTime start = DateTime.Now; localDriver.Url = slowPage; // We discard the element, but want a check to make sure the GET actually // completed. WaitFor(() => localDriver.FindElement(By.Id("peas")), TimeSpan.FromSeconds(10), "did not find element"); DateTime end = DateTime.Now; // The slow loading resource on that page takes 6 seconds to return. If we // waited for it, our load time should be over 6 seconds. TimeSpan duration = end - start; Assert.That(duration.TotalMilliseconds, Is.LessThan(5 * 1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver does not support eager page load strategy")] public void EagerStrategyShouldNotWaitForResourcesOnRefresh() { InitLocalDriver(PageLoadStrategy.Eager); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("slowLoadingResourcePage.html"); localDriver.Url = slowPage; // We discard the element, but want a check to make sure the GET actually // completed. WaitFor(() => localDriver.FindElement(By.Id("peas")), TimeSpan.FromSeconds(10), "did not find element"); DateTime start = DateTime.Now; localDriver.Navigate().Refresh(); // We discard the element, but want a check to make sure the GET actually // completed. WaitFor(() => localDriver.FindElement(By.Id("peas")), TimeSpan.FromSeconds(10), "did not find element"); DateTime end = DateTime.Now; // The slow loading resource on that page takes 6 seconds to return. If we // waited for it, our load time should be over 6 seconds. TimeSpan duration = end - start; Assert.That(duration.TotalMilliseconds, Is.LessThan(5 * 1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver does not support eager page load strategy")] public void EagerStrategyShouldWaitForDocumentToBeLoaded() { InitLocalDriver(PageLoadStrategy.Eager); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=3"); localDriver.Url = slowPage; // We discard the element, but want a check to make sure the GET actually completed. WaitFor(() => localDriver.FindElement(By.TagName("body")), TimeSpan.FromSeconds(10), "did not find body"); } [Test] public void NormalStrategyShouldWaitForDocumentToBeLoaded() { driver.Url = simpleTestPage; Assert.AreEqual(driver.Title, "Hello WebDriver"); } [Test] public void ShouldFollowRedirectsSentInTheHttpResponseHeaders() { driver.Url = redirectPage; Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldFollowMetaRedirects() { driver.Url = metaRedirectPage; WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldBeAbleToGetAFragmentOnTheCurrentPage() { if (TestUtilities.IsMarionette(driver)) { // Don't run this test on Marionette. Assert.Ignore("Marionette doesn't see subsequent navigation to a fragment as a new navigation."); } driver.Url = xhtmlTestPage; driver.Url = xhtmlTestPage + "#text"; driver.FindElement(By.Id("id1")); } [Test] public void ShouldReturnWhenGettingAUrlThatDoesNotResolve() { try { // Of course, we're up the creek if this ever does get registered driver.Url = "http://www.thisurldoesnotexist.comx/"; } catch (Exception e) { if (!IsIeDriverTimedOutException(e)) { throw e; } } } [Test] [IgnoreBrowser(Browser.Safari, "Safari driver does not throw on malformed URL, causing long delay awaiting timeout")] [NeedsFreshDriver(IsCreatedBeforeTest = true)] public void ShouldThrowIfUrlIsMalformed() { Assert.That(() => driver.Url = "www.test.com", Throws.InstanceOf<WebDriverException>()); } [Test] [IgnoreBrowser(Browser.Safari, "Safari driver does not throw on malformed URL")] [NeedsFreshDriver(IsCreatedBeforeTest = true)] public void ShouldThrowIfUrlIsMalformedInPortPart() { Assert.That(() => driver.Url = "http://localhost:30001bla", Throws.InstanceOf<WebDriverException>()); } [Test] public void ShouldReturnWhenGettingAUrlThatDoesNotConnect() { // Here's hoping that there's nothing here. There shouldn't be driver.Url = "http://localhost:3001"; } [Test] public void ShouldReturnUrlOnNotExistedPage() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("not_existed_page.html"); driver.Url = url; Assert.AreEqual(url, driver.Url); } [Test] public void ShouldBeAbleToLoadAPageWithFramesetsAndWaitUntilAllFramesAreLoaded() { driver.Url = framesetPage; driver.SwitchTo().Frame(0); IWebElement pageNumber = driver.FindElement(By.XPath("//span[@id='pageNumber']")); Assert.AreEqual(pageNumber.Text.Trim(), "1"); driver.SwitchTo().DefaultContent().SwitchTo().Frame(1); pageNumber = driver.FindElement(By.XPath("//span[@id='pageNumber']")); Assert.AreEqual(pageNumber.Text.Trim(), "2"); } [Test] [NeedsFreshDriver(IsCreatedBeforeTest = true)] public void ShouldDoNothingIfThereIsNothingToGoBackTo() { string originalTitle = driver.Title; driver.Url = formsPage; driver.Navigate().Back(); // We may have returned to the browser's home page string currentTitle = driver.Title; Assert.That(currentTitle, Is.EqualTo(originalTitle).Or.EqualTo("We Leave From Here")); if (driver.Title == originalTitle) { driver.Navigate().Back(); Assert.AreEqual(originalTitle, driver.Title); } } [Test] public void ShouldBeAbleToNavigateBackInTheBrowserHistory() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Submit(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("We Leave From Here"), "Browser title was not 'We Leave From Here'"); Assert.AreEqual(driver.Title, "We Leave From Here"); } [Test] public void ShouldBeAbleToNavigateBackInTheBrowserHistoryInPresenceOfIframes() { driver.Url = xhtmlTestPage; driver.FindElement(By.Name("sameWindow")).Click(); WaitFor(TitleToBeEqualTo("This page has iframes"), "Browser title was not 'This page has iframes'"); Assert.AreEqual(driver.Title, "This page has iframes"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Browser title was not 'XHTML Test Page'"); Assert.AreEqual(driver.Title, "XHTML Test Page"); } [Test] public void ShouldBeAbleToNavigateForwardsInTheBrowserHistory() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Submit(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("We Leave From Here"), "Browser title was not 'We Leave From Here'"); Assert.AreEqual(driver.Title, "We Leave From Here"); driver.Navigate().Forward(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] [IgnoreBrowser(Browser.IE, "Browser does not support using insecure SSL certs")] [IgnoreBrowser(Browser.Safari, "Browser does not support using insecure SSL certs")] public void ShouldBeAbleToAccessPagesWithAnInsecureSslCertificate() { String url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("simpleTest.html"); driver.Url = url; // This should work Assert.AreEqual(driver.Title, "Hello WebDriver"); } [Test] public void ShouldBeAbleToRefreshAPage() { driver.Url = xhtmlTestPage; driver.Navigate().Refresh(); Assert.AreEqual(driver.Title, "XHTML Test Page"); } /// <summary> /// see <a href="http://code.google.com/p/selenium/issues/detail?id=208">Issue 208</a> /// </summary> [Test] [IgnoreBrowser(Browser.IE, "Browser does, in fact, hang in this case.")] [IgnoreBrowser(Browser.Firefox, "Browser does, in fact, hang in this case.")] public void ShouldNotHangIfDocumentOpenCallIsNeverFollowedByDocumentCloseCall() { driver.Url = documentWrite; // If this command succeeds, then all is well. driver.FindElement(By.XPath("//body")); } // Note: If this test ever fixed/enabled on Firefox, check if it also needs [NeedsFreshDriver] OR // if [NeedsFreshDriver] can be removed from some other tests in this class. [Test] [IgnoreBrowser(Browser.Firefox)] [IgnoreBrowser(Browser.Safari)] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void PageLoadTimeoutCanBeChanged() { TestPageLoadTimeoutIsEnforced(2); TestPageLoadTimeoutIsEnforced(3); } [Test] [IgnoreBrowser(Browser.Firefox)] [IgnoreBrowser(Browser.Safari)] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void CanHandleSequentialPageLoadTimeouts() { long pageLoadTimeout = 2; long pageLoadTimeBuffer = 10; string slowLoadingPageUrl = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=" + (pageLoadTimeout + pageLoadTimeBuffer)); driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2); AssertPageLoadTimeoutIsEnforced(() => driver.Url = slowLoadingPageUrl, pageLoadTimeout, pageLoadTimeBuffer); AssertPageLoadTimeoutIsEnforced(() => driver.Url = slowLoadingPageUrl, pageLoadTimeout, pageLoadTimeBuffer); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [IgnoreBrowser(Browser.Edge, "Not implemented for browser")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldTimeoutIfAPageTakesTooLongToLoad() { try { TestPageLoadTimeoutIsEnforced(2); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } // Load another page after get() timed out but before test HTTP server served previous page. driver.Url = xhtmlTestPage; WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Title was not expected value"); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [IgnoreBrowser(Browser.Edge, "Not implemented for browser")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldTimeoutIfAPageTakesTooLongToLoadAfterClick() { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("page_with_link_to_slow_loading_page.html"); IWebElement link = WaitFor(() => driver.FindElement(By.Id("link-to-slow-loading-page")), "Could not find link"); try { AssertPageLoadTimeoutIsEnforced(() => link.Click(), 2, 3); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } // Load another page after get() timed out but before test HTTP server served previous page. driver.Url = xhtmlTestPage; WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Title was not expected value"); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldTimeoutIfAPageTakesTooLongToRefresh() { // Get the sleeping servlet with a pause of 5 seconds long pageLoadTimeout = 2; long pageLoadTimeBuffer = 0; string slowLoadingPageUrl = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=" + (pageLoadTimeout + pageLoadTimeBuffer)); driver.Url = slowLoadingPageUrl; driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2); try { AssertPageLoadTimeoutIsEnforced(() => driver.Navigate().Refresh(), 2, 4); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } // Load another page after get() timed out but before test HTTP server served previous page. driver.Url = xhtmlTestPage; WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Title was not expected value"); } [Test] [IgnoreBrowser(Browser.Edge, "Test hangs browser.")] [IgnoreBrowser(Browser.Chrome, "Chrome driver does, in fact, stop loading page after a timeout.")] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [IgnoreBrowser(Browser.Safari, "Safari behaves correctly with page load timeout, but getting text does not propertly trim, leading to a test run time of over 30 seconds")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldNotStopLoadingPageAfterTimeout() { try { TestPageLoadTimeoutIsEnforced(1); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } WaitFor(() => { try { string text = driver.FindElement(By.TagName("body")).Text; return text == "Slept for 11s"; } catch (NoSuchElementException) { } catch (StaleElementReferenceException) { } return false; }, TimeSpan.FromSeconds(30), "Did not find expected text"); } private Func<bool> TitleToBeEqualTo(string expectedTitle) { return () => { return driver.Title == expectedTitle; }; } /** * Sets given pageLoadTimeout to the {@link #driver} and asserts that attempt to navigate to a * page that takes much longer (10 seconds longer) to load results in a TimeoutException. * <p> * Side effects: 1) {@link #driver} is configured to use given pageLoadTimeout, * 2) test HTTP server still didn't serve the page to browser (some browsers may still * be waiting for the page to load despite the fact that driver responded with the timeout). */ private void TestPageLoadTimeoutIsEnforced(long webDriverPageLoadTimeoutInSeconds) { // Test page will load this many seconds longer than WD pageLoadTimeout. long pageLoadTimeBufferInSeconds = 10; string slowLoadingPageUrl = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=" + (webDriverPageLoadTimeoutInSeconds + pageLoadTimeBufferInSeconds)); driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(webDriverPageLoadTimeoutInSeconds); AssertPageLoadTimeoutIsEnforced(() => driver.Url = slowLoadingPageUrl, webDriverPageLoadTimeoutInSeconds, pageLoadTimeBufferInSeconds); } private void AssertPageLoadTimeoutIsEnforced(TestDelegate delegateToTest, long webDriverPageLoadTimeoutInSeconds, long pageLoadTimeBufferInSeconds) { DateTime start = DateTime.Now; Assert.That(delegateToTest, Throws.InstanceOf<WebDriverTimeoutException>(), "I should have timed out after " + webDriverPageLoadTimeoutInSeconds + " seconds"); DateTime end = DateTime.Now; TimeSpan duration = end - start; Assert.That(duration.TotalSeconds, Is.GreaterThan(webDriverPageLoadTimeoutInSeconds)); Assert.That(duration.TotalSeconds, Is.LessThan(webDriverPageLoadTimeoutInSeconds + pageLoadTimeBufferInSeconds)); } private void InitLocalDriver(PageLoadStrategy strategy) { EnvironmentManager.Instance.CloseCurrentDriver(); if (localDriver != null) { localDriver.Quit(); } PageLoadStrategyOptions options = new PageLoadStrategyOptions(); options.PageLoadStrategy = strategy; localDriver = EnvironmentManager.Instance.CreateDriverInstance(options); } private class PageLoadStrategyOptions : DriverOptions { public override void AddAdditionalCapability(string capabilityName, object capabilityValue) { } public override ICapabilities ToCapabilities() { return null; } } } }
using System; using System.Text.RegularExpressions; using System.Collections.Generic; using KaoriStudio.Core.Text.Parsing; using System.Text; using KaoriStudio.Core.Text.Serializers; using KaoriStudio.Core.Configuration; using System.IO; using System.Collections; using System.Linq; using System.Globalization; namespace KaoriStudio.Core.Helpers { #if NETFX_40 using ISetChar = ISet<char>; #else using ISetChar = HashSet<char>; #endif /// <summary> /// Helper for text operations /// </summary> public static class TextHelper { /// <summary> /// Matches an expression to a set of regular expressions /// </summary> /// <param name="regexes">The set of regular expressions</param> /// <param name="expression">The expression to match</param> /// <param name="match">Output match data</param> /// <returns>The index of the match, returns -1 if not found</returns> public static int MatchPatterns(IEnumerable<Regex> regexes, string expression, out Match match) { int i = 0; foreach (Regex r in regexes) { Match m = r.Match(expression); if (m.Success) { match = m; return i; } i++; } match = null; return -1; } /// <summary> /// Matches a string from a set of regexes /// </summary> /// <typeparam name="T">The type, usually an enum</typeparam> /// <param name="regexes">The set of regex-enum pairs</param> /// <param name="expression">The expression to match</param> /// <param name="match">Output match data</param> /// <returns>The enum value of the match, or default(T) if not found</returns> public static T MatchPatterns<T>(IEnumerable<KeyValuePair<Regex, T>> regexes, string expression, out Match match) { foreach (KeyValuePair<Regex, T> kvp in regexes) { Match m = kvp.Key.Match(expression); if (m.Success) { match = m; return kvp.Value; } } match = null; return default(T); } /// <summary> /// Matches a string from a set of strings /// </summary> /// <param name="strings">The set of strings to test</param> /// <param name="expression">The expression to match</param> /// <param name="ignoreCase">Whether to ignore case in the comparison</param> /// <returns>The index of the match, returns -1 if not found</returns> public static int MatchStrings(IEnumerable<string> strings, string expression, bool ignoreCase) { int i = 0; foreach (string s in strings) { if (string.Compare(s, expression, ignoreCase) == 0) return i; i++; } return -1; } private static SortedDictionary<string, Regex> compiledCache; static TextHelper() { compiledCache = new SortedDictionary<string, Regex>(); } /// <summary> /// Generates a compiled Regex from a JavaScript style string /// </summary> /// <param name="regex">The regex string</param> /// <returns>The compiled regex</returns> public static Regex CompileRegex(string regex) { if (regex.Length == 0) return null; if (compiledCache.ContainsKey(regex)) return compiledCache[regex]; char delim = regex[0]; int loc = regex.LastIndexOf(delim); if (loc == 0) throw new RegexParseException("No trailing delimeter"); string pattern = regex.Substring(1, loc - 1); string options = regex.Substring(loc + 1); RegexOptions opts = RegexOptions.Compiled; foreach (char o in options) { switch (o) { case 'm': opts |= RegexOptions.Multiline; break; case 'i': opts |= RegexOptions.IgnoreCase; break; case 'x': opts |= RegexOptions.ExplicitCapture; break; case 'e': opts |= RegexOptions.ECMAScript; break; case 's': opts |= RegexOptions.Singleline; break; case 'w': opts |= RegexOptions.IgnorePatternWhitespace; break; case 'r': opts |= RegexOptions.RightToLeft; break; case 'c': opts |= RegexOptions.CultureInvariant; break; default: throw new RegexParseException("Invalid option: " + o.ToString()); } } Regex r = new Regex(pattern, opts); compiledCache.Add(regex, r); return r; } /// <summary> /// Replaces multiple patterns /// </summary> /// <param name="patterns">The pairs of patterns to replace</param> /// <param name="subject">The subject string</param> /// <returns>The replaced string</returns> public static string RegexReplaceMany(IEnumerable<KeyValuePair<string, string>> patterns, string subject) { foreach (KeyValuePair<string, string> pattern in patterns) subject = CompileRegex(pattern.Key).Replace(subject, pattern.Value); return subject; } /// <summary> /// Replaces mutliple regular expressions within this string /// </summary> /// <param name="str">The source string</param> /// <param name="replacements">The replacement regular expressions</param> /// <returns>The new string</returns> public static string Replace(this string str, IDictionary<Regex, string> replacements) { StringBuilder sb = new StringBuilder(); int index = 0; while (index < str.Length) { int minIndexOf = -1; int matchLength = -1; KeyValuePair<Regex, string> matchValue = default(KeyValuePair<Regex, string>); foreach (KeyValuePair<Regex, string> replacement in replacements) { Match m = replacement.Key.Match(str, index); int indexOf = m.Success ? m.Index : -1; if (indexOf != -1) { if (minIndexOf == -1 || indexOf < minIndexOf) { minIndexOf = indexOf; if (indexOf == index) { matchLength = m.Length; matchValue = replacement; break; } } } } if (matchLength != -1) { sb.Append(matchValue.Key.Replace(str.Substring(index, matchLength), matchValue.Value)); index += matchLength; } else { if (minIndexOf != -1) { sb.Append(str.Substring(index, minIndexOf - index)); index = minIndexOf; } else { sb.Append(str.Substring(index)); index = str.Length; } } } return sb.ToString(); } /// <summary> /// Replaces mutliple strings within this string /// </summary> /// <param name="str">The source string</param> /// <param name="replacements">The replacement strings</param> /// <returns>The new string</returns> public static string Replace(this string str, IDictionary<string, string> replacements) { StringBuilder sb = new StringBuilder(); int index = 0; while (index < str.Length) { int minIndexOf = -1; int matchLength = -1; string matchValue = null; foreach (KeyValuePair<string, string> replacement in replacements) { int indexOf = str.IndexOf(replacement.Key, index); if (indexOf != -1) { if (minIndexOf == -1 || indexOf < minIndexOf) { minIndexOf = indexOf; if (indexOf == index) { matchLength = replacement.Key.Length; matchValue = replacement.Value; break; } } } } if (matchLength != -1) { sb.Append(matchValue); index += matchLength; } else { if (minIndexOf != -1) { sb.Append(str.Substring(index, minIndexOf - index)); index = minIndexOf; } else { sb.Append(str.Substring(index)); index = str.Length; } } } return sb.ToString(); } /// <summary> /// Deserialies a file /// </summary> /// <param name="ts">The text serializer</param> /// <param name="filename">The filename</param> /// <returns>The deserialized form</returns> public static ConfigurationDictionary DeserializeFile(this ITextSerializer ts, string filename) { using (StreamReader sr = new StreamReader(filename)) { return ts.Deserialize(sr); } } /// <summary> /// Deserialies a file /// </summary> /// <param name="ts">The text serializer</param> /// <param name="fi">The file information</param> /// <returns>The deserialized form</returns> public static ConfigurationDictionary DeserializeFile(this ITextSerializer ts, FileInfo fi) { using (StreamReader sr = new StreamReader(fi.OpenRead())) { return ts.Deserialize(sr); } } /// <summary> /// Serializes to a file /// </summary> /// <param name="ts">The text serializer</param> /// <param name="data">The data</param> /// <param name="filename">The filename</param> public static void SerializeFile(this ITextSerializer ts, ConfigurationDictionary data, string filename) { using (StreamWriter sw = new StreamWriter(filename)) { ts.Serialize(data, sw); } } /// <summary> /// Serializes to a file /// </summary> /// <param name="ts">The text serializer</param> /// <param name="data">The data</param> /// <param name="fi">The file information</param> public static void SerializeFile(this ITextSerializer ts, ConfigurationDictionary data, FileInfo fi) { using (StreamWriter sw = new StreamWriter(fi.OpenWrite())) { ts.Serialize(data, sw); } } /// <summary> /// Translates characters /// </summary> /// <param name="subject">The subject string</param> /// <param name="mappings">The mappings of characters to replace</param> /// <returns>The translated string</returns> public static string Translate(this string subject, IDictionary<char, char> mappings) { StringBuilder sb = new StringBuilder(subject.Length); foreach (char c in subject) { char z; if (mappings.TryGetValue(c, out z)) sb.Append(z); else sb.Append(c); } return sb.ToString(); } /// <summary> /// Translates characters /// </summary> /// <param name="subject">The subject string</param> /// <param name="mappings">The mappings of characters to replace</param> /// <returns>The translated string</returns> public static string Translate(this string subject, IDictionary<char, string> mappings) { StringBuilder sb = new StringBuilder(subject.Length); foreach (char c in subject) { string z; if (mappings.TryGetValue(c, out z)) sb.Append(z); else sb.Append(c); } return sb.ToString(); } /// <summary> /// Translates characters /// </summary> /// <param name="subject">The subject string</param> /// <param name="inputChars">The input mappings</param> /// <param name="outputChars">The output mappings</param> /// <returns>The translated string</returns> public static string Translate(this string subject, string inputChars, string outputChars) { SortedDictionary<char, char> mappings = new SortedDictionary<char, char>(); for (int i = 0; i < inputChars.Length; i++) { char ic = inputChars[i]; char oc; if (i < outputChars.Length) oc = outputChars[i]; else oc = outputChars[outputChars.Length - 1]; mappings[ic] = oc; } return Translate(subject, mappings); } /// <summary> /// Repeats a string /// </summary> /// <param name="subject">The string to repeat</param> /// <param name="count">The number of times to repeat</param> /// <returns>The repeated string</returns> public static string Repeat(this string subject, int count) { if (subject.Length == 0) return string.Empty; else if (subject.Length == 1) return new string(subject[0], count); StringBuilder sb = new StringBuilder(subject.Length * count); for (int i = 0; i < count; i++) sb.Append(subject); return sb.ToString(); } /// <summary> /// Lazy substring enumerable /// </summary> public struct LazySubstringEnumerable : IEnumerable<char> { string str; int index; int ubound; /// <summary> /// Creates a new lazy substring enumerable /// </summary> /// <param name="str">The string</param> /// <param name="index">The starting index</param> public LazySubstringEnumerable(string str, int index) { this.str = str; this.index = index; this.ubound = str.Length; } /// <summary> /// Creates a new lazy substring enumerable /// </summary> /// <param name="str">The string</param> /// <param name="index">The starting index</param> /// <param name="length">The length</param> public LazySubstringEnumerable(string str, int index, int length) { this.str = str; this.index = index; var u = index + length; this.ubound = System.Math.Min(str.Length, u); } /// <summary> /// Gets the enumerator for this evaluator /// </summary> /// <returns>The enumerator</returns> public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator<char> IEnumerable<char>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Lazy substring enumerator /// </summary> public struct Enumerator : IEnumerator<char> { int index; LazySubstringEnumerable enumerable; char current; /// <summary> /// The current character /// </summary> public char Current { get { return current; } } object IEnumerator.Current { get { return Current; } } /// <summary> /// Creates a new lazy substring enumerator /// </summary> /// <param name="enumerable">The enumerable</param> public Enumerator(LazySubstringEnumerable enumerable) { this.enumerable = enumerable; this.index = enumerable.index; this.current = default(char); } /// <summary> /// Disposes of this enumerator /// </summary> public void Dispose() { } /// <summary> /// Moves to the next character /// </summary> /// <returns>Whether there was a next character</returns> public bool MoveNext() { if (index < enumerable.ubound) { current = enumerable.str[index]; index++; return true; } else return false; } /// <summary> /// Resets this enumerator /// </summary> public void Reset() { this.index = enumerable.index; } } } /// <summary> /// Lazily evaluates a substring /// </summary> /// <param name="str">The string</param> /// <param name="start">The starting index</param> /// <param name="length">The length</param> /// <returns>An enumerable of the substring</returns> public static IEnumerable<char> LazySubstring(this string str, int start, int length) { return new LazySubstringEnumerable(str, start, length); } /// <summary> /// Lazily evaluates a substring /// </summary> /// <param name="str">The string</param> /// <param name="start">The starting index</param> /// <returns>An enumerable of the substring</returns> public static IEnumerable<char> LazySubstring(this string str, int start) { return new LazySubstringEnumerable(str, start); } /// <summary> /// Lazily splits a string /// </summary> /// <param name="str">The string</param> /// <param name="separator">The separator characters</param> /// <returns>The sequence of split parts</returns> public static IEnumerable<string> LazySplit(this string str, params char[] separator) { StringBuilder sb = new StringBuilder(); var hs = new HashSet<char>(separator); for (int i = 0; i < str.Length; i++) { var c = str[i]; if (hs.Contains(c)) { yield return sb.ToString(); sb.Clear(); } else sb.Append(c); } yield return sb.ToString(); } /// <summary> /// Lazily splits a string /// </summary> /// <param name="str">The string</param> /// <param name="separator">The separator characters</param> /// <param name="count">The maximum number of parts</param> /// <returns>The sequence of split parts</returns> public static IEnumerable<string> LazySplit(this string str, char[] separator, int count) { StringBuilder sb = new StringBuilder(); var hs = new HashSet<char>(separator); int splits = 1; for (int i = 0; i < str.Length; i++) { var c = str[i]; if (splits < count && hs.Contains(c)) { splits++; yield return sb.ToString(); sb.Clear(); } else sb.Append(c); } yield return sb.ToString(); } /// <summary> /// Lazily splits a string /// </summary> /// <param name="str">The string</param> /// <param name="separator">The separator characters</param> /// <param name="count">The maximum number of parts</param> /// <param name="options">The split options</param> /// <returns>The sequence of split parts</returns> public static IEnumerable<string> LazySplit(this string str, char[] separator, int count, StringSplitOptions options) { if (options != StringSplitOptions.RemoveEmptyEntries) return LazySplit(str, separator, count); else return LazySplit(str, separator, count).Where(x => x.Length != 0); } /// <summary> /// Lazily splits a string /// </summary> /// <param name="str">The string</param> /// <param name="separator">The separator characters</param> /// <param name="options">The split options</param> /// <returns>The sequence of split parts</returns> public static IEnumerable<string> LazySplit(this string str, char[] separator, StringSplitOptions options) { if (options != StringSplitOptions.RemoveEmptyEntries) return LazySplit(str, separator); else return LazySplit(str, separator).Where(x => x.Length != 0); } /// <summary> /// Lazily splits a string /// </summary> /// <param name="str">The string</param> /// <param name="separator">The separator string</param> /// <param name="count">The maximum number of parts</param> /// <param name="options">The split options</param> /// <returns>The sequence of split parts</returns> public static IEnumerable<string> LazySplit(this string str, string[] separator, int count, StringSplitOptions options) { if (count <= 0) yield break; var fseps = separator.Where(x => x != null && x.Length != 0); string match = null; int matchIndex = -1; int splits = 1; int i = 0; while (i < str.Length) { if (splits < count) { matchIndex = str.Length; match = null; foreach (var m in fseps) { int io = str.IndexOf(m, i); if (io != -1) { if (match == null || io < matchIndex) { match = m; matchIndex = io; } } } if (match != null) { if (options != StringSplitOptions.RemoveEmptyEntries || i != matchIndex) yield return str.Substring(i, matchIndex); i += match.Length; splits++; continue; } } yield return str.Substring(i); yield break; } if (options != StringSplitOptions.RemoveEmptyEntries) yield return string.Empty; } /// <summary> /// Lazily splits a string /// </summary> /// <param name="str">The string</param> /// <param name="separator">The separator string</param> /// <param name="options">The split options</param> /// <returns>The sequence of split parts</returns> public static IEnumerable<string> LazySplit(this string str, string[] separator, StringSplitOptions options) { var fseps = separator.Where(x => x != null && x.Length != 0); string match = null; int matchIndex = -1; int i = 0; while (i < str.Length) { matchIndex = str.Length; match = null; foreach (var m in fseps) { int io = str.IndexOf(m, i); if (io != -1) { if (match == null || io < matchIndex) { match = m; matchIndex = io; } } } if (match != null) { if (options != StringSplitOptions.RemoveEmptyEntries || i != matchIndex) yield return str.Substring(i, matchIndex); i += match.Length; } else { yield return str.Substring(i); yield break; } } if (options != StringSplitOptions.RemoveEmptyEntries) yield return string.Empty; } /// <summary> /// Gets the part of a string after the first occurrence of a character /// </summary> /// <param name="str">The subject string</param> /// <param name="separator">The character to search for</param> /// <param name="defaultValue">The default value is the character was not found</param> /// <returns>The string after the first occurrence, or defaultValue</returns> public static string PostFirstCharacter(this string str, char separator, string defaultValue) { int i = str.IndexOf(separator); if (i == -1) return defaultValue; else if (i == (str.Length - 1)) return string.Empty; else return str.Substring(i + 1); } /// <summary> /// Gets the part of a string after the first occurrence of a character /// </summary> /// <param name="str">The subject string</param> /// <param name="separator">The character to search for</param> /// <returns>The string after the first occurrence, or str</returns> public static string PostFirstCharacter(this string str, char separator) { return str.PostFirstCharacter(separator, str); } /// <summary> /// Gets the part of a string after the first occurrence of a character /// </summary> /// <param name="str">The subject string</param> /// <param name="separator">The characters to search for</param> /// <param name="defaultValue">The default value is the character was not found</param> /// <returns>The string after the first occurrence, or defaultValue</returns> public static string PostFirstCharacter(this string str, IEnumerable<char> separator, string defaultValue) { int i = -1; for (int p = 0; p < str.Length && i == -1; p++) { var c = str[p]; foreach (var s in separator) { if (s == c) { i = p; break; } } } if (i == -1) return defaultValue; else if (i == (str.Length - 1)) return string.Empty; else return str.Substring(i + 1); } /// <summary> /// Gets the part of a string after the first occurrence of a character /// </summary> /// <param name="str">The subject string</param> /// <param name="separator">The characters to search for</param> /// <returns>The string after the first occurrence, or str</returns> public static string PostFirstCharacter(this string str, IEnumerable<char> separator) { return str.PostFirstCharacter(separator, str); } /// <summary> /// Gets the part of a string after the last occurrence of a character /// </summary> /// <param name="str">The subject string</param> /// <param name="separator">The character to search for</param> /// <param name="defaultValue">The default value is the character was not found</param> /// <returns>The string after the last occurrence, or defaultValue</returns> public static string PostLastCharacter(this string str, char separator, string defaultValue) { int i = str.LastIndexOf(separator); if (i == -1) return defaultValue; else if (i == (str.Length - 1)) return string.Empty; else return str.Substring(i + 1); } /// <summary> /// Gets the part of a string after the last occurrence of a character /// </summary> /// <param name="str">The subject string</param> /// <param name="separator">The character to search for</param> /// <returns>The string after the last occurrence, or str</returns> public static string PostLastCharacter(this string str, char separator) { return str.PostLastCharacter(separator, str); } /// <summary> /// Gets the part of a string after the last occurrence of a character /// </summary> /// <param name="str">The subject string</param> /// <param name="separator">The characters to search for</param> /// <param name="defaultValue">The default value is the character was not found</param> /// <returns>The string after the last occurrence, or defaultValue</returns> public static string PostLastCharacter(this string str, IEnumerable<char> separator, string defaultValue) { int i = -1; if (str.Length == 0) return defaultValue; for (int p = str.Length - 1; p >= 0 && i == -1; p--) { var c = str[p]; foreach (var s in separator) { if (s == c) { i = p; break; } } } if (i == -1) return defaultValue; else if (i == (str.Length - 1)) return string.Empty; else return str.Substring(i + 1); } /// <summary> /// Gets the part of a string after the last occurrence of a character /// </summary> /// <param name="str">The subject string</param> /// <param name="separator">The characters to search for</param> /// <returns>The string after the last occurrence, or str</returns> public static string PostLastCharacter(this string str, IEnumerable<char> separator) { return str.PostLastCharacter(separator, str); } enum FormatState { Initial, OpenBrace, CloseBrace, FormatItem, FormatItemOpenBrace, FormatItemCloseBrace, FormatSpecifier, FormatSpecifierOpenBrace, FormatSpecifierCloseBrace, } /// <summary> /// Finds the indices of each occurence of a needle in a haystack. /// </summary> /// <param name="haystack">The string to search.</param> /// <param name="needle">The string to search for.</param> /// <returns>The indices where the string occurs.</returns> public static IEnumerable<int> IndicesOf(this string haystack, string needle) { if (string.IsNullOrEmpty(haystack) || string.IsNullOrEmpty(needle)) yield break; var i = haystack.IndexOf(needle); while(i != -1) { yield return i; i += needle.Length; if (i > haystack.Length) break; i = haystack.IndexOf(needle, i); } } static void selectNeedle(string haystack, IEnumerable<string> needles, ref int index, out int length) { length = 0; if (string.IsNullOrEmpty(haystack)) return; var i = -1; foreach(var needle in needles) { var j = haystack.IndexOf(needle, index); if (i == -1) { i = j; length = needle.Length; } else if (j != -1 && j < i) { i = j; length = needle.Length; //Console.WriteLine($"needle: {needle}"); } } index = i; } /// <summary> /// Finds the indices of each occurence of a needle in a haystack. /// </summary> /// <param name="haystack">The string to search.</param> /// <param name="needles">The strings to search for.</param> /// <returns>The indices where the string occurs.</returns> public static IEnumerable<int> IndicesOfAny(this string haystack, IEnumerable<string> needles) { if (string.IsNullOrEmpty(haystack)) yield break; var i = 0; selectNeedle(haystack, needles, ref i, out var length); while (i != -1) { yield return i; i += length; //Console.WriteLine($"i: {i}, length: {length}"); if (i > haystack.Length) break; selectNeedle(haystack, needles, ref i, out length); } } /// <inheritdoc/> public static IEnumerable<int> IndicesOfAny(this string haystack, ISetChar needles) { if (string.IsNullOrEmpty(haystack)) yield break; var i = 0; foreach (var c in haystack) { if (needles.Contains(c)) yield return i; i++; } } /// <inheritdoc/> public static IEnumerable<int> IndicesOfAny(this string haystack, IEnumerable<char> needles) { if (string.IsNullOrEmpty(haystack)) yield break; var needleSet = new HashSet<char>(needles); var i = 0; foreach(var c in haystack) { if (needleSet.Contains(c)) yield return i; i++; } } /// <inheritdoc/> public static IEnumerable<int> IndicesOf(this string haystack, char needle) { if (string.IsNullOrEmpty(haystack)) yield break; var i = haystack.IndexOf(needle); while (i != -1) { yield return i; i++; if (i > haystack.Length) break; i = haystack.IndexOf(needle, i); } } static FormatException NewFormatException() { return new FormatException("Named input string was not in a correct format."); } static FormatException NewFormatException(string key) { return new FormatException(string.Format("Cannot find argument \"{0}\"", key)); } static int FormatArgNo(string varname, IDictionary<string, object> args, Dictionary<string, int> argsMap, List<object> argsList) { int argno; if (argsMap.TryGetValue(varname, out argno)) return argno; else { argno = argsList.Count; argsMap[varname] = argno; object o; if (!args.TryGetValue(varname, out o)) throw NewFormatException(varname); argsList.Add(o); return argno; } } /// <summary> /// Generates a normal format string from a named format string /// </summary> /// <param name="format">The named format string</param> /// <param name="args">The arguments map</param> /// <param name="realFormat">The real format string</param> /// <param name="realArgs">The real format args</param> public static void Format(string format, IDictionary<string, object> args, out string realFormat, out object[] realArgs) { var argsMap = new Dictionary<string, int>(args.Count); var argsList = new List<object>(args.Count); var sb = new StringBuilder(); var varname = new StringBuilder(); var state = FormatState.Initial; if (format == null) throw new ArgumentNullException("format", "Value cannot be null"); if (args == null) throw new ArgumentNullException("args", "Value cannot be null"); for (int i = 0; i <= format.Length; i++) { int chr; if (i == format.Length) chr = -1; else chr = (int)format[i]; switch (state) { case FormatState.Initial: switch (chr) { case -1: break; case '{': sb.Append('{'); state = FormatState.OpenBrace; break; case '}': sb.Append('}'); state = FormatState.CloseBrace; break; default: sb.Append((char)chr); break; } break; case FormatState.OpenBrace: switch (chr) { case -1: case '}': throw NewFormatException(); case '{': sb.Append('{'); state = FormatState.Initial; break; default: varname.Clear(); varname.Append((char)chr); state = FormatState.FormatItem; break; } break; case FormatState.CloseBrace: switch (chr) { case '}': sb.Append('}'); state = FormatState.Initial; break; default: throw NewFormatException(); } break; case FormatState.FormatItem: switch (chr) { case -1: throw NewFormatException(); case '{': state = FormatState.FormatItemOpenBrace; break; case '}': state = FormatState.FormatItemCloseBrace; break; case ':': case ',': sb.Append(FormatArgNo(varname.ToString(), args, argsMap, argsList)); sb.Append((char)chr); state = FormatState.FormatSpecifier; break; default: varname.Append((char)chr); break; } break; case FormatState.FormatItemOpenBrace: switch (chr) { case '{': varname.Append('{'); state = FormatState.FormatItem; break; default: throw NewFormatException(); } break; case FormatState.FormatItemCloseBrace: switch (chr) { case '}': varname.Append('}'); state = FormatState.FormatItem; break; default: sb.Append(FormatArgNo(varname.ToString(), args, argsMap, argsList)); sb.Append('}'); if (chr != -1) sb.Append((char)chr); state = (chr == '{') ? FormatState.OpenBrace : FormatState.Initial; break; } break; case FormatState.FormatSpecifier: switch (chr) { case -1: throw NewFormatException(); case '{': sb.Append('{'); state = FormatState.FormatSpecifierOpenBrace; break; case '}': sb.Append('}'); state = FormatState.FormatSpecifierCloseBrace; break; default: sb.Append((char)chr); break; } break; case FormatState.FormatSpecifierOpenBrace: switch (chr) { case '{': sb.Append('{'); state = FormatState.FormatSpecifier; break; default: throw NewFormatException(); } break; case FormatState.FormatSpecifierCloseBrace: switch (chr) { case -1: break; case '{': sb.Append('{'); state = FormatState.OpenBrace; break; case '}': sb.Append('}'); state = FormatState.FormatSpecifier; break; default: sb.Append((char)chr); state = FormatState.Initial; break; } break; } } realFormat = sb.ToString(); realArgs = argsList.ToArray(); } /// <summary> /// Replaces the format items in a specified string with the string representations of corresponding objects in a specified array. /// A parameter supplies culture-specific formatting information. /// </summary> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <param name="format">A composite format string.</param> /// <param name="args">An object dictionary that contains zero or more objects to format. </param> /// <returns>A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.</returns> public static string Format(IFormatProvider provider, string format, IDictionary<string, object> args) { string realFormat; object[] realArgs; Format(format, args, out realFormat, out realArgs); return string.Format(provider, realFormat, realArgs); } /// <summary> /// Replaces the format items in a specified string with the string representations of corresponding objects in a specified array. /// </summary> /// <param name="format">A composite format string.</param> /// <param name="args">An object dictionary that contains zero or more objects to format. </param> /// <returns>A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.</returns> public static string Format(string format, IDictionary<string, object> args) { string realFormat; object[] realArgs; Format(format, args, out realFormat, out realArgs); return string.Format(realFormat, realArgs); } /// <summary> /// Converts the character representation of a decimal digit to its value. /// </summary> /// <param name="c">The character representation.</param> /// <returns>The represented value.</returns> public static int DecimalDigit(char c) { switch (c) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; default: return -1; } } /// <summary> /// Converts the character representation of a hexadecimal digit to its value. /// </summary> /// <param name="c">The character representation.</param> /// <returns>The represented value.</returns> public static int HexadecimalDigit(char c) { switch (c) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'a': case 'A': return 10; case 'b': case 'B': return 11; case 'c': case 'C': return 12; case 'd': case 'D': return 13; case 'e': case 'E': return 14; case 'f': case 'F': return 15; default: return -1; } } } }
// FastZip.cs // // Copyright 2005 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.IO; using ICSharpCode.SharpZipLib.Core; namespace ICSharpCode.SharpZipLib.Zip { /// <summary> /// FastZipEvents supports all events applicable to <see cref="FastZip">FastZip</see> operations. /// </summary> public class FastZipEvents { /// <summary> /// Delegate to invoke when processing directories. /// </summary> public ProcessDirectoryDelegate ProcessDirectory; /// <summary> /// Delegate to invoke when processing files. /// </summary> public ProcessFileDelegate ProcessFile; /// <summary> /// Delegate to invoke when processing directory failures. /// </summary> public DirectoryFailureDelegate DirectoryFailure; /// <summary> /// Delegate to invoke when processing file failures. /// </summary> public FileFailureDelegate FileFailure; /// <summary> /// Raise the <see cref="DirectoryFailure">directory failure</see> event. /// </summary> /// <param name="directory">The directory causing the failure.</param> /// <param name="e">The exception for this event.</param> /// <returns>A boolean indicating if execution should continue or not.</returns> public bool OnDirectoryFailure(string directory, Exception e) { bool result = false; if ( DirectoryFailure != null ) { ScanFailureEventArgs args = new ScanFailureEventArgs(directory, e); DirectoryFailure(this, args); result = args.ContinueRunning; } return result; } /// <summary> /// Raises the <see cref="FileFailure">file failure delegate</see>. /// </summary> /// <param name="file">The file causing the failure.</param> /// <param name="e">The exception for this failure.</param> /// <returns>A boolean indicating if execution should continue or not.</returns> public bool OnFileFailure(string file, Exception e) { bool result = false; if ( FileFailure != null ) { ScanFailureEventArgs args = new ScanFailureEventArgs(file, e); FileFailure(this, args); result = args.ContinueRunning; } return result; } /// <summary> /// Raises the <see cref="ProcessFile">Process File delegate</see>. /// </summary> /// <param name="file">The file being processed.</param> /// <returns>A boolean indicating if execution should continue or not.</returns> public bool OnProcessFile(string file) { bool result = true; if ( ProcessFile != null ) { ScanEventArgs args = new ScanEventArgs(file); ProcessFile(this, args); result = args.ContinueRunning; } return result; } /// <summary> /// Fires the <see cref="ProcessDirectory">process directory</see> delegate. /// </summary> /// <param name="directory">The directory being processed.</param> /// <param name="hasMatchingFiles">Flag indicating if directory has matching files as determined by the current filter.</param> public bool OnProcessDirectory(string directory, bool hasMatchingFiles) { bool result = true; if ( ProcessDirectory != null ) { DirectoryEventArgs args = new DirectoryEventArgs(directory, hasMatchingFiles); ProcessDirectory(this, args); result = args.ContinueRunning; } return result; } } /// <summary> /// FastZip provides facilities for creating and extracting zip files. /// </summary> public class FastZip { #region Enumerations /// <summary> /// Defines the desired handling when overwriting files during extraction. /// </summary> public enum Overwrite { /// <summary> /// Prompt the user to confirm overwriting /// </summary> Prompt, /// <summary> /// Never overwrite files. /// </summary> Never, /// <summary> /// Always overwrite files. /// </summary> Always } #endregion #region Constructors /// <summary> /// Initialise a default instance of <see cref="FastZip"/>. /// </summary> public FastZip() { } /// <summary> /// Initialise a new instance of <see cref="FastZip"/> /// </summary> /// <param name="events">The <see cref="FastZipEvents">events</see> to use during operations.</param> public FastZip(FastZipEvents events) { events_ = events; } #endregion #region Properties /// <summary> /// Get/set a value indicating wether empty directories should be created. /// </summary> public bool CreateEmptyDirectories { get { return createEmptyDirectories_; } set { createEmptyDirectories_ = value; } } #if !NETCF_1_0 /// <summary> /// Get / set the password value. /// </summary> public string Password { get { return password_; } set { password_ = value; } } #endif /// <summary> /// Get or set the <see cref="INameTransform"></see> active when creating Zip files. /// </summary> /// <seealso cref="EntryFactory"></seealso> public INameTransform NameTransform { get { return entryFactory_.NameTransform; } set { entryFactory_.NameTransform = value; } } /// <summary> /// Get or set the <see cref="IEntryFactory"></see> active when creating Zip files. /// </summary> public IEntryFactory EntryFactory { get { return entryFactory_; } set { if ( value == null ) { entryFactory_ = new ZipEntryFactory(); } else { entryFactory_ = value; } } } /// <summary> /// Get/set a value indicating wether file dates and times should /// be restored when extracting files from an archive. /// </summary> /// <remarks>The default value is false.</remarks> public bool RestoreDateTimeOnExtract { get { return restoreDateTimeOnExtract_; } set { restoreDateTimeOnExtract_ = value; } } /// <summary> /// Get/set a value indicating wether file attributes should /// be restored during extract operations /// </summary> public bool RestoreAttributesOnExtract { get { return restoreAttributesOnExtract_; } set { restoreAttributesOnExtract_ = value; } } #endregion #region Delegates /// <summary> /// Delegate called when confirming overwriting of files. /// </summary> public delegate bool ConfirmOverwriteDelegate(string fileName); #endregion #region CreateZip /// <summary> /// Create a zip file. /// </summary> /// <param name="zipFileName">The name of the zip file to create.</param> /// <param name="sourceDirectory">The directory to source files from.</param> /// <param name="recurse">True to recurse directories, false for no recursion.</param> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter">directory filter</see> to apply.</param> public void CreateZip(string zipFileName, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) { CreateZip(File.Create(zipFileName), sourceDirectory, recurse, fileFilter, directoryFilter); } /// <summary> /// Create a zip file/archive. /// </summary> /// <param name="zipFileName">The name of the zip file to create.</param> /// <param name="sourceDirectory">The directory to obtain files and directories from.</param> /// <param name="recurse">True to recurse directories, false for no recursion.</param> /// <param name="fileFilter">The file filter to apply.</param> public void CreateZip(string zipFileName, string sourceDirectory, bool recurse, string fileFilter) { CreateZip(File.Create(zipFileName), sourceDirectory, recurse, fileFilter, null); } /// <summary> /// Create a zip archive sending output to the <paramref name="outputStream"/> passed. /// </summary> /// <param name="outputStream">The stream to write archive data to.</param> /// <param name="sourceDirectory">The directory to source files from.</param> /// <param name="recurse">True to recurse directories, false for no recursion.</param> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter">directory filter</see> to apply.</param> public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) { NameTransform = new ZipNameTransform(sourceDirectory); sourceDirectory_ = sourceDirectory; using ( outputStream_ = new ZipOutputStream(outputStream) ) { #if !NETCF_1_0 if ( password_ != null ) { outputStream_.Password = password_; } #endif FileSystemScanner scanner = new FileSystemScanner(fileFilter, directoryFilter); scanner.ProcessFile += new ProcessFileDelegate(ProcessFile); if ( this.CreateEmptyDirectories ) { scanner.ProcessDirectory += new ProcessDirectoryDelegate(ProcessDirectory); } if (events_ != null) { if ( events_.FileFailure != null ) { scanner.FileFailure += events_.FileFailure; } if ( events_.DirectoryFailure != null ) { scanner.DirectoryFailure += events_.DirectoryFailure; } } scanner.Scan(sourceDirectory, recurse); } } #endregion #region ExtractZip /// <summary> /// Extract the contents of a zip file. /// </summary> /// <param name="zipFileName">The zip file to extract from.</param> /// <param name="targetDirectory">The directory to save extracted information in.</param> /// <param name="fileFilter">A filter to apply to files.</param> public void ExtractZip(string zipFileName, string targetDirectory, string fileFilter) { ExtractZip(zipFileName, targetDirectory, Overwrite.Always, null, fileFilter, null, restoreDateTimeOnExtract_); } /// <summary> /// Extract the contents of a zip file. /// </summary> /// <param name="zipFileName">The zip file to extract from.</param> /// <param name="targetDirectory">The directory to save extracted information in.</param> /// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param> /// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param> /// <param name="fileFilter">A filter to apply to files.</param> /// <param name="directoryFilter">A filter to apply to directories.</param> /// <param name="restoreDateTime">Flag indicating wether to restore the date and time for extracted files.</param> public void ExtractZip(string zipFileName, string targetDirectory, Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, string fileFilter, string directoryFilter, bool restoreDateTime) { if ( (overwrite == Overwrite.Prompt) && (confirmDelegate == null) ) { throw new ArgumentNullException("confirmDelegate"); } continueRunning_ = true; overwrite_ = overwrite; confirmDelegate_ = confirmDelegate; targetDirectory_ = targetDirectory; fileFilter_ = new NameFilter(fileFilter); directoryFilter_ = new NameFilter(directoryFilter); restoreDateTimeOnExtract_ = restoreDateTime; using ( zipFile_ = new ZipFile(zipFileName) ) { #if !NETCF_1_0 if (password_ != null) { zipFile_.Password = password_; } #endif System.Collections.IEnumerator enumerator = zipFile_.GetEnumerator(); while ( continueRunning_ && enumerator.MoveNext()) { ZipEntry entry = (ZipEntry) enumerator.Current; if ( entry.IsFile ) { if ( directoryFilter_.IsMatch(Path.GetDirectoryName(entry.Name)) && fileFilter_.IsMatch(entry.Name) ) { ExtractEntry(entry); } } else if ( entry.IsDirectory ) { if ( directoryFilter_.IsMatch(entry.Name) && CreateEmptyDirectories ) { ExtractEntry(entry); } } else { // Do nothing for volume labels etc... } } } } #endregion #region Internal Processing void ProcessDirectory(object sender, DirectoryEventArgs e) { if ( !e.HasMatchingFiles && CreateEmptyDirectories ) { if ( events_ != null ) { events_.OnProcessDirectory(e.Name, e.HasMatchingFiles); } if ( e.ContinueRunning ) { if (e.Name != sourceDirectory_) { ZipEntry entry = entryFactory_.MakeDirectoryEntry(e.Name); outputStream_.PutNextEntry(entry); } } } } void ProcessFile(object sender, ScanEventArgs e) { if ( (events_ != null) && (events_.ProcessFile != null) ) { events_.ProcessFile(sender, e); } if ( e.ContinueRunning ) { ZipEntry entry = entryFactory_.MakeFileEntry(e.Name); outputStream_.PutNextEntry(entry); AddFileContents(e.Name); } } void AddFileContents(string name) { if ( buffer_ == null ) { buffer_ = new byte[4096]; } using (FileStream stream = File.OpenRead(name)) { StreamUtils.Copy(stream, outputStream_, buffer_); } } void ExtractFileEntry(ZipEntry entry, string targetName) { bool proceed = true; if ( overwrite_ != Overwrite.Always ) { if ( File.Exists(targetName) ) { if ( (overwrite_ == Overwrite.Prompt) && (confirmDelegate_ != null) ) { proceed = confirmDelegate_(targetName); } else { proceed = false; } } } if ( proceed ) { if ( events_ != null ) { continueRunning_ = events_.OnProcessFile(entry.Name); } if ( continueRunning_ ) { try { using ( FileStream outputStream = File.Create(targetName) ) { if ( buffer_ == null ) { buffer_ = new byte[4096]; } StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_); } #if !NETCF_1_0 && !NETCF_2_0 if ( restoreDateTimeOnExtract_ ) { File.SetLastWriteTime(targetName, entry.DateTime); } if ( RestoreAttributesOnExtract && entry.IsDOSEntry && (entry.ExternalFileAttributes != -1)) { FileAttributes fileAttributes = (FileAttributes) entry.ExternalFileAttributes; // TODO: FastZip - Setting of other file attributes on extraction is a little trickier. fileAttributes &= (FileAttributes.Archive | FileAttributes.Normal | FileAttributes.ReadOnly | FileAttributes.Hidden); File.SetAttributes(targetName, fileAttributes); } #endif } catch(Exception ex) { if ( events_ != null ) { continueRunning_ = events_.OnFileFailure(targetName, ex); } else { continueRunning_ = false; } } } } } void ExtractEntry(ZipEntry entry) { bool doExtraction = false; string nameText = entry.Name; if ( entry.IsFile ) { doExtraction = NameIsValid(nameText) && entry.IsCompressionMethodSupported(); } else if ( entry.IsDirectory ) { doExtraction = NameIsValid(nameText); } // TODO: Fire delegate were compression method not supported, or name is invalid. string dirName = null; string targetName = null; if ( doExtraction ) { // Handle invalid entry names by chopping of path root. if (Path.IsPathRooted(nameText)) { string workName = Path.GetPathRoot(nameText); nameText = nameText.Substring(workName.Length); } if ( nameText.Length > 0 ) { targetName = Path.Combine(targetDirectory_, nameText); if ( entry.IsDirectory ) { dirName = targetName; } else { dirName = Path.GetDirectoryName(Path.GetFullPath(targetName)); } } else { doExtraction = false; } } if ( doExtraction && !Directory.Exists(dirName) ) { if ( !entry.IsDirectory || CreateEmptyDirectories ) { try { Directory.CreateDirectory(dirName); } catch (Exception ex) { doExtraction = false; if ( events_ != null ) { if ( entry.IsDirectory ) { continueRunning_ = events_.OnDirectoryFailure(targetName, ex); } else { continueRunning_ = events_.OnFileFailure(targetName, ex); } } else { continueRunning_ = false; } } } } if ( doExtraction && entry.IsFile ) { ExtractFileEntry(entry, targetName); } } static int MakeExternalAttributes(FileInfo info) { return (int)info.Attributes; } #if NET_1_0 || NET_1_1 || NETCF_1_0 static bool NameIsValid(string name) { return (name != null) && (name.Length > 0) && (name.IndexOfAny(Path.InvalidPathChars) < 0); } #else static bool NameIsValid(string name) { return (name != null) && (name.Length > 0) && (name.IndexOfAny(Path.GetInvalidPathChars()) < 0); } #endif #endregion #region Instance Fields bool continueRunning_; byte[] buffer_; ZipOutputStream outputStream_; ZipFile zipFile_; string targetDirectory_; string sourceDirectory_; NameFilter fileFilter_; NameFilter directoryFilter_; Overwrite overwrite_; ConfirmOverwriteDelegate confirmDelegate_; bool restoreDateTimeOnExtract_; bool restoreAttributesOnExtract_; bool createEmptyDirectories_; FastZipEvents events_; IEntryFactory entryFactory_ = new ZipEntryFactory(); #if !NETCF_1_0 string password_; #endif #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.Generic; using System.Linq; using System.Security; using System.Threading; using System.Windows.Media; using System.Windows.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion { public abstract class AbstractCompletionProviderTests<TWorkspaceFixture> : TestBase, IUseFixture<TWorkspaceFixture> where TWorkspaceFixture : TestWorkspaceFixture, new() { protected readonly Mock<ICompletionSession> MockCompletionSession; internal ICompletionProvider CompletionProvider; protected TWorkspaceFixture workspaceFixture; public AbstractCompletionProviderTests() { SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext()); MockCompletionSession = new Mock<ICompletionSession>(MockBehavior.Strict); } public void SetFixture(TWorkspaceFixture workspaceFixture) { this.workspaceFixture = workspaceFixture; this.CompletionProvider = CreateCompletionProvider(); } protected static bool CanUseSpeculativeSemanticModel(Document document, int position) { var service = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var node = document.GetSyntaxRootAsync().Result.FindToken(position).Parent; return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty; } private void CheckResults(Document document, int position, string expectedItemOrNull, string expectedDescriptionOrNull, bool usePreviousCharAsTrigger, bool checkForAbsence, Glyph? glyph) { var code = document.GetTextAsync().Result.ToString(); CompletionTriggerInfo completionTriggerInfo = new CompletionTriggerInfo(); if (usePreviousCharAsTrigger) { completionTriggerInfo = CompletionTriggerInfo.CreateTypeCharTriggerInfo(triggerCharacter: code.ElementAt(position - 1)); } var group = CompletionProvider.GetGroupAsync(document, position, completionTriggerInfo).Result; var completions = group == null ? null : group.Items; if (checkForAbsence) { if (completions == null) { return; } if (expectedItemOrNull == null) { Assert.Empty(completions); } else { AssertEx.None( completions, c => CompareItems(c.DisplayText, expectedItemOrNull) && (expectedDescriptionOrNull != null ? c.GetDescriptionAsync().Result.GetFullText() == expectedDescriptionOrNull : true)); } } else { if (expectedItemOrNull == null) { Assert.NotEmpty(completions); } else { AssertEx.Any(completions, c => CompareItems(c.DisplayText, expectedItemOrNull) && (expectedDescriptionOrNull != null ? c.GetDescriptionAsync().Result.GetFullText() == expectedDescriptionOrNull : true) && (glyph.HasValue ? c.Glyph == glyph.Value : true)); } } } private void Verify(string markup, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, bool experimental, int? glyph) { string code; int position; MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out code, out position); VerifyWorker(code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, experimental, glyph); } protected void VerifyCustomCommitProvider(string markupBeforeCommit, string itemToCommit, string expectedCodeAfterCommit, SourceCodeKind? sourceCodeKind = null, char? commitChar = null) { string code; int position; MarkupTestFile.GetPosition(markupBeforeCommit.NormalizeLineEndings(), out code, out position); if (sourceCodeKind.HasValue) { VerifyCustomCommitProviderWorker(code, position, itemToCommit, expectedCodeAfterCommit, sourceCodeKind.Value, commitChar); } else { VerifyCustomCommitProviderWorker(code, position, itemToCommit, expectedCodeAfterCommit, SourceCodeKind.Regular, commitChar); VerifyCustomCommitProviderWorker(code, position, itemToCommit, expectedCodeAfterCommit, SourceCodeKind.Script, commitChar); } } protected void VerifyProviderCommit(string markupBeforeCommit, string itemToCommit, string expectedCodeAfterCommit, char? commitChar, string textTypedSoFar, SourceCodeKind? sourceCodeKind = null) { string code; int position; MarkupTestFile.GetPosition(markupBeforeCommit.NormalizeLineEndings(), out code, out position); expectedCodeAfterCommit = expectedCodeAfterCommit.NormalizeLineEndings(); if (sourceCodeKind.HasValue) { VerifyProviderCommitWorker(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, sourceCodeKind.Value); } else { VerifyProviderCommitWorker(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, SourceCodeKind.Regular); VerifyProviderCommitWorker(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, SourceCodeKind.Script); } } protected virtual bool CompareItems(string actualItem, string expectedItem) { return actualItem.Equals(expectedItem); } protected void VerifyItemExists(string markup, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool experimental = false, int? glyph = null) { if (sourceCodeKind.HasValue) { Verify(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind.Value, usePreviousCharAsTrigger, checkForAbsence: false, experimental: experimental, glyph: glyph); } else { Verify(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Regular, usePreviousCharAsTrigger, checkForAbsence: false, experimental: experimental, glyph: glyph); Verify(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Script, usePreviousCharAsTrigger, checkForAbsence: false, experimental: experimental, glyph: glyph); } } protected void VerifyItemIsAbsent(string markup, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool experimental = false) { if (sourceCodeKind.HasValue) { Verify(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind.Value, usePreviousCharAsTrigger, checkForAbsence: true, experimental: experimental, glyph: null); } else { Verify(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Regular, usePreviousCharAsTrigger, checkForAbsence: true, experimental: experimental, glyph: null); Verify(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Script, usePreviousCharAsTrigger, checkForAbsence: true, experimental: experimental, glyph: null); } } protected void VerifyAnyItemExists(string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool experimental = false) { if (sourceCodeKind.HasValue) { Verify(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind.Value, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, experimental: experimental, glyph: null); } else { Verify(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, experimental: experimental, glyph: null); Verify(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, experimental: experimental, glyph: null); } } protected void VerifyNoItemsExist(string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool experimental = false) { if (sourceCodeKind.HasValue) { Verify(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind.Value, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, experimental: experimental, glyph: null); } else { Verify(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, experimental: experimental, glyph: null); Verify(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, experimental: experimental, glyph: null); } } internal abstract ICompletionProvider CreateCompletionProvider(); /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="code">The source code (not markup).</param> /// <param name="expectedItemOrNull">The expected item. If this is null, verifies that *any* item shows up for this CompletionProvider (or no items show up if checkForAbsence is true).</param> /// <param name="expectedDescriptionOrNull">If this is null, the Description for the item is ignored.</param> /// <param name="usePreviousCharAsTrigger">Whether or not the previous character in markup should be used to trigger IntelliSense for this provider. If false, invokes it through the invoke IntelliSense command.</param> /// <param name="checkForAbsence">If true, checks for absence of a specific item (or that no items are returned from this CompletionProvider)</param> protected virtual void VerifyWorker(string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, bool experimental, int? glyph) { if (experimental) { foreach (var project in workspaceFixture.Workspace.Projects) { workspaceFixture.Workspace.OnParseOptionsChanged(project.Id, CreateExperimentalParseOptions(project.ParseOptions)); } } Glyph? expectedGlyph = null; if (glyph.HasValue) { expectedGlyph = (Glyph)glyph.Value; } var document1 = workspaceFixture.UpdateDocument(code, sourceCodeKind); CheckResults(document1, position, expectedItemOrNull, expectedDescriptionOrNull, usePreviousCharAsTrigger, checkForAbsence, expectedGlyph); if (CanUseSpeculativeSemanticModel(document1, position)) { var document2 = workspaceFixture.UpdateDocument(code, sourceCodeKind, cleanBeforeUpdate: false); CheckResults(document2, position, expectedItemOrNull, expectedDescriptionOrNull, usePreviousCharAsTrigger, checkForAbsence, expectedGlyph); } } protected virtual ParseOptions CreateExperimentalParseOptions(ParseOptions parseOptions) { return parseOptions; } /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="codeBeforeCommit">The source code (not markup).</param> /// <param name="position">Position where intellisense is invoked.</param> /// <param name="itemToCommit">The item to commit from the completion provider.</param> /// <param name="expectedCodeAfterCommit">The expected code after commit.</param> protected virtual void VerifyCustomCommitProviderWorker(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, SourceCodeKind sourceCodeKind, char? commitChar = null) { var document1 = workspaceFixture.UpdateDocument(codeBeforeCommit, sourceCodeKind); VerifyCustomCommitProviderCheckResults(document1, codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, commitChar); if (CanUseSpeculativeSemanticModel(document1, position)) { var document2 = workspaceFixture.UpdateDocument(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate: false); VerifyCustomCommitProviderCheckResults(document2, codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, commitChar); } } private void VerifyCustomCommitProviderCheckResults(Document document, string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar) { var textBuffer = workspaceFixture.Workspace.Documents.Single().TextBuffer; var completions = CompletionProvider.GetGroupAsync(document, position, CompletionTriggerInfo.CreateInvokeCompletionTriggerInfo()).Result.Items; var completionItem = completions.First(i => CompareItems(i.DisplayText, itemToCommit)); var customCommitCompletionProvider = CompletionProvider as ICustomCommitCompletionProvider; if (customCommitCompletionProvider != null) { var textView = workspaceFixture.Workspace.Documents.Single().GetTextView(); VerifyCustomCommitWorker(customCommitCompletionProvider, completionItem, textView, textBuffer, codeBeforeCommit, expectedCodeAfterCommit, commitChar); } else { throw new Exception(); } } internal virtual void VerifyCustomCommitWorker(ICustomCommitCompletionProvider customCommitCompletionProvider, CompletionItem completionItem, ITextView textView, ITextBuffer textBuffer, string codeBeforeCommit, string expectedCodeAfterCommit, char? commitChar = null) { int expectedCaretPosition; string actualExpectedCode = null; MarkupTestFile.GetPosition(expectedCodeAfterCommit, out actualExpectedCode, out expectedCaretPosition); if (commitChar.HasValue && !customCommitCompletionProvider.IsCommitCharacter(completionItem, commitChar.Value, string.Empty)) { Assert.Equal(codeBeforeCommit, actualExpectedCode); return; } customCommitCompletionProvider.Commit(completionItem, textView, textBuffer, textView.TextSnapshot, commitChar); string actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="codeBeforeCommit">The source code (not markup).</param> /// <param name="position">Position where intellisense is invoked.</param> /// <param name="itemToCommit">The item to commit from the completion provider.</param> /// <param name="expectedCodeAfterCommit">The expected code after commit.</param> protected virtual void VerifyProviderCommitWorker(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar, string textTypedSoFar, SourceCodeKind sourceCodeKind) { var document1 = workspaceFixture.UpdateDocument(codeBeforeCommit, sourceCodeKind); VerifyProviderCommitCheckResults(document1, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar); if (CanUseSpeculativeSemanticModel(document1, position)) { var document2 = workspaceFixture.UpdateDocument(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate: false); VerifyProviderCommitCheckResults(document2, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar); } } private void VerifyProviderCommitCheckResults(Document document, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar, string textTypedSoFar) { var textBuffer = workspaceFixture.Workspace.Documents.Single().TextBuffer; var textSnapshot = textBuffer.CurrentSnapshot.AsText(); var completions = CompletionProvider.GetGroupAsync(document, position, CompletionTriggerInfo.CreateInvokeCompletionTriggerInfo()).Result.Items; var completionItem = completions.First(i => CompareItems(i.DisplayText, itemToCommit)); var textChange = CompletionProvider.IsCommitCharacter(completionItem, commitChar.HasValue ? commitChar.Value : ' ', textTypedSoFar) ? CompletionProvider.GetTextChange(completionItem, commitChar, textTypedSoFar) : new TextChange(); var oldText = document.GetTextAsync().Result; var newText = oldText.WithChanges(textChange); Assert.Equal(expectedCodeAfterCommit, newText.ToString()); } protected void VerifyItemInEditorBrowsableContexts(string markup, string referencedCode, string item, int expectedSymbolsSameSolution, int expectedSymbolsMetadataReference, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers = false) { CompletionProvider = CreateCompletionProvider(); VerifyItemWithMetadataReference(markup, referencedCode, item, expectedSymbolsMetadataReference, sourceLanguage, referencedLanguage, hideAdvancedMembers); VerifyItemWithProjectReference(markup, referencedCode, item, expectedSymbolsSameSolution, sourceLanguage, referencedLanguage, hideAdvancedMembers); // If the source and referenced languages are different, then they cannot be in the same project if (sourceLanguage == referencedLanguage) { VerifyItemInSameProject(markup, referencedCode, item, expectedSymbolsSameSolution, sourceLanguage, hideAdvancedMembers); } } private void VerifyItemWithMetadataReference(string markup, string metadataReferenceCode, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument""> {3} </Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(metadataReferenceCode)); VerifyItemWithReferenceWorker(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected void VerifyItemWithAliasedMetadataReferences(string markup, string metadataAlias, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" Aliases=""{3}, global"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument""> </Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(metadataAlias)); VerifyItemWithReferenceWorker(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected void VerifyItemWithProjectReference(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <ProjectReference>ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument""> {1} </Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument""> {3} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(referencedCode)); VerifyItemWithReferenceWorker(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } private void VerifyItemInSameProject(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <Document FilePath=""ReferencedDocument""> {2} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), SecurityElement.Escape(referencedCode)); VerifyItemWithReferenceWorker(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } private void VerifyItemWithReferenceWorker(string xmlString, string expectedItem, int expectedSymbols, bool hideAdvancedMembers) { using (var testWorkspace = TestWorkspaceFactory.CreateWorkspace(xmlString)) { var optionsService = testWorkspace.Services.GetService<IOptionService>(); int cursorPosition = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var solution = testWorkspace.CurrentSolution; DocumentId docId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id; Document doc = solution.GetDocument(docId); optionsService.SetOptions(optionsService.GetOptions().WithChangedOption(Microsoft.CodeAnalysis.Completion.CompletionOptions.HideAdvancedMembers, doc.Project.Language, hideAdvancedMembers)); CompletionTriggerInfo completionTriggerInfo = new CompletionTriggerInfo(); var completions = CompletionProvider.GetGroupAsync(doc, cursorPosition, completionTriggerInfo).Result; if (expectedSymbols >= 1) { AssertEx.Any(completions.Items, c => CompareItems(c.DisplayText, expectedItem)); // Throw if multiple to indicate a bad test case var description = completions.Items.Single(c => CompareItems(c.DisplayText, expectedItem)).GetDescriptionAsync().Result; if (expectedSymbols == 1) { Assert.DoesNotContain("+", description.GetFullText()); } else { Assert.Contains(GetExpectedOverloadSubstring(expectedSymbols), description.GetFullText()); } } else { if (completions != null) { AssertEx.None(completions.Items, c => CompareItems(c.DisplayText, expectedItem)); } } } } protected void VerifyItemWithMscorlib45(string markup, string expectedItem, string expectedDescription, string sourceLanguage) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferencesNet45=""true""> <Document FilePath=""SourceDocument""> {1} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup)); VerifyItemWithMscorlib45Worker(xmlString, expectedItem, expectedDescription); } private void VerifyItemWithMscorlib45Worker(string xmlString, string expectedItem, string expectedDescription) { using (var testWorkspace = TestWorkspaceFactory.CreateWorkspace(xmlString)) { int cursorPosition = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var solution = testWorkspace.CurrentSolution; DocumentId docId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id; Document doc = solution.GetDocument(docId); CompletionTriggerInfo completionTriggerInfo = new CompletionTriggerInfo(); var completions = CompletionProvider.GetGroupAsync(doc, cursorPosition, completionTriggerInfo).Result; var item = completions.Items.FirstOrDefault(i => i.DisplayText == expectedItem); Assert.Equal(expectedDescription, item.GetDescriptionAsync().Result.GetFullText()); } } private const char NonBreakingSpace = (char)0x00A0; private string GetExpectedOverloadSubstring(int expectedSymbols) { if (expectedSymbols <= 1) { throw new ArgumentOutOfRangeException("expectedSymbols"); } return "+" + NonBreakingSpace + (expectedSymbols - 1) + NonBreakingSpace + "overload"; } protected void VerifyItemInLinkedFiles(string xmlString, string expectedItem, string expectedDescription) { using (var testWorkspace = TestWorkspaceFactory.CreateWorkspace(xmlString)) { var optionsService = testWorkspace.Services.GetService<IOptionService>(); int cursorPosition = testWorkspace.Documents.First().CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var textContainer = testWorkspace.Documents.First().TextBuffer.AsTextContainer(); var currentContextDocumentId = testWorkspace.GetDocumentIdInCurrentContext(textContainer); Document doc = solution.GetDocument(currentContextDocumentId); CompletionTriggerInfo completionTriggerInfo = new CompletionTriggerInfo(); var completions = CompletionProvider.GetGroupAsync(doc, cursorPosition, completionTriggerInfo).WaitAndGetResult(CancellationToken.None); var item = completions.Items.Single(c => c.DisplayText == expectedItem); Assert.NotNull(item); if (expectedDescription != null) { var actualDescription = item.GetDescriptionAsync().Result.GetFullText(); Assert.Equal(expectedDescription, actualDescription); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.NetCore.Extensions; namespace System.Tests { public class EnvironmentTests : RemoteExecutorTestBase { [Fact] public void CurrentDirectory_Null_Path_Throws_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("value", () => Environment.CurrentDirectory = null); } [Fact] public void CurrentDirectory_Empty_Path_Throws_ArgumentException() { AssertExtensions.Throws<ArgumentException>("value", null, () => Environment.CurrentDirectory = string.Empty); } [Fact] public void CurrentDirectory_SetToNonExistentDirectory_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => Environment.CurrentDirectory = GetTestFilePath()); } [Fact] public void CurrentDirectory_SetToValidOtherDirectory() { RemoteInvoke(() => { Environment.CurrentDirectory = TestDirectory; Assert.Equal(Directory.GetCurrentDirectory(), Environment.CurrentDirectory); if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // On OSX, the temp directory /tmp/ is a symlink to /private/tmp, so setting the current // directory to a symlinked path will result in GetCurrentDirectory returning the absolute // path that followed the symlink. Assert.Equal(TestDirectory, Directory.GetCurrentDirectory()); } return SuccessExitCode; }).Dispose(); } [Fact] public void CurrentManagedThreadId_Idempotent() { Assert.Equal(Environment.CurrentManagedThreadId, Environment.CurrentManagedThreadId); } [Fact] public void CurrentManagedThreadId_DifferentForActiveThreads() { var ids = new HashSet<int>(); Barrier b = new Barrier(10); Task.WaitAll((from i in Enumerable.Range(0, b.ParticipantCount) select Task.Factory.StartNew(() => { b.SignalAndWait(); lock (ids) ids.Add(Environment.CurrentManagedThreadId); b.SignalAndWait(); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray()); Assert.Equal(b.ParticipantCount, ids.Count); } [Fact] public void HasShutdownStarted_FalseWhileExecuting() { Assert.False(Environment.HasShutdownStarted); } [Fact] public void Is64BitProcess_MatchesIntPtrSize() { Assert.Equal(IntPtr.Size == 8, Environment.Is64BitProcess); } [Fact] public void Is64BitOperatingSystem_TrueIf64BitProcess() { if (Environment.Is64BitProcess) { Assert.True(Environment.Is64BitOperatingSystem); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment public void Is64BitOperatingSystem_Unix_TrueIff64BitProcess() { Assert.Equal(Environment.Is64BitProcess, Environment.Is64BitOperatingSystem); } [Fact] public void OSVersion_Idempotent() { Assert.Same(Environment.OSVersion, Environment.OSVersion); } [Fact] public void OSVersion_MatchesPlatform() { PlatformID id = Environment.OSVersion.Platform; Assert.Equal( RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? PlatformID.Win32NT : PlatformID.Unix, id); } [Fact] public void OSVersion_ValidVersion() { Version version = Environment.OSVersion.Version; string versionString = Environment.OSVersion.VersionString; Assert.False(string.IsNullOrWhiteSpace(versionString), "Expected non-empty version string"); Assert.True(version.Major > 0); Assert.Contains(version.ToString(2), versionString); Assert.Contains(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "Windows" : "Unix", versionString); } [Fact] public void SystemPageSize_Valid() { int pageSize = Environment.SystemPageSize; Assert.Equal(pageSize, Environment.SystemPageSize); Assert.True(pageSize > 0, "Expected positive page size"); Assert.True((pageSize & (pageSize - 1)) == 0, "Expected power-of-2 page size"); } [Fact] public void UserInteractive_True() { Assert.True(Environment.UserInteractive); } [Fact] public void UserName_Valid() { Assert.False(string.IsNullOrWhiteSpace(Environment.UserName)); } [Fact] public void UserDomainName_Valid() { Assert.False(string.IsNullOrWhiteSpace(Environment.UserDomainName)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment public void UserDomainName_Unix_MatchesMachineName() { Assert.Equal(Environment.MachineName, Environment.UserDomainName); } [Fact] public void Version_MatchesFixedVersion() { Assert.Equal(new Version(4, 0, 30319, 42000), Environment.Version); } [Fact] public void WorkingSet_Valid() { Assert.True(Environment.WorkingSet > 0, "Expected positive WorkingSet value"); } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // fail fast crashes the process [OuterLoop] [Fact] public void FailFast_ExpectFailureExitCode() { using (Process p = RemoteInvoke(() => { Environment.FailFast("message"); return SuccessExitCode; }).Process) { p.WaitForExit(); Assert.NotEqual(SuccessExitCode, p.ExitCode); } using (Process p = RemoteInvoke(() => { Environment.FailFast("message", new Exception("uh oh")); return SuccessExitCode; }).Process) { p.WaitForExit(); Assert.NotEqual(SuccessExitCode, p.ExitCode); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment public void GetFolderPath_Unix_PersonalIsHomeAndUserProfile() { Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.Personal)); Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); } [Fact] public void GetSystemDirectory() { if (PlatformDetection.IsWindowsNanoServer) { // https://github.com/dotnet/corefx/issues/19110 // On Windows Nano, ShGetKnownFolderPath currently doesn't give // the correct result for SystemDirectory. // Assert that it's wrong, so that if it's fixed, we don't forget to // enable this test for Nano. Assert.NotEqual(Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.SystemDirectory); return; } Assert.Equal(Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.SystemDirectory); } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment [InlineData(Environment.SpecialFolder.UserProfile, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.Personal, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.CommonApplicationData, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.CommonTemplates, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Desktop, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.DesktopDirectory, Environment.SpecialFolderOption.DoNotVerify)] // Not set on Unix (amongst others) //[InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Templates, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyVideos, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyMusic, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyPictures, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Fonts, Environment.SpecialFolderOption.DoNotVerify)] public void GetFolderPath_Unix_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option) { Assert.NotEmpty(Environment.GetFolderPath(folder, option)); if (option == Environment.SpecialFolderOption.None) { Assert.NotEmpty(Environment.GetFolderPath(folder)); } } [Theory] [PlatformSpecific(TestPlatforms.OSX)] // Tests OS-specific environment [InlineData(Environment.SpecialFolder.Favorites, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.InternetCache, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.None)] public void GetFolderPath_OSX_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option) { Assert.NotEmpty(Environment.GetFolderPath(folder, option)); if (option == Environment.SpecialFolderOption.None) { Assert.NotEmpty(Environment.GetFolderPath(folder)); } } // The commented out folders aren't set on all systems. [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))] // https://github.com/dotnet/corefx/issues/19110 [InlineData(Environment.SpecialFolder.ApplicationData)] [InlineData(Environment.SpecialFolder.CommonApplicationData)] [InlineData(Environment.SpecialFolder.LocalApplicationData)] [InlineData(Environment.SpecialFolder.Cookies)] [InlineData(Environment.SpecialFolder.Desktop)] [InlineData(Environment.SpecialFolder.Favorites)] [InlineData(Environment.SpecialFolder.History)] [InlineData(Environment.SpecialFolder.InternetCache)] [InlineData(Environment.SpecialFolder.Programs)] // [InlineData(Environment.SpecialFolder.MyComputer)] [InlineData(Environment.SpecialFolder.MyMusic)] [InlineData(Environment.SpecialFolder.MyPictures)] [InlineData(Environment.SpecialFolder.MyVideos)] [InlineData(Environment.SpecialFolder.Recent)] [InlineData(Environment.SpecialFolder.SendTo)] [InlineData(Environment.SpecialFolder.StartMenu)] [InlineData(Environment.SpecialFolder.Startup)] [InlineData(Environment.SpecialFolder.System)] [InlineData(Environment.SpecialFolder.Templates)] [InlineData(Environment.SpecialFolder.DesktopDirectory)] [InlineData(Environment.SpecialFolder.Personal)] [InlineData(Environment.SpecialFolder.ProgramFiles)] [InlineData(Environment.SpecialFolder.CommonProgramFiles)] [InlineData(Environment.SpecialFolder.AdminTools)] [InlineData(Environment.SpecialFolder.CDBurning)] [InlineData(Environment.SpecialFolder.CommonAdminTools)] [InlineData(Environment.SpecialFolder.CommonDocuments)] [InlineData(Environment.SpecialFolder.CommonMusic)] // [InlineData(Environment.SpecialFolder.CommonOemLinks)] [InlineData(Environment.SpecialFolder.CommonPictures)] [InlineData(Environment.SpecialFolder.CommonStartMenu)] [InlineData(Environment.SpecialFolder.CommonPrograms)] [InlineData(Environment.SpecialFolder.CommonStartup)] [InlineData(Environment.SpecialFolder.CommonDesktopDirectory)] [InlineData(Environment.SpecialFolder.CommonTemplates)] [InlineData(Environment.SpecialFolder.CommonVideos)] [InlineData(Environment.SpecialFolder.Fonts)] [InlineData(Environment.SpecialFolder.NetworkShortcuts)] // [InlineData(Environment.SpecialFolder.PrinterShortcuts)] [InlineData(Environment.SpecialFolder.UserProfile)] [InlineData(Environment.SpecialFolder.CommonProgramFilesX86)] [InlineData(Environment.SpecialFolder.ProgramFilesX86)] [InlineData(Environment.SpecialFolder.Resources)] // [InlineData(Environment.SpecialFolder.LocalizedResources)] [InlineData(Environment.SpecialFolder.SystemX86)] [InlineData(Environment.SpecialFolder.Windows)] [PlatformSpecific(TestPlatforms.Windows)] // Tests OS-specific environment public unsafe void GetFolderPath_Windows(Environment.SpecialFolder folder) { string knownFolder = Environment.GetFolderPath(folder); Assert.NotEmpty(knownFolder); // Call the older folder API to compare our results. char* buffer = stackalloc char[260]; SHGetFolderPathW(IntPtr.Zero, (int)folder, IntPtr.Zero, 0, buffer); string folderPath = new string(buffer); Assert.Equal(folderPath, knownFolder); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invokes public void GetLogicalDrives_Unix_AtLeastOneIsRoot() { string[] drives = Environment.GetLogicalDrives(); Assert.NotNull(drives); Assert.True(drives.Length > 0, "Expected at least one drive"); Assert.All(drives, d => Assert.NotNull(d)); Assert.Contains(drives, d => d == "/"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes public void GetLogicalDrives_Windows_MatchesExpectedLetters() { string[] drives = Environment.GetLogicalDrives(); uint mask = (uint)GetLogicalDrives(); var bits = new BitArray(new[] { (int)mask }); Assert.Equal(bits.Cast<bool>().Count(b => b), drives.Length); for (int bit = 0, d = 0; bit < bits.Length; bit++) { if (bits[bit]) { Assert.Contains((char)('A' + bit), drives[d++]); } } } [DllImport("kernel32.dll", SetLastError = true)] internal static extern int GetLogicalDrives(); [DllImport("shell32.dll", SetLastError = false, BestFitMapping = false, ExactSpelling = true)] internal static extern unsafe int SHGetFolderPathW( IntPtr hwndOwner, int nFolder, IntPtr hToken, uint dwFlags, char* pszPath); public static IEnumerable<object[]> EnvironmentVariableTargets { get { yield return new object[] { EnvironmentVariableTarget.Process }; if (!(s_EnvironmentRegKeysStillAccessDenied.Value)) { yield return new object[] { EnvironmentVariableTarget.User }; yield return new object[] { EnvironmentVariableTarget.Machine }; } } } private static readonly Lazy<bool> s_EnvironmentRegKeysStillAccessDenied = new Lazy<bool>( delegate () { if (!PlatformDetection.IsWindows) return false; // On Unix, registry-based environment api's won't throw a SecurityException - they just eat all writes. if (!PlatformDetection.IsWinRT) return false; // On non-appcontainer apps, these won't throw (except writes to Target.Machine on non-elevated but that's accounted for separately.) try { Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User); } catch (SecurityException) { return true; // AppX registry exemptions not yet granted (at least on this build.) } catch { return false; // Hmm... some other exception. We'll enable the individual tests and let them report it... } return false; }); } }
using System; using Gtk; using NuGet; using System.Text; using GtkNuGetPackageExplorer; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Threading.Tasks; public class MainWindow: Gtk.Window { IPackage _package; PackageMetadataView _metadataView; PackageFileListView _treeViewManager; FileContentEditor _fileContentEditor; OpenFileFromFeedDialog _openFileFromFeedDialog; FileChooserDialog _saveAsDialog; MenuItem _saveAsMenuItem; UserSettings _userSettings; UserPrefs _userPrefs; HPaned _hpaned; VPaned _rightPane; public MainWindow() : base(Gtk.WindowType.Toplevel) { LoadUserPrefs(); Build(); DragDropSetup(); LoadUserSettings(); } void LoadUserPrefs() { _userPrefs = new UserPrefs(); _userPrefs.Load(); } void LoadUserSettings() { _userSettings = new UserSettings(); _userSettings.Load(); if (_userSettings.UIFont == null) { _userSettings.UIFont = _metadataView.Font; } if (_userSettings.TextEditorFont == null) { var f = _fileContentEditor.TextEditorFont.Copy(); if (f.Family == "Mono") { f.Family = "Monospace"; } _userSettings.TextEditorFont = f.ToString(); } ApplySettings(); } protected virtual void Build() { // create menu var openMenuItem = new MenuItem("Open"); openMenuItem.Activated += (o, e) => OpenFile(); var openFromFeedMenuItem = new MenuItem("Open from feed ..."); openFromFeedMenuItem.Activated += (o, e) => OpenFileFromFeed(); _saveAsMenuItem = new MenuItem("Save as ..."); _saveAsMenuItem.Activated += (o, e) => SaveAs(); _saveAsMenuItem.Sensitive = false; var settingsMenuItem = new MenuItem("Settings"); settingsMenuItem.Activated += SettingsMenuItem_Activated; var fileMenu = new Menu(); fileMenu.Append(openMenuItem); fileMenu.Append(openFromFeedMenuItem); fileMenu.Append(_saveAsMenuItem); fileMenu.Append(settingsMenuItem); var fileMenuItem = new MenuItem("File"); fileMenuItem.Submenu = fileMenu; var menuBar = new MenuBar(); menuBar.Append(fileMenuItem); _metadataView = new PackageMetadataView(); _hpaned = new HPaned(); _hpaned.Position = _userPrefs.HPanedPosition; _hpaned.Add1(_metadataView.Widget); // tree view manager _treeViewManager = new PackageFileListView(); _treeViewManager.FileSelected += HandleFileSelected; // file content _fileContentEditor = new FileContentEditor(); _rightPane = new VPaned(); _rightPane.Position = _userPrefs.VPanedPosition; _rightPane.Add1(_treeViewManager.Widget); _rightPane.Add2(_fileContentEditor.Widget); _hpaned.Add2(_rightPane); var vbox = new VBox(); vbox.PackStart(menuBar, expand: false, fill: false, padding: 0); vbox.PackEnd(_hpaned); this.Add(vbox); vbox.ShowAll(); this.DefaultWidth = _userPrefs.WindowWidth; this.DefaultHeight = _userPrefs.WindowHeight; this.Show(); this.DeleteEvent += new global::Gtk.DeleteEventHandler(this.OnDeleteEvent); _openFileFromFeedDialog = new OpenFileFromFeedDialog(this); } void SettingsMenuItem_Activated(object sender, EventArgs e) { var userSettingsDialog = new UserSettingsDialog(this, _userSettings); int r = userSettingsDialog.Run(); if (r == (int)ResponseType.Ok) { userSettingsDialog.Destroy(); _userSettings = userSettingsDialog.UserSettings; _userSettings.Save(); ApplySettings(); } else { userSettingsDialog.Destroy(); } } private void ApplySettings() { _metadataView.Font = _userSettings.UIFont; _treeViewManager.Font = _userSettings.UIFont; _fileContentEditor.Font = _userSettings.UIFont; _fileContentEditor.TextEditorFont = Pango.FontDescription.FromString(_userSettings.TextEditorFont); } private void SaveAs() { if (_package == null) { return; } if (_saveAsDialog == null) { _saveAsDialog = new FileChooserDialog( "Save as", this, FileChooserAction.Save, Stock.Cancel, ResponseType.Cancel, Stock.Ok, ResponseType.Ok); } _saveAsDialog.CurrentName = string.Format("{0}.{1}.nupkg", _package.Id, _package.Version); _saveAsDialog.DoOverwriteConfirmation = true; var r = _saveAsDialog.Run(); _saveAsDialog.Hide(); if (r != (int)ResponseType.Ok) { return; } var fileName = _saveAsDialog.Filename; using (var f = new FileStream(fileName, FileMode.Create)) { using (var inputStream = _package.GetStream()) { inputStream.CopyTo(f); } } } private void DragDropSetup() { var targetEntries = new TargetEntry[] { new TargetEntry("text/uri-list", 0, 0) }; Drag.DestSet( this, DestDefaults.All, targetEntries, Gdk.DragAction.Copy); this.DragDataReceived += HandleDragDataReceived; } void HandleDragDataReceived (object o, DragDataReceivedArgs args) { byte[] data = args.SelectionData.Data; string s = System.Text.Encoding.UTF8.GetString(data); string[] fileList = Regex.Split(s, "\r\n"); string fileName = fileList[0]; Uri uri; if (!Uri.TryCreate(fileName, UriKind.Absolute, out uri)) { return; } if (!uri.IsFile) { return; } OpenPackageFile(uri.LocalPath); } protected void OnDeleteEvent(object sender, DeleteEventArgs a) { SaveUserPrefs(); Application.Quit(); a.RetVal = true; } private void OpenPackage(IPackage package) { _package = package; _saveAsMenuItem.Sensitive = true; _metadataView.Update(_package); _treeViewManager.Package = _package; _fileContentEditor.Clear(); _fileContentEditor.SetMode(FileContentEditorMode.FileInfo); } public void OpenPackageFile(string fileName) { try { _package = new OptimizedZipPackage(fileName); OpenPackage(_package); } catch (Exception ex) { var errorMessage = String.Format( "Error while openning file {0}: {1} ", fileName, ex.Message); var m = new MessageDialog( this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, errorMessage); m.Run(); m.Destroy(); } } private void OpenFileFromFeed() { int r = _openFileFromFeedDialog.Run(); _openFileFromFeedDialog.Hide(); if (r != (int)ResponseType.Ok) { return; } // load package in the background var package = _openFileFromFeedDialog.Package; var message = string.Format( "loading pacakge {0} {1}", package.Id, package.Version); var waitDialog = new WaitDialog(message, this); waitDialog.Show(); var task = Task.Factory.StartNew(() => { package.GetFiles(); }); GLib.Timeout.Add(100, () => { if (task.IsCompleted) { // show package waitDialog.Destroy(); OpenPackage(package); return false; } waitDialog.Pulse(); return true; }); } private void OpenFile() { FileChooserDialog fc = new FileChooserDialog( "Open package file", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "OK", ResponseType.Ok); if (fc.Run() == (int)ResponseType.Ok) { var fileName = fc.Filename; fc.Destroy(); OpenPackageFile(fileName); } else { fc.Destroy(); } } void HandleFileSelected(object sender, FileSelectedEventArgs e) { _fileContentEditor.Clear(); if (e.FilePath == null) { return; } var packageFile = _package.GetFiles().FirstOrDefault(f => f.Path == e.FilePath); _fileContentEditor.OpenFile(packageFile); } void SaveUserPrefs() { int h, w; this.GetSize(out w, out h); _userPrefs.WindowHeight = h; _userPrefs.WindowWidth = w; _userPrefs.HPanedPosition = _hpaned.Position; _userPrefs.VPanedPosition = _rightPane.Position; _userPrefs.Save(); } }
/* ----------------------------------------------------------------------------- * Rule_URI.cs * ----------------------------------------------------------------------------- * * Producer : com.parse2.aparse.Parser 2.5 * Produced : Sat Dec 18 07:35:23 GMT 2021 * * ----------------------------------------------------------------------------- */ using System; using System.Collections.Generic; sealed internal class Rule_URI:Rule { private Rule_URI(String spelling, List<Rule> rules) : base(spelling, rules) { } internal override Object Accept(Visitor visitor) { return visitor.Visit(this); } public static Rule_URI Parse(ParserContext context) { context.Push("URI"); Rule rule; bool parsed = true; ParserAlternative b; int s0 = context.index; ParserAlternative a0 = new ParserAlternative(s0); List<ParserAlternative> as1 = new List<ParserAlternative>(); parsed = false; { int s1 = context.index; ParserAlternative a1 = new ParserAlternative(s1); parsed = true; if (parsed) { bool f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { rule = Rule_scheme.Parse(context); if ((f1 = rule != null)) { a1.Add(rule, context.index); c1++; } } parsed = c1 == 1; } if (parsed) { bool f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { rule = Terminal_StringValue.Parse(context, ":"); if ((f1 = rule != null)) { a1.Add(rule, context.index); c1++; } } parsed = c1 == 1; } if (parsed) { bool f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { rule = Rule_hier_part.Parse(context); if ((f1 = rule != null)) { a1.Add(rule, context.index); c1++; } } parsed = c1 == 1; } if (parsed) { bool f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { int g1 = context.index; List<ParserAlternative> as2 = new List<ParserAlternative>(); parsed = false; { int s2 = context.index; ParserAlternative a2 = new ParserAlternative(s2); parsed = true; if (parsed) { bool f2 = true; int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { rule = Terminal_StringValue.Parse(context, "?"); if ((f2 = rule != null)) { a2.Add(rule, context.index); c2++; } } parsed = c2 == 1; } if (parsed) { bool f2 = true; int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { rule = Rule_query.Parse(context); if ((f2 = rule != null)) { a2.Add(rule, context.index); c2++; } } parsed = c2 == 1; } if (parsed) { as2.Add(a2); } context.index = s2; } b = ParserAlternative.GetBest(as2); parsed = b != null; if (parsed) { a1.Add(b.rules, b.end); context.index = b.end; } f1 = context.index > g1; if (parsed) c1++; } parsed = true; } if (parsed) { bool f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { int g1 = context.index; List<ParserAlternative> as2 = new List<ParserAlternative>(); parsed = false; { int s2 = context.index; ParserAlternative a2 = new ParserAlternative(s2); parsed = true; if (parsed) { bool f2 = true; int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { rule = Terminal_StringValue.Parse(context, "#"); if ((f2 = rule != null)) { a2.Add(rule, context.index); c2++; } } parsed = c2 == 1; } if (parsed) { bool f2 = true; int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { rule = Rule_fragment.Parse(context); if ((f2 = rule != null)) { a2.Add(rule, context.index); c2++; } } parsed = c2 == 1; } if (parsed) { as2.Add(a2); } context.index = s2; } b = ParserAlternative.GetBest(as2); parsed = b != null; if (parsed) { a1.Add(b.rules, b.end); context.index = b.end; } f1 = context.index > g1; if (parsed) c1++; } parsed = true; } if (parsed) { as1.Add(a1); } context.index = s1; } b = ParserAlternative.GetBest(as1); parsed = b != null; if (parsed) { a0.Add(b.rules, b.end); context.index = b.end; } rule = null; if (parsed) { rule = new Rule_URI(context.text.Substring(a0.start, a0.end - a0.start), a0.rules); } else { context.index = s0; } context.Pop("URI", parsed); return (Rule_URI)rule; } } /* ----------------------------------------------------------------------------- * eof * ----------------------------------------------------------------------------- */
namespace KabMan.Forms { partial class DataCenterManagerForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule2 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule1 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); this.CManagerValidator = new DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider(this.components); this.CName = new DevExpress.XtraEditors.TextEdit(); this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.CHasSwitch = new DevExpress.XtraEditors.CheckEdit(); this.CLocation = new KabMan.Controls.C_LookUpLocation(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem(); this.CManager = new KabMan.Controls.C_ControlManagerForm(); this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn2 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn3 = new DevExpress.XtraGrid.Columns.GridColumn(); ((System.ComponentModel.ISupportInitialize)(this.CManagerValidator)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CName.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.CHasSwitch.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CLocation.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit(); this.CManager.LayoutPanel.SuspendLayout(); this.SuspendLayout(); // // CName // this.CName.Location = new System.Drawing.Point(52, 38); this.CName.Name = "CName"; this.CName.Size = new System.Drawing.Size(225, 20); this.CName.StyleController = this.layoutControl1; this.CName.TabIndex = 5; conditionValidationRule2.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule2.ErrorText = "This value is not valid"; conditionValidationRule2.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CName, conditionValidationRule2); // // layoutControl1 // this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true; this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true; this.layoutControl1.Controls.Add(this.CHasSwitch); this.layoutControl1.Controls.Add(this.CName); this.layoutControl1.Controls.Add(this.CLocation); this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.layoutControl1.Location = new System.Drawing.Point(0, 0); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; this.layoutControl1.Size = new System.Drawing.Size(412, 66); this.layoutControl1.TabIndex = 0; this.layoutControl1.Text = "layoutControl1"; // // CHasSwitch // this.CHasSwitch.Location = new System.Drawing.Point(288, 38); this.CHasSwitch.Name = "CHasSwitch"; this.CHasSwitch.Properties.Caption = "Has Switch"; this.CHasSwitch.Size = new System.Drawing.Size(118, 19); this.CHasSwitch.StyleController = this.layoutControl1; this.CHasSwitch.TabIndex = 6; // // CLocation // this.CLocation.AddButtonEnabled = true; this.CLocation.Location = new System.Drawing.Point(52, 7); this.CLocation.Name = "CLocation"; this.CLocation.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.CLocation.Properties.DisplayMember = "Name"; this.CLocation.Properties.NullText = "Select Location!"; this.CLocation.Properties.ValueMember = "ID"; this.CLocation.Size = new System.Drawing.Size(354, 20); this.CLocation.StyleController = this.layoutControl1; this.CLocation.TabIndex = 4; conditionValidationRule1.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule1.ErrorText = "This value is not valid"; conditionValidationRule1.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CLocation, conditionValidationRule1); this.CLocation.EditValueChanged += new System.EventHandler(this.CLocation_EditValueChanged); // // layoutControlGroup1 // this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1"; this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem1, this.layoutControlItem2, this.layoutControlItem3}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "layoutControlGroup1"; this.layoutControlGroup1.Size = new System.Drawing.Size(412, 66); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.Text = "layoutControlGroup1"; this.layoutControlGroup1.TextVisible = false; // // layoutControlItem1 // this.layoutControlItem1.Control = this.CLocation; this.layoutControlItem1.CustomizationFormText = "Location"; this.layoutControlItem1.Location = new System.Drawing.Point(0, 0); this.layoutControlItem1.Name = "layoutControlItem1"; this.layoutControlItem1.Size = new System.Drawing.Size(410, 31); this.layoutControlItem1.Text = "Location"; this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem1.TextSize = new System.Drawing.Size(40, 13); // // layoutControlItem2 // this.layoutControlItem2.Control = this.CName; this.layoutControlItem2.CustomizationFormText = "Name"; this.layoutControlItem2.Location = new System.Drawing.Point(0, 31); this.layoutControlItem2.Name = "layoutControlItem2"; this.layoutControlItem2.Size = new System.Drawing.Size(281, 33); this.layoutControlItem2.Text = "Name"; this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem2.TextSize = new System.Drawing.Size(40, 13); // // layoutControlItem3 // this.layoutControlItem3.Control = this.CHasSwitch; this.layoutControlItem3.CustomizationFormText = "layoutControlItem3"; this.layoutControlItem3.Location = new System.Drawing.Point(281, 31); this.layoutControlItem3.Name = "layoutControlItem3"; this.layoutControlItem3.Size = new System.Drawing.Size(129, 33); this.layoutControlItem3.Text = "layoutControlItem3"; this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem3.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem3.TextToControlDistance = 0; this.layoutControlItem3.TextVisible = false; // // CManager // this.CManager.DeleteProcedure = null; this.CManager.Dock = System.Windows.Forms.DockStyle.Fill; this.CManager.InsertProcedure = null; this.CManager.IsCancel = true; this.CManager.IsEdit = false; this.CManager.IsNew = true; // // CManager.layoutControlPanel // this.CManager.LayoutPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.CManager.LayoutPanel.Controls.Add(this.layoutControl1); this.CManager.LayoutPanel.Location = new System.Drawing.Point(0, 0); this.CManager.LayoutPanel.MinimumSize = new System.Drawing.Size(400, 20); this.CManager.LayoutPanel.Name = "layoutControlPanel"; this.CManager.LayoutPanel.Size = new System.Drawing.Size(412, 66); this.CManager.LayoutPanel.TabIndex = 6; this.CManager.Location = new System.Drawing.Point(0, 0); this.CManager.MinimumSize = new System.Drawing.Size(400, 460); this.CManager.Name = "CManager"; this.CManager.SelectParameters = null; this.CManager.SelectRequiresParameter = true; this.CManager.Size = new System.Drawing.Size(412, 466); this.CManager.TabIndex = 0; this.CManager.UpdateProcedure = null; // // gridColumn1 // this.gridColumn1.Caption = "ID"; this.gridColumn1.FieldName = "ID"; this.gridColumn1.Name = "gridColumn1"; // // gridColumn2 // this.gridColumn2.Caption = "Name"; this.gridColumn2.FieldName = "Name"; this.gridColumn2.Name = "gridColumn2"; // // gridColumn3 // this.gridColumn3.Caption = "Has Switch"; this.gridColumn3.FieldName = "HasSwitch"; this.gridColumn3.Name = "gridColumn3"; // // DataCenterManagerForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(412, 466); this.Controls.Add(this.CManager); this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(420, 500); this.Name = "DataCenterManagerForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Data Center Manager"; this.Load += new System.EventHandler(this.DataCenterManagerForm_Load); ((System.ComponentModel.ISupportInitialize)(this.CManagerValidator)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CName.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.CHasSwitch.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CLocation.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit(); this.CManager.LayoutPanel.ResumeLayout(false); this.ResumeLayout(false); } #endregion private KabMan.Controls.C_ControlManagerForm CManager; private DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider CManagerValidator; private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private DevExpress.XtraEditors.CheckEdit CHasSwitch; private DevExpress.XtraEditors.TextEdit CName; private KabMan.Controls.C_LookUpLocation CLocation; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3; private DevExpress.XtraGrid.Columns.GridColumn gridColumn1; private DevExpress.XtraGrid.Columns.GridColumn gridColumn2; private DevExpress.XtraGrid.Columns.GridColumn gridColumn3; } }
//------------------------------------------------------------------------------ // <copyright file="DeviceSpecificChoice.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Web; using System.Web.UI; using System.Web.Mobile; using System.Security.Permissions; namespace System.Web.UI.MobileControls { /* * DeviceSpecificChoice object. * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoice"]/*' /> [ ControlBuilderAttribute(typeof(DeviceSpecificChoiceControlBuilder)), PersistName("Choice"), PersistChildren(false), ] [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class DeviceSpecificChoice : IParserAccessor, IAttributeAccessor { private String _deviceFilter = String.Empty; private String _argument; private String _xmlns; private IDictionary _contents; private IDictionary _templates; private DeviceSpecific _owner; private static IComparer _caseInsensitiveComparer = new CaseInsensitiveComparer(CultureInfo.InvariantCulture); /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoice.Filter"]/*' /> [ DefaultValue("") ] public String Filter { get { Debug.Assert(_deviceFilter != null); return _deviceFilter; } set { if (value == null) { value = String.Empty; } _deviceFilter = value; } } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoice.Argument"]/*' /> public String Argument { get { return _argument; } set { _argument = value; } } // This property is used by the Designer, and has no runtime effect /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoice.Xmlns"]/*' /> [ DefaultValue("") ] public String Xmlns { get { return _xmlns; } set { _xmlns = value; } } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoice.Contents"]/*' /> [ DesignerSerializationVisibility(DesignerSerializationVisibility.Content), ] public IDictionary Contents { get { if (_contents == null) { _contents = new ListDictionary(_caseInsensitiveComparer); } return _contents; } } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoice.Templates"]/*' /> [ PersistenceMode(PersistenceMode.InnerProperty), ] public IDictionary Templates { get { if (_templates == null) { _templates = new ListDictionary(_caseInsensitiveComparer); } return _templates; } } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoice.HasTemplates"]/*' /> [ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public bool HasTemplates { get { return _templates != null && _templates.Count > 0; } } internal void ApplyProperties() { IDictionaryEnumerator enumerator = Contents.GetEnumerator(); while (enumerator.MoveNext()) { Object parentObject = Owner.Owner; String propertyName = (String)enumerator.Key; String propertyValue = enumerator.Value as String; // The ID property may not be overridden, according to spec // (since it will override the parent's ID, not very useful). if (String.Equals(propertyName, "id", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException( SR.GetString(SR.DeviceSpecificChoice_InvalidPropertyOverride, propertyName)); } if (propertyValue != null) { // Parse through any "-" syntax items. int dash; while ((dash = propertyName.IndexOf("-", StringComparison.Ordinal)) != -1) { String containingObjectName = propertyName.Substring(0, dash); PropertyDescriptor pd = TypeDescriptor.GetProperties(parentObject).Find( containingObjectName, true); if (pd == null) { throw new ArgumentException( SR.GetString(SR.DeviceSpecificChoice_OverridingPropertyNotFound, propertyName)); } parentObject = pd.GetValue(parentObject); propertyName = propertyName.Substring(dash + 1); } if (!FindAndApplyProperty(parentObject, propertyName, propertyValue) && !FindAndApplyEvent(parentObject, propertyName, propertyValue)) { // If control supports IAttributeAccessor (which it should) // use it to set a custom attribute. IAttributeAccessor a = parentObject as IAttributeAccessor; if (a != null) { a.SetAttribute(propertyName, propertyValue); } else { throw new ArgumentException( SR.GetString(SR.DeviceSpecificChoice_OverridingPropertyNotFound, propertyName)); } } } } } private bool FindAndApplyProperty(Object parentObject, String name, String value) { PropertyDescriptor pd = TypeDescriptor.GetProperties(parentObject).Find(name, true); if (pd == null) { return false; } // Make sure the property is declarable. if (pd.Attributes.Contains(DesignerSerializationVisibilityAttribute.Hidden)) { throw new ArgumentException( SR.GetString(SR.DeviceSpecificChoice_OverridingPropertyNotDeclarable, name)); } Object o; Type type = pd.PropertyType; if (type.IsAssignableFrom(typeof(String))) { o = value; } else if (type.IsAssignableFrom(typeof(int))) { o = Int32.Parse(value, CultureInfo.InvariantCulture); } else if (type.IsEnum) { o = Enum.Parse(type, value, true); } else if (value.Length == 0) { o = null; } else { TypeConverter converter = pd.Converter; if (converter != null) { o = converter.ConvertFromInvariantString(value); } else { throw new InvalidCastException( SR.GetString(SR.DeviceSpecificChoice_OverridingPropertyTypeCast, name)); } } pd.SetValue(parentObject, o); return true; } private bool FindAndApplyEvent(Object parentObject, String name, String value) { if (name.Length > 2 && Char.ToLower(name[0], CultureInfo.InvariantCulture) == 'o' && Char.ToLower(name[1], CultureInfo.InvariantCulture) == 'n') { String eventName = name.Substring(2); EventDescriptor ed = TypeDescriptor.GetEvents(parentObject).Find(eventName, true); if (ed != null) { Delegate d = Delegate.CreateDelegate(ed.EventType, Owner.MobilePage, value); ed.AddEventHandler(parentObject, d); return true; } } return false; } internal DeviceSpecific Owner { get { return _owner; } set { _owner = value; } } internal bool Evaluate(MobileCapabilities capabilities) { // Evaluate the <Choice> by first looking to see if it's null, then // checking against evaluators defined in code on the page, then by // consulting the MobileCapabilities object. bool result; if (_deviceFilter != null && _deviceFilter.Length == 0) { // indicates device-independent <choice> clause result = true; } else if (CheckOnPageEvaluator(capabilities, out result)) { // result already been set through the out-bound parameter // above. } else { // The exception message generated by HasCapability() failing is // inappropriate, so we substitute a more specific one. try { result = capabilities.HasCapability(_deviceFilter, _argument); } catch { throw new ArgumentException(SR.GetString( SR.DeviceSpecificChoice_CantFindFilter, _deviceFilter)); } } return result; } // Return true if specified evaluator exists on the page with the // correct signature. If it does, return result of invoking it in // evaluatorResult. private bool CheckOnPageEvaluator(MobileCapabilities capabilities, out bool evaluatorResult) { evaluatorResult = false; TemplateControl containingTemplateControl = Owner.ClosestTemplateControl; MethodInfo methodInfo = containingTemplateControl.GetType().GetMethod(_deviceFilter, new Type[] { typeof(MobileCapabilities), typeof(String) } ); if (methodInfo == null || methodInfo.ReturnType != typeof(bool)) { return false; } else { evaluatorResult = (bool) methodInfo.Invoke(containingTemplateControl, new Object[] { capabilities, _argument } ); return true; } } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoice.IAttributeAccessor.GetAttribute"]/*' /> /// <internalonly/> protected String GetAttribute(String key) { Object o = Contents[key]; if (o != null & !(o is String)) { throw new ArgumentException(SR.GetString( SR.DeviceSpecificChoice_PropertyNotAnAttribute)); } return (String)o; } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoice.IAttributeAccessor.SetAttribute"]/*' /> /// <internalonly/> protected void SetAttribute(String key, String value) { Contents[key] = value; } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoice.IParserAccessor.AddParsedSubObject"]/*' /> /// <internalonly/> protected void AddParsedSubObject(Object obj) { DeviceSpecificChoiceTemplateContainer c = obj as DeviceSpecificChoiceTemplateContainer; if (c != null) { Templates[c.Name] = c.Template; } } #region IAttributeAccessor implementation String IAttributeAccessor.GetAttribute(String name) { return GetAttribute(name); } void IAttributeAccessor.SetAttribute(String name, String value) { SetAttribute(name, value); } #endregion #region IParserAccessor implementation void IParserAccessor.AddParsedSubObject(Object obj) { AddParsedSubObject(obj); } #endregion } // TEMPLATE BAG // // The following classes are public by necessity (since they are exposed to // the framework), but all internal to the DeviceSpecificChoice. They have to do with // persistence of arbitrary templates in a choice. Here's a description of what is done: // // ASP.NET provides no way for an object or control to allow an arbitrary bag of // templates. It only allows one way to define templates - the parent object must have // a property, of type ITemplate, with the same name as the template name. For example, // the code // // <ParentCtl> // <FirstTemplate>....</FirstTemplate> // <SecondTemplate>....</SecondTemplate> // <ThirdTemplate>....</ThirdTemplate> // </ParentCtl> // // only works if the ParentCtl class exposes ITemplate properties with names FirstTemplate, // SecondTemplate, and ThirdTemplate. // // Because Choices apply to any control, that could potentially require any named template, // what we really need is something like a "template bag" that takes arbitrary templates. // // To work around this, here's what is done. First, at compile time: // // 1) DeviceSpecificChoice has its own control builder at compile time. When it is given a // sub-object (in GetChildControlType), it returns DeviceSpecificChoiceTemplateType, which // is a marker type similar to that used in ASP.NET. However, it is our own class, and // has DeviceSpecificChoiceTemplateBuilder as its builder. // 2) DeviceSpecificChoiceTemplateBuilder inherits from TemplateBuilder, and thus has the same // behavior as TemplateBuilder for parsing and compiling a template. However, it has // an overriden Init method, which changes the tag name (and thus, the template name) // to a constant, "Template". It also saves the real template name in a property. // 3) When parsed, the framework calls the AppendSubBuilder method of the // DeviceSpecificChoiceBuilder, to add the template builder into it. But this builder // first creates an intermediate builder, for the class DeviceSpecificChoiceTemplateContainer, // adding the template name as a property in the builder's attribute dictionary. It then // adds the intermediate builder into itself, and the template builder into it. // // All this has the net effect of automatically transforming something like // // <Choice> // <ItemTemplate>...</ItemTemplate> // <HeaderTemplate>...</HeaderTemplate> // </Choice> // // into // // <Choice> // <DeviceSpecificChoiceTemplateContainer Name="ItemTemplate"> // <Template>...</Template> // </DeviceSpecificChoiceTemplateContainer> // <DeviceSpecificChoiceTemplateContainer Name="HeaderTemplate"> // <Template>...</Template> // </DeviceSpecificChoiceTemplateContainer> // </Choice> // // Now, at runtime the compiled code creates a DeviceSpecificChoiceTemplateContainer object, // and calls the AddParsedSubObject method of the DeviceSpecificChoice with it. This code (above) // then extracts the template referred to by the Template property of the object, and // uses the Name property to add it to the template bag. Presto, we have a general template bag. /* * DeviceSpecificChoice control builder. For more information, see note on "Template Bag" above. * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoiceControlBuilder"]/*' /> [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class DeviceSpecificChoiceControlBuilder : ControlBuilder { private bool _isDeviceIndependent = false; internal bool IsDeviceIndependent() { return _isDeviceIndependent; } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoiceControlBuilder.Init"]/*' /> public override void Init(TemplateParser parser, ControlBuilder parentBuilder, Type type, String tagName, String id, IDictionary attributes) { if (!(parentBuilder is DeviceSpecificControlBuilder)) { throw new ArgumentException( SR.GetString(SR.DeviceSpecificChoice_ChoiceOnlyExistInDeviceSpecific)); } _isDeviceIndependent = attributes == null || attributes["Filter"] == null; base.Init (parser, parentBuilder, type, tagName, id, attributes); } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoiceControlBuilder.AppendLiteralString"]/*' /> public override void AppendLiteralString(String text) { // Ignore literal strings. } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoiceControlBuilder.GetChildControlType"]/*' /> public override Type GetChildControlType(String tagName, IDictionary attributes) { // Assume children are templates. return typeof(DeviceSpecificChoiceTemplateType); } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoiceControlBuilder.AppendSubBuilder"]/*' /> public override void AppendSubBuilder(ControlBuilder subBuilder) { DeviceSpecificChoiceTemplateBuilder tplBuilder = subBuilder as DeviceSpecificChoiceTemplateBuilder; if (tplBuilder != null) { // Called to add a template. Insert an intermediate control, // by creating and adding its builder. ListDictionary dict = new ListDictionary(); // Add the template's name as a Name attribute for the control. dict["Name"] = tplBuilder.TemplateName; // 1 and "xxxx" are bogus filename/line number values. ControlBuilder container = ControlBuilder.CreateBuilderFromType( Parser, this, typeof(DeviceSpecificChoiceTemplateContainer), "Templates", null, dict, 1, null); base.AppendSubBuilder(container); // Now, append the template builder into the new intermediate builder. container.AppendSubBuilder(subBuilder); } else { base.AppendSubBuilder(subBuilder); } } } /* * DeviceSpecificChoiceTemplateType - marker type for a template that goes inside * a Choice. Used only at compile time, and never instantiated. See note * on "Template Bag" above. * * Copyright (c) 2000 Microsoft Corporation */ [ ControlBuilderAttribute(typeof(DeviceSpecificChoiceTemplateBuilder)) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal class DeviceSpecificChoiceTemplateType : Control, IParserAccessor { private DeviceSpecificChoiceTemplateType() { } void IParserAccessor.AddParsedSubObject(Object o) { } } /* * DeviceSpecificChoiceTemplateBuilder - builder for a template that goes inside * a Choice. See note on "Template Bag" above. * When a Choice is device-independent, it also parses literal text content. * The code for this is copied from LiteralTextContainerControlBuilder.cs * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoiceTemplateBuilder"]/*' /> [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class DeviceSpecificChoiceTemplateBuilder : TemplateBuilder { private String _templateName; private bool _doLiteralText = false; private bool _controlsInserted = false; internal String TemplateName { get { return _templateName; } } CompileLiteralTextParser _textParser = null; internal CompileLiteralTextParser TextParser { get { if (_textParser == null) { _textParser = new CompileLiteralTextParser(Parser, this, "xxxx", 1); if (_controlsInserted) { _textParser.ResetBreaking(); _textParser.ResetNewParagraph(); } } return _textParser; } } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoiceTemplateBuilder.Init"]/*' /> public override void Init(TemplateParser parser, ControlBuilder parentBuilder, Type type, String tagName, String id, IDictionary attributes) { // Save off template name, and always pass the name "Template" to the base // class, because the intermediate object has this property as the name. _templateName = tagName; base.Init(parser, parentBuilder, type, "Template", id, attributes); // Are we a device-independent template? if (!InDesigner) { DeviceSpecificChoiceControlBuilder choiceBuilder = parentBuilder as DeviceSpecificChoiceControlBuilder; _doLiteralText = choiceBuilder != null && choiceBuilder.IsDeviceIndependent(); } } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoiceTemplateBuilder.AppendLiteralString"]/*' /> public override void AppendLiteralString(String text) { if (_doLiteralText) { if (LiteralTextParser.IsValidText(text)) { TextParser.Parse(text); } } else { base.AppendLiteralString(text); } } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoiceTemplateBuilder.AppendSubBuilder"]/*' /> public override void AppendSubBuilder(ControlBuilder subBuilder) { if (_doLiteralText) { // The first one is used if ASP.NET is compiled with FAST_DATABINDING off. The second // is used if it is compiled with FAST_DATABINDING on. Note: We can't do a type // comparison because CodeBlockBuilder is internal. // if (typeof(DataBoundLiteralControl).IsAssignableFrom(subBuilder.ControlType)) if (subBuilder.GetType().FullName == "System.Web.UI.CodeBlockBuilder") { TextParser.AddDataBinding(subBuilder); } else { base.AppendSubBuilder(subBuilder); if (subBuilder.ControlType != typeof(LiteralText)) { if (_textParser != null) { _textParser.ResetBreaking(); } else { _controlsInserted = true; } } } } else { base.AppendSubBuilder(subBuilder); } } } /* * DeviceSpecificChoiceTemplateContainer - "dummy" container object for * a template that goes inside a Choice. Once the Choice receives and * extracts the information out of it, this object is simply discarded. * See note on "Template Bag" above. * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoiceTemplateContainer"]/*' /> [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class DeviceSpecificChoiceTemplateContainer { private ITemplate _template; private String _name; /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoiceTemplateContainer.Template"]/*' /> [ Filterable(false), TemplateContainer(typeof(TemplateContainer)), ] public ITemplate Template { get { return _template; } set { _template = value; } } /// <include file='doc\DeviceSpecificChoice.uex' path='docs/doc[@for="DeviceSpecificChoiceTemplateContainer.Name"]/*' /> public String Name { get { return _name; } set { _name = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel.Composition.Hosting; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Text; using Microsoft.Internal; namespace System.ComponentModel.Composition.Primitives { /// <summary> /// Represents a contract name and metadata-based import /// required by a <see cref="ComposablePart"/> object. /// </summary> public class ContractBasedImportDefinition : ImportDefinition { // Unlike contract name, both metadata and required metadata has a sensible default; set it to an empty // enumerable, so that derived definitions only need to override ContractName by default. private readonly IEnumerable<KeyValuePair<string, Type>> _requiredMetadata = Enumerable.Empty<KeyValuePair<string, Type>>(); private Expression<Func<ExportDefinition, bool>> _constraint; private readonly CreationPolicy _requiredCreationPolicy = CreationPolicy.Any; private readonly string _requiredTypeIdentity = null; private bool _isRequiredMetadataValidated = false; /// <summary> /// Initializes a new instance of the <see cref="ContractBasedImportDefinition"/> class. /// </summary> /// <remarks> /// <note type="inheritinfo"> /// Derived types calling this constructor can optionally override the /// <see cref="ImportDefinition.ContractName"/>, <see cref="RequiredTypeIdentity"/>, /// <see cref="RequiredMetadata"/>, <see cref="ImportDefinition.Cardinality"/>, /// <see cref="ImportDefinition.IsPrerequisite"/>, <see cref="ImportDefinition.IsRecomposable"/> /// and <see cref="RequiredCreationPolicy"/> properties. /// </note> /// </remarks> protected ContractBasedImportDefinition() { } /// <summary> /// Initializes a new instance of the <see cref="ContractBasedImportDefinition"/> class /// with the specified contract name, required metadataq, cardinality, value indicating /// if the import definition is recomposable and a value indicating if the import definition /// is a prerequisite. /// </summary> /// <param name="contractName"> /// A <see cref="String"/> containing the contract name of the /// <see cref="Export"/> required by the <see cref="ContractBasedImportDefinition"/>. /// </param> /// <param name="requiredTypeIdentity"> /// The type identity of the export type expected. Use <see cref="AttributedModelServices.GetTypeIdentity(Type)"/> /// to generate a type identity for a given type. If no specific type is required pass <see langword="null"/>. /// </param> /// <param name="requiredMetadata"> /// An <see cref="IEnumerable{T}"/> of <see cref="String"/> objects containing /// the metadata names of the <see cref="Export"/> required by the /// <see cref="ContractBasedImportDefinition"/>; or <see langword="null"/> to /// set the <see cref="RequiredMetadata"/> property to an empty <see cref="IEnumerable{T}"/>. /// </param> /// <param name="cardinality"> /// One of the <see cref="ImportCardinality"/> values indicating the /// cardinality of the <see cref="Export"/> objects required by the /// <see cref="ContractBasedImportDefinition"/>. /// </param> /// <param name="isRecomposable"> /// <see langword="true"/> if the <see cref="ContractBasedImportDefinition"/> can be satisfied /// multiple times throughout the lifetime of a <see cref="ComposablePart"/>, otherwise, /// <see langword="false"/>. /// </param> /// <param name="isPrerequisite"> /// <see langword="true"/> if the <see cref="ContractBasedImportDefinition"/> is required to be /// satisfied before a <see cref="ComposablePart"/> can start producing exported /// objects; otherwise, <see langword="false"/>. /// </param> /// <param name="requiredCreationPolicy"> /// A value indicating that the importer requires a specific <see cref="CreationPolicy"/> for /// the exports used to satisfy this import. If no specific <see cref="CreationPolicy"/> is needed /// pass the default <see cref="CreationPolicy.Any"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="contractName"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="contractName"/> is an empty string (""). /// <para> /// -or- /// </para> /// <paramref name="requiredMetadata"/> contains an element that is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="cardinality"/> is not one of the <see cref="ImportCardinality"/> /// values. /// </exception> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy) : this(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy, MetadataServices.EmptyMetadata) { } /// <summary> /// Initializes a new instance of the <see cref="ContractBasedImportDefinition"/> class /// with the specified contract name, required metadataq, cardinality, value indicating /// if the import definition is recomposable and a value indicating if the import definition /// is a prerequisite. /// </summary> /// <param name="contractName"> /// A <see cref="String"/> containing the contract name of the /// <see cref="Export"/> required by the <see cref="ContractBasedImportDefinition"/>. /// </param> /// <param name="requiredTypeIdentity"> /// The type identity of the export type expected. Use <see cref="AttributedModelServices.GetTypeIdentity(Type)"/> /// to generate a type identity for a given type. If no specific type is required pass <see langword="null"/>. /// </param> /// <param name="requiredMetadata"> /// An <see cref="IEnumerable{T}"/> of <see cref="String"/> objects containing /// the metadata names of the <see cref="Export"/> required by the /// <see cref="ContractBasedImportDefinition"/>; or <see langword="null"/> to /// set the <see cref="RequiredMetadata"/> property to an empty <see cref="IEnumerable{T}"/>. /// </param> /// <param name="cardinality"> /// One of the <see cref="ImportCardinality"/> values indicating the /// cardinality of the <see cref="Export"/> objects required by the /// <see cref="ContractBasedImportDefinition"/>. /// </param> /// <param name="isRecomposable"> /// <see langword="true"/> if the <see cref="ContractBasedImportDefinition"/> can be satisfied /// multiple times throughout the lifetime of a <see cref="ComposablePart"/>, otherwise, /// <see langword="false"/>. /// </param> /// <param name="isPrerequisite"> /// <see langword="true"/> if the <see cref="ContractBasedImportDefinition"/> is required to be /// satisfied before a <see cref="ComposablePart"/> can start producing exported /// objects; otherwise, <see langword="false"/>. /// </param> /// <param name="requiredCreationPolicy"> /// A value indicating that the importer requires a specific <see cref="CreationPolicy"/> for /// the exports used to satisfy this import. If no specific <see cref="CreationPolicy"/> is needed /// pass the default <see cref="CreationPolicy.Any"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="contractName"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="contractName"/> is an empty string (""). /// <para> /// -or- /// </para> /// <paramref name="requiredMetadata"/> contains an element that is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="cardinality"/> is not one of the <see cref="ImportCardinality"/> /// values. /// </exception> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy, IDictionary<string, object> metadata) : base(contractName, cardinality, isRecomposable, isPrerequisite, metadata) { Requires.NotNullOrEmpty(contractName, "contractName"); _requiredTypeIdentity = requiredTypeIdentity; if (requiredMetadata != null) { _requiredMetadata = requiredMetadata; } _requiredCreationPolicy = requiredCreationPolicy; } /// <summary> /// The type identity of the export type expected. /// </summary> /// <value> /// A <see cref="string"/> that is generated by <see cref="AttributedModelServices.GetTypeIdentity(Type)"/> /// on the type that this import expects. If the value is <see langword="null"/> then this import /// doesn't expect a particular type. /// </value> public virtual string RequiredTypeIdentity { get { return _requiredTypeIdentity; } } /// <summary> /// Gets the metadata names of the export required by the import definition. /// </summary> /// <value> /// An <see cref="IEnumerable{T}"/> of pairs of metadata keys and types of the <see cref="Export"/> required by the /// <see cref="ContractBasedImportDefinition"/>. The default is an empty /// <see cref="IEnumerable{T}"/>. /// </value> /// <remarks> /// <note type="inheritinfo"> /// Overriders of this property should never return <see langword="null"/> /// or return an <see cref="IEnumerable{T}"/> that contains an element that is /// <see langword="null"/>. If the definition does not contain required metadata, /// return an empty <see cref="IEnumerable{T}"/> instead. /// </note> /// </remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public virtual IEnumerable<KeyValuePair<string, Type>> RequiredMetadata { get { Contract.Ensures(Contract.Result<IEnumerable<KeyValuePair<string, Type>>>() != null); // NOTE : unlike other arguments, we validate this one as late as possible, because its validation may lead to type loading ValidateRequiredMetadata(); return _requiredMetadata; } } private void ValidateRequiredMetadata() { if (!_isRequiredMetadataValidated) { foreach (KeyValuePair<string, Type> metadataItem in _requiredMetadata) { if ((metadataItem.Key == null) || (metadataItem.Value == null)) { throw new InvalidOperationException( string.Format(CultureInfo.CurrentCulture, SR.Argument_NullElement, "requiredMetadata")); } } _isRequiredMetadataValidated = true; } } /// <summary> /// Gets or sets a value indicating that the importer requires a specific /// <see cref="CreationPolicy"/> for the exports used to satisfy this import. T /// </summary> /// <value> /// <see cref="CreationPolicy.Any"/> - default value, used if the importer doesn't /// require a specific <see cref="CreationPolicy"/>. /// /// <see cref="CreationPolicy.Shared"/> - Requires that all exports used should be shared /// by everyone in the container. /// /// <see cref="CreationPolicy.NonShared"/> - Requires that all exports used should be /// non-shared in a container and thus everyone gets their own instance. /// </value> public virtual CreationPolicy RequiredCreationPolicy { get { return _requiredCreationPolicy; } } /// <summary> /// Gets an expression that defines conditions that must be matched for the import /// described by the import definition to be satisfied. /// </summary> /// <returns> /// A <see cref="Expression{TDelegate}"/> containing a <see cref="Func{T, TResult}"/> /// that defines the conditions that must be matched for the /// <see cref="ImportDefinition"/> to be satisfied by an <see cref="Export"/>. /// </returns> /// <remarks> /// <para> /// This property returns an expression that defines conditions based on the /// <see cref="ImportDefinition.ContractName"/>, <see cref="RequiredTypeIdentity"/>, /// <see cref="RequiredMetadata"/>, and <see cref="RequiredCreationPolicy"/> /// properties. /// </para> /// </remarks> public override Expression<Func<ExportDefinition, bool>> Constraint { get { if (_constraint == null) { _constraint = ConstraintServices.CreateConstraint(ContractName, RequiredTypeIdentity, RequiredMetadata, RequiredCreationPolicy); } return _constraint; } } /// <summary> /// Executes an optimized version of the contraint given by the <see cref="Constraint"/> property /// </summary> /// <param name="exportDefinition"> /// A definition for a <see cref="Export"/> used to determine if it satisfies the /// requirements for this <see cref="ImportDefinition"/>. /// </param> /// <returns> /// <see langword="True"/> if the <see cref="Export"/> satisfies the requirements for /// this <see cref="ImportDefinition"/>, otherwise returns <see langword="False"/>. /// </returns> /// <remarks> /// <note type="inheritinfo"> /// Overrides of this method can provide a more optimized execution of the /// <see cref="Constraint"/> property but the result should remain consistent. /// </note> /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="exportDefinition"/> is <see langword="null"/>. /// </exception> public override bool IsConstraintSatisfiedBy(ExportDefinition exportDefinition) { Requires.NotNull(exportDefinition, nameof(exportDefinition)); if (!StringComparers.ContractName.Equals(ContractName, exportDefinition.ContractName)) { return false; } return MatchRequiredMetadata(exportDefinition); } private bool MatchRequiredMetadata(ExportDefinition definition) { if (!string.IsNullOrEmpty(RequiredTypeIdentity)) { string exportTypeIdentity = definition.Metadata.GetValue<string>(CompositionConstants.ExportTypeIdentityMetadataName); if (!StringComparers.ContractName.Equals(RequiredTypeIdentity, exportTypeIdentity)) { return false; } } foreach (KeyValuePair<string, Type> metadataItem in RequiredMetadata) { string metadataKey = metadataItem.Key; Type metadataValueType = metadataItem.Value; object metadataValue = null; if (!definition.Metadata.TryGetValue(metadataKey, out metadataValue)) { return false; } if (metadataValue != null) { // the metadata value is not null, we can rely on IsInstanceOfType to do the right thing if (!metadataValueType.IsInstanceOfType(metadataValue)) { return false; } } else { // this is an unfortunate special case - typeof(object).IsInstanceofType(null) == false // basically nulls are not considered valid values for anything // We want them to match anything that is a reference type if (metadataValueType.IsValueType) { // this is a pretty expensive check, but we only invoke it when metadata values are null, which is very rare return false; } } } if (RequiredCreationPolicy == CreationPolicy.Any) { return true; } CreationPolicy exportPolicy = definition.Metadata.GetValue<CreationPolicy>(CompositionConstants.PartCreationPolicyMetadataName); return exportPolicy == CreationPolicy.Any || exportPolicy == RequiredCreationPolicy; } public override string ToString() { var sb = new StringBuilder(); sb.Append(string.Format("\n\tContractName\t{0}", ContractName)); sb.Append(string.Format("\n\tRequiredTypeIdentity\t{0}", RequiredTypeIdentity)); if(_requiredCreationPolicy != CreationPolicy.Any) { sb.Append(string.Format("\n\tRequiredCreationPolicy\t{0}", RequiredCreationPolicy)); } if(_requiredMetadata.Count() > 0) { sb.Append(string.Format("\n\tRequiredMetadata")); foreach (KeyValuePair<string, Type> metadataItem in _requiredMetadata) { sb.Append(string.Format("\n\t\t{0}\t({1})", metadataItem.Key, metadataItem.Value)); } } return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using DoVuiHaiNao.Data; using DoVuiHaiNao.Models; using DoVuiHaiNao.Areas.WebManager.Data; using DoVuiHaiNao.Areas.WebManager.ViewModels.PostViewModels; using DoVuiHaiNao.Areas.WebManager.ViewModels; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Authorization; namespace DoVuiHaiNao.Areas.WebManager.Controllers { [Area("WebManager")] [Authorize(Roles = "Admin, Manager")] public class PostsController : Controller { private readonly ApplicationDbContext _context; private readonly IPostManagerRepository _repository; private readonly UserManager<Member> _userManager; public PostsController( ApplicationDbContext context, IPostManagerRepository repository, UserManager<Member> userManager) { _repository = repository; _context = context; _userManager = userManager; } // GET: WebManager/Posts [Route("/quan-ly-web/blog/")] public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? page, int? pageSize) { List<NumberItem> SoLuong = new List<NumberItem> { new NumberItem { Value = 10}, new NumberItem { Value = 20}, new NumberItem { Value = 50}, new NumberItem { Value = 100}, }; ViewData["SoLuong"] = SoLuong; ViewData["CurrentSort"] = sortOrder; ViewData["TitleParm"] = String.IsNullOrEmpty(sortOrder) ? "title" : ""; ViewData["CurrentSize"] = pageSize; if (searchString != null) { page = 1; } else { searchString = currentFilter; } ViewData["CurrentFilter"] = searchString; var applicationDbContext = await _repository.GetAll(sortOrder, searchString, page, pageSize); return View(applicationDbContext); } private async Task<Member> GetCurrentUser() { return await _userManager.GetUserAsync(HttpContext.User); } // GET: WebManager/Posts/Details/5 [Route("/quan-ly-web/blog/chi-tiet/{id}")] public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var post = await _repository.Get(id); if (post == null) { return NotFound(); } return View(post); } // GET: WebManager/Posts/Create [Route("/quan-ly-web/blog/tao-moi")] public IActionResult Create() { ViewData["ImageID"] = new SelectList(_context.Images, "ID", "Name"); return View(); } // POST: WebManager/Posts/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] [Route("/quan-ly-web/blog/tao-moi")] public async Task<IActionResult> Create( CreatePostViewModel post) { if (ModelState.IsValid) { var user = await GetCurrentUser(); post.AuthorID = user.Id; await _repository.Add(post); return RedirectToAction("Index"); } ViewData["ImageID"] = new SelectList(_context.Images, "ID", "Name", post.ImageID); return View(post); } // GET: WebManager/Posts/Edit/5 [Route("/quan-ly-web/blog/chinh-sua/{id}")] public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var post = await _repository.GetEdit(id); if (post == null) { return NotFound(); } AllSelectList selectlist = new AllSelectList(); ViewData["Approved"] = new SelectList(selectlist.ListApproved, "ID", "Name", post.Approved); ViewData["AuthorID"] = new SelectList(_context.Member, "Id", "FullName", post.AuthorID); ViewData["ImageID"] = new SelectList(_context.Images, "ID", "Name", post.ImageID); return View(post); } // POST: WebManager/Posts/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [Route("/quan-ly-web/blog/chinh-sua/{id}")] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, EditPostViewModel post) { if (id != post.ID) { return NotFound(); } if (ModelState.IsValid) { try { await _repository.Update(post); } catch (DbUpdateConcurrencyException) { if (!PostExists(post.ID)) { return NotFound(); } else { throw; } } return RedirectToAction("Index"); } AllSelectList selectlist = new AllSelectList(); ViewData["Approved"] = new SelectList(selectlist.ListApproved, "ID", "Name", post.Approved); ViewData["AuthorID"] = new SelectList(_context.Member, "Id", "FullName", post.AuthorID); ViewData["ImageID"] = new SelectList(_context.Images, "ID", "Name", post.ImageID); return View(post); } // GET: WebManager/Posts/Delete/5 [Route("/quan-ly-web/blog/xoa/{id}")] public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var post = await _repository.Get(id); if (post == null) { return NotFound(); } return View(post); } // POST: WebManager/Posts/Delete/5 [HttpPost, ActionName("Delete")] [Route("/quan-ly-web/blog/xoa/{id}")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { await _repository.Delete(id); return RedirectToAction("Index"); } private bool PostExists(int id) { return _repository.Exists(id); } } }
/* * CKFinder * ======== * http://cksource.com/ckfinder * Copyright (C) 2007-2013, CKSource - Frederico Knabben. All rights reserved. * * The software, this file and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying or distribute this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. */ // To disabled special debugging features, simply uncomment this line. // #undef DEBUG using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Web.UI; using System.Reflection; namespace CKFinder.Connector { /// <summary> /// The class handles all requests sent to the CKFinder connector file, /// connector.aspx. /// </summary> public class Connector : Page { /// <summary> /// The "ConfigFile" object, is the instance of config.ascx, present in /// the connector.aspx file. It makes it possible to configure CKFinder /// whithout having to compile it. /// </summary> public Settings.ConfigFile ConfigFile; public CKFinderPlugin[] Plugins; public List<string> JavascriptPlugins; public CKFinderEvent CKFinderEvent = new CKFinderEvent(); #region Disable ASP.NET features /// <summary> /// Theming is disabled as it interferes in the connector response data. /// </summary> public override bool EnableTheming { get { return false; } set { /* Ignore it with no error */ } } /// <summary> /// Master Page is disabled as it interferes in the connector response data. /// </summary> public override string MasterPageFile { get { return null; } set { /* Ignore it with no error */ } } /// <summary> /// Theming is disabled as it interferes in the connector response data. /// </summary> public override string Theme { get { return ""; } set { /* Ignore it with no error */ } } /// <summary> /// Theming is disabled as it interferes in the connector response data. /// </summary> public override string StyleSheetTheme { get { return ""; } set { /* Ignore it with no error */ } } #endregion protected void LoadPlugins() { Config _Config = Config.Current; if ( _Config.Plugins == null || _Config.Plugins.Length == 0 ) return; Plugins = new CKFinderPlugin[_Config.Plugins.Length]; JavascriptPlugins = new List<string>(); for ( int i = 0; i < _Config.Plugins.Length; i++ ) { int j = 0; if ( _Config.Plugins[i].IndexOf( "," ) != -1 ) { this.Plugins[j] = (CKFinderPlugin)Activator.CreateInstance( Type.GetType( _Config.Plugins[i] ) ); this.Plugins[j].Init( CKFinderEvent ); if ( this.Plugins[j].JavascriptPlugins.Length > 0 ) { this.JavascriptPlugins.Add( this.Plugins[j].JavascriptPlugins ); } j++; } else { this.JavascriptPlugins.Add( _Config.Plugins[i] ); } } } protected override void OnLoad( EventArgs e ) { // Set the config file instance as the current one (to avoid singleton issues). ConfigFile.SetCurrent(); // Load the config file settings. ConfigFile.SetConfig(); // Load plugins. LoadPlugins(); #if (DEBUG) // For testing purposes, we may force the user to get the Admin role. // Session[ "CKFinder_UserRole" ] = "Admin"; // Simulate slow connections. // System.Threading.Thread.Sleep( 2000 ); #endif CommandHandlers.CommandHandlerBase commandHandler = null; try { // Take the desired command from the querystring. string command = Request.QueryString["command"]; if ( command == null ) ConnectorException.Throw( Errors.InvalidCommand ); else { CKFinderEvent.ActivateEvent( CKFinderEvent.Hooks.BeforeExecuteCommand, command, Response ); // Create an instance of the class that handles the // requested command. switch ( command ) { case "Init": commandHandler = new CommandHandlers.InitCommandHandler(); break; case "LoadCookies": commandHandler = new CommandHandlers.LoadCookiesCommandHandler(); break; case "GetFolders": commandHandler = new CommandHandlers.GetFoldersCommandHandler(); break; case "GetFiles": commandHandler = new CommandHandlers.GetFilesCommandHandler(); break; case "Thumbnail": commandHandler = new CommandHandlers.ThumbnailCommandHandler(); break; case "CreateFolder": commandHandler = new CommandHandlers.CreateFolderCommandHandler(); break; case "RenameFolder": commandHandler = new CommandHandlers.RenameFolderCommandHandler(); break; case "DeleteFolder": commandHandler = new CommandHandlers.DeleteFolderCommandHandler(); break; case "FileUpload": commandHandler = new CommandHandlers.FileUploadCommandHandler(); break; case "QuickUpload": commandHandler = new CommandHandlers.QuickUploadCommandHandler(); break; case "DownloadFile": commandHandler = new CommandHandlers.DownloadFileCommandHandler(); break; case "RenameFile": commandHandler = new CommandHandlers.RenameFileCommandHandler(); break; case "DeleteFiles": commandHandler = new CommandHandlers.DeleteFilesCommandHandler(); break; case "CopyFiles": commandHandler = new CommandHandlers.CopyFilesCommandHandler(); break; case "MoveFiles": commandHandler = new CommandHandlers.MoveFilesCommandHandler(); break; default: ConnectorException.Throw( Errors.InvalidCommand ); break; } } // Send the appropriate response. if ( commandHandler != null ) commandHandler.SendResponse( Response ); } catch ( ConnectorException connectorException ) { #if DEBUG // While debugging, throwing the error gives us more useful // information. throw connectorException; #else commandHandler = new CommandHandlers.ErrorCommandHandler( connectorException ); commandHandler.SendResponse( Response ); #endif } } public static bool CheckFolderName(string folderName) { Config _Config = Config.Current; if ( _Config.DisallowUnsafeCharacters && folderName.Contains(".") ) return false; return Connector.CheckFileName(folderName); } public static bool CheckFileName( string fileName ) { if ( fileName == null || fileName.Length == 0 || fileName.StartsWith( "." ) || fileName.EndsWith( "." ) || fileName.Contains( ".." ) ) return false; if ( Regex.IsMatch( fileName, @"[/\\:\*\?""\<\>\|\p{C}]" ) ) return false; Config _Config = Config.Current; if ( _Config.DisallowUnsafeCharacters && fileName.Contains(";") ) return false; return true; } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using System; using System.Collections; using System.Runtime.InteropServices; using System.Linq; using System.Text.RegularExpressions; using UnityEngine; using Ovr; /// <summary> /// Configuration data for Oculus virtual reality. /// </summary> public class OVRManager : MonoBehaviour { /// <summary> /// Contains information about the user's preferences and body dimensions. /// </summary> public struct Profile { public float ipd; public float eyeHeight; public float eyeDepth; public float neckHeight; } /// <summary> /// Gets the singleton instance. /// </summary> public static OVRManager instance { get; private set; } /// <summary> /// Gets a reference to the low-level C API Hmd Wrapper /// </summary> private static Hmd _capiHmd; public static Hmd capiHmd { get { #if !UNITY_ANDROID || UNITY_EDITOR if (_capiHmd == null) { IntPtr hmdPtr = IntPtr.Zero; OVR_GetHMD(ref hmdPtr); _capiHmd = (hmdPtr != IntPtr.Zero) ? new Hmd(hmdPtr) : null; } #else _capiHmd = null; #endif return _capiHmd; } } /// <summary> /// Gets a reference to the active OVRDisplay /// </summary> public static OVRDisplay display { get; private set; } /// <summary> /// Gets a reference to the active OVRTracker /// </summary> public static OVRTracker tracker { get; private set; } /// <summary> /// Gets the current profile, which contains information about the user's settings and body dimensions. /// </summary> private static bool _profileIsCached = false; private static Profile _profile; public static Profile profile { get { if (!_profileIsCached) { #if !UNITY_ANDROID || UNITY_EDITOR float ipd = capiHmd.GetFloat(Hmd.OVR_KEY_IPD, Hmd.OVR_DEFAULT_IPD); float eyeHeight = capiHmd.GetFloat(Hmd.OVR_KEY_EYE_HEIGHT, Hmd.OVR_DEFAULT_EYE_HEIGHT); float[] defaultOffset = new float[] { Hmd.OVR_DEFAULT_NECK_TO_EYE_HORIZONTAL, Hmd.OVR_DEFAULT_NECK_TO_EYE_VERTICAL }; float[] neckToEyeOffset = capiHmd.GetFloatArray(Hmd.OVR_KEY_NECK_TO_EYE_DISTANCE, defaultOffset); float neckHeight = eyeHeight - neckToEyeOffset[1]; _profile = new Profile { ipd = ipd, eyeHeight = eyeHeight, eyeDepth = neckToEyeOffset[0], neckHeight = neckHeight, }; #else float ipd = 0.0f; OVR_GetInterpupillaryDistance(ref ipd); float eyeHeight = 0.0f; OVR_GetPlayerEyeHeight(ref eyeHeight); _profile = new Profile { ipd = ipd, eyeHeight = eyeHeight, eyeDepth = 0f, //TODO neckHeight = 0.0f, // TODO }; #endif _profileIsCached = true; } return _profile; } } /// <summary> /// Occurs when an HMD attached. /// </summary> public static event Action HMDAcquired; /// <summary> /// Occurs when an HMD detached. /// </summary> public static event Action HMDLost; /// <summary> /// Occurs when the tracker gained tracking. /// </summary> public static event Action TrackingAcquired; /// <summary> /// Occurs when the tracker lost tracking. /// </summary> public static event Action TrackingLost; /// <summary> /// Occurs when HSW dismissed. /// </summary> public static event Action HSWDismissed; /// <summary> /// If true, then the Oculus health and safety warning (HSW) is currently visible. /// </summary> public static bool isHSWDisplayed { get { #if !UNITY_ANDROID || UNITY_EDITOR return capiHmd.GetHSWDisplayState().Displayed; #else return false; #endif } } /// <summary> /// If the HSW has been visible for the necessary amount of time, this will make it disappear. /// </summary> public static void DismissHSWDisplay() { #if !UNITY_ANDROID || UNITY_EDITOR capiHmd.DismissHSWDisplay(); #endif } /// <summary> /// Gets the current battery level. /// </summary> /// <returns><c>battery level in the range [0.0,1.0]</c> /// <param name="batteryLevel">Battery level.</param> public static float batteryLevel { get { #if !UNITY_ANDROID || UNITY_EDITOR return 1.0f; #else return OVR_GetBatteryLevel(); #endif } } /// <summary> /// Gets the current battery temperature. /// </summary> /// <returns><c>battery temperature in Celsius</c> /// <param name="batteryTemperature">Battery temperature.</param> public static float batteryTemperature { get { #if !UNITY_ANDROID || UNITY_EDITOR return 0.0f; #else return OVR_GetBatteryTemperature(); #endif } } /// <summary> /// Gets the current battery status. /// </summary> /// <returns><c>battery status</c> /// <param name="batteryStatus">Battery status.</param> public static int batteryStatus { get { #if !UNITY_ANDROID || UNITY_EDITOR return 0; #else return OVR_GetBatteryStatus(); #endif } } /// <summary> /// Controls the size of the eye textures. /// Values must be above 0. /// Values below 1 permit sub-sampling for improved performance. /// Values above 1 permit super-sampling for improved sharpness. /// </summary> public float nativeTextureScale = 1.0f; /// <summary> /// Controls the size of the rendering viewport. /// Values must be between 0 and 1. /// Values below 1 permit dynamic sub-sampling for improved performance. /// </summary> public float virtualTextureScale = 1.0f; /// <summary> /// If true, head tracking will affect the orientation of each OVRCameraRig's cameras. /// </summary> public bool usePositionTracking = true; /// <summary> /// The format of each eye texture. /// </summary> public RenderTextureFormat eyeTextureFormat = RenderTextureFormat.Default; /// <summary> /// The depth of each eye texture in bits. /// </summary> public int eyeTextureDepth = 24; /// <summary> /// If true, TimeWarp will be used to correct the output of each OVRCameraRig for rotational latency. /// </summary> public bool timeWarp = true; /// <summary> /// If this is true and TimeWarp is true, each OVRCameraRig will stop tracking and only TimeWarp will respond to head motion. /// </summary> public bool freezeTimeWarp = false; /// <summary> /// If true, each scene load will cause the head pose to reset. /// </summary> public bool resetTrackerOnLoad = true; /// <summary> /// If true, the eyes see the same image, which is rendered only by the left camera. /// </summary> public bool monoscopic = false; /// <summary> /// True if the current platform supports virtual reality. /// </summary> public bool isSupportedPlatform { get; private set; } private static bool usingPositionTracking = false; private static bool wasHmdPresent = false; private static bool wasPositionTracked = false; private static WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame(); #if UNITY_ANDROID && !UNITY_EDITOR // Get this from Unity on startup so we can call Activity java functions private static bool androidJavaInit = false; private static AndroidJavaObject activity; private static AndroidJavaClass javaVrActivityClass; internal static int timeWarpViewNumber = 0; public static event Action OnCustomPostRender; #else private static bool ovrIsInitialized; private static bool isQuitting; #endif public static bool isPaused { get { return _isPaused; } set { #if UNITY_ANDROID && !UNITY_EDITOR RenderEventType eventType = (value) ? RenderEventType.Pause : RenderEventType.Resume; OVRPluginEvent.Issue(eventType); #endif _isPaused = value; } } private static bool _isPaused; #region Unity Messages private void Awake() { // Only allow one instance at runtime. if (instance != null) { enabled = false; DestroyImmediate(this); return; } instance = this; #if !UNITY_ANDROID || UNITY_EDITOR if (!ovrIsInitialized) { OVR_Initialize(); OVRPluginEvent.Issue(RenderEventType.Initialize); ovrIsInitialized = true; } var netVersion = new System.Version(Ovr.Hmd.OVR_VERSION_STRING); var ovrVersion = new System.Version(Ovr.Hmd.GetVersionString()); if (netVersion > ovrVersion) Debug.LogWarning("Using an older version of LibOVR."); #endif // Detect whether this platform is a supported platform RuntimePlatform currPlatform = Application.platform; isSupportedPlatform |= currPlatform == RuntimePlatform.Android; isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer; isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor; isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer; isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor; isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer; if (!isSupportedPlatform) { Debug.LogWarning("This platform is unsupported"); return; } #if UNITY_ANDROID && !UNITY_EDITOR Application.targetFrameRate = 60; // don't allow the app to run in the background Application.runInBackground = false; // Disable screen dimming Screen.sleepTimeout = SleepTimeout.NeverSleep; if (!androidJavaInit) { AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"); javaVrActivityClass = new AndroidJavaClass("com.oculusvr.vrlib.VrActivity"); // Prepare for the RenderThreadInit() SetInitVariables(activity.GetRawObject(), javaVrActivityClass.GetRawClass()); androidJavaInit = true; } // We want to set up our touchpad messaging system OVRTouchpad.Create(); // This will trigger the init on the render thread InitRenderThread(); #else SetEditorPlay(Application.isEditor); #endif if (display == null) display = new OVRDisplay(); if (tracker == null) tracker = new OVRTracker(); if (resetTrackerOnLoad) display.RecenterPose(); // Except for D3D9, SDK rendering forces vsync unless you pass ovrHmdCap_NoVSync to Hmd.SetEnabledCaps(). if (timeWarp) { bool useUnityVSync = SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9"); QualitySettings.vSyncCount = useUnityVSync ? 1 : 0; } #if (UNITY_STANDALONE_WIN && (UNITY_4_6 || UNITY_4_5)) bool unity_4_6 = false; bool unity_4_5_2 = false; bool unity_4_5_3 = false; bool unity_4_5_4 = false; bool unity_4_5_5 = false; #if (UNITY_4_6) unity_4_6 = true; #elif (UNITY_4_5_2) unity_4_5_2 = true; #elif (UNITY_4_5_3) unity_4_5_3 = true; #elif (UNITY_4_5_4) unity_4_5_4 = true; #elif (UNITY_4_5_5) unity_4_5_5 = true; #endif // Detect correct Unity releases which contain the fix for D3D11 exclusive mode. string version = Application.unityVersion; int releaseNumber; bool releaseNumberFound = Int32.TryParse(Regex.Match(version, @"\d+$").Value, out releaseNumber); // Exclusive mode was broken for D3D9 in Unity 4.5.2p2 - 4.5.4 and 4.6 builds prior to beta 21 bool unsupportedExclusiveModeD3D9 = (unity_4_6 && version.Last(char.IsLetter) == 'b' && releaseNumberFound && releaseNumber < 21) || (unity_4_5_2 && version.Last(char.IsLetter) == 'p' && releaseNumberFound && releaseNumber >= 2) || (unity_4_5_3) || (unity_4_5_4); // Exclusive mode was broken for D3D11 in Unity 4.5.2p2 - 4.5.5p2 and 4.6 builds prior to f1 bool unsupportedExclusiveModeD3D11 = (unity_4_6 && version.Last(char.IsLetter) == 'b') || (unity_4_5_2 && version.Last(char.IsLetter) == 'p' && releaseNumberFound && releaseNumber >= 2) || (unity_4_5_3) || (unity_4_5_4) || (unity_4_5_5 && version.Last(char.IsLetter) == 'f') || (unity_4_5_5 && version.Last(char.IsLetter) == 'p' && releaseNumberFound && releaseNumber < 3); if (unsupportedExclusiveModeD3D9 && !display.isDirectMode && SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9")) { MessageBox(0, "Direct3D 9 extended mode is not supported in this configuration. " + "Please use direct display mode, a different graphics API, or rebuild the application with a newer Unity version." , "VR Configuration Warning", 0); } if (unsupportedExclusiveModeD3D11 && !display.isDirectMode && SystemInfo.graphicsDeviceVersion.Contains("Direct3D 11")) { MessageBox(0, "Direct3D 11 extended mode is not supported in this configuration. " + "Please use direct display mode, a different graphics API, or rebuild the application with a newer Unity version." , "VR Configuration Warning", 0); } #endif } #if !UNITY_ANDROID || UNITY_EDITOR private void OnApplicationQuit() { isQuitting = true; } private void OnDisable() { if (!isQuitting) return; if (ovrIsInitialized) { OVR_Destroy(); OVRPluginEvent.Issue(RenderEventType.Destroy); _capiHmd = null; ovrIsInitialized = false; } } #endif private void Start() { #if !UNITY_ANDROID || UNITY_EDITOR Camera cam = GetComponent<Camera>(); if (cam == null) { // Ensure there is a non-RT camera in the scene to force rendering of the left and right eyes. cam = gameObject.AddComponent<Camera>(); cam.cullingMask = 0; cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = new Color(0.0f, 0.0f, 0.0f); cam.renderingPath = RenderingPath.Forward; cam.orthographic = true; cam.useOcclusionCulling = false; } #endif bool isD3d = SystemInfo.graphicsDeviceVersion.Contains("Direct3D") || Application.platform == RuntimePlatform.WindowsEditor && SystemInfo.graphicsDeviceVersion.Contains("emulated"); display.flipInput = isD3d; StartCoroutine(CallbackCoroutine()); } private void Update() { if (usePositionTracking != usingPositionTracking) { tracker.isEnabled = usePositionTracking; usingPositionTracking = usePositionTracking; } if (Input.GetKeyDown(KeyCode.R)) { display.RecenterPose(); } // Dispatch any events. if (HMDLost != null && wasHmdPresent && !display.isPresent) HMDLost(); if (HMDAcquired != null && !wasHmdPresent && display.isPresent) HMDAcquired(); wasHmdPresent = display.isPresent; if (TrackingLost != null && wasPositionTracked && !tracker.isPositionTracked) TrackingLost(); if (TrackingAcquired != null && !wasPositionTracked && tracker.isPositionTracked) TrackingAcquired(); wasPositionTracked = tracker.isPositionTracked; if (isHSWDisplayed && Input.anyKeyDown) { DismissHSWDisplay(); if (HSWDismissed != null) HSWDismissed(); } display.timeWarp = timeWarp; #if (!UNITY_ANDROID || UNITY_EDITOR) display.Update(); #endif } #if (UNITY_EDITOR_OSX) private void OnPreCull() // TODO: Fix Mac Unity Editor memory corruption issue requiring OnPreCull workaround. #else private void LateUpdate() #endif { #if (!UNITY_ANDROID || UNITY_EDITOR) display.BeginFrame(); #endif } private IEnumerator CallbackCoroutine() { while (true) { yield return waitForEndOfFrame; #if UNITY_ANDROID && !UNITY_EDITOR OVRManager.DoTimeWarp(timeWarpViewNumber); #else display.EndFrame(); #endif } } #if UNITY_ANDROID && !UNITY_EDITOR private void OnPause() { isPaused = true; } private void OnApplicationPause(bool pause) { Debug.Log("OnApplicationPause() " + pause); if (pause) { OnPause(); } else { StartCoroutine(OnResume()); } } void OnDisable() { StopAllCoroutines(); } private IEnumerator OnResume() { yield return null; // delay 1 frame to allow Unity enough time to create the windowSurface isPaused = false; } /// <summary> /// Leaves the application/game and returns to the launcher/dashboard /// </summary> public void ReturnToLauncher() { // show the platform UI quit prompt OVRManager.PlatformUIConfirmQuit(); } private void OnPostRender() { // Allow custom code to render before we kick off the plugin if (OnCustomPostRender != null) { OnCustomPostRender(); } EndEye(OVREye.Left, display.GetEyeTextureId(OVREye.Left)); EndEye(OVREye.Right, display.GetEyeTextureId(OVREye.Right)); } #endif #endregion public static void SetEditorPlay(bool isEditor) { #if !UNITY_ANDROID || UNITY_EDITOR OVR_SetEditorPlay(isEditor); #endif } public static void SetDistortionCaps(uint distortionCaps) { #if !UNITY_ANDROID || UNITY_EDITOR OVR_SetDistortionCaps(distortionCaps); #endif } public static void SetInitVariables(IntPtr activity, IntPtr vrActivityClass) { #if UNITY_ANDROID && !UNITY_EDITOR OVR_SetInitVariables(activity, vrActivityClass); #endif } public static void PlatformUIConfirmQuit() { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.Issue(RenderEventType.PlatformUIConfirmQuit); #endif } public static void PlatformUIGlobalMenu() { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.Issue(RenderEventType.PlatformUI); #endif } public static void DoTimeWarp(int timeWarpViewNumber) { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.IssueWithData(RenderEventType.TimeWarp, timeWarpViewNumber); #endif } public static void EndEye(OVREye eye, int eyeTextureId) { #if UNITY_ANDROID && !UNITY_EDITOR RenderEventType eventType = (eye == OVREye.Left) ? RenderEventType.LeftEyeEndFrame : RenderEventType.RightEyeEndFrame; OVRPluginEvent.IssueWithData(eventType, eyeTextureId); #endif } public static void InitRenderThread() { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.Issue(RenderEventType.InitRenderThread); #endif } private const string LibOVR = "OculusPlugin"; #if !UNITY_ANDROID || UNITY_EDITOR [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] private static extern void OVR_GetHMD(ref IntPtr hmdPtr); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] private static extern void OVR_SetEditorPlay(bool isEditorPlay); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] private static extern void OVR_SetDistortionCaps(uint distortionCaps); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] private static extern void OVR_Initialize(); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] private static extern void OVR_Destroy(); #if UNITY_STANDALONE_WIN [DllImport("user32", EntryPoint = "MessageBoxA", CharSet = CharSet.Ansi)] public static extern bool MessageBox(int hWnd, [MarshalAs(UnmanagedType.LPStr)]string text, [MarshalAs(UnmanagedType.LPStr)]string caption, uint type); #endif #else [DllImport(LibOVR)] private static extern void OVR_SetInitVariables(IntPtr activity, IntPtr vrActivityClass); [DllImport(LibOVR)] private static extern float OVR_GetBatteryLevel(); [DllImport(LibOVR)] private static extern int OVR_GetBatteryStatus(); [DllImport(LibOVR)] private static extern float OVR_GetBatteryTemperature(); [DllImport(LibOVR)] private static extern bool OVR_GetPlayerEyeHeight(ref float eyeHeight); [DllImport(LibOVR)] private static extern bool OVR_GetInterpupillaryDistance(ref float interpupillaryDistance); #endif }
/// Dedicated to the public domain by Christopher Diggins /// http://creativecommons.org/licenses/publicdomain/ using System; using System.Collections.Generic; using System.Text; using Peg; namespace Cat { /// <summary> /// Contains grammar rules. Any circular references require the usage of a "Delay" function which prevents /// the parser construction to lead to a stack overflow. /// </summary> public class CatGrammar : Peg.Grammar { public static Rule CatAstNode(AstLabel label, Rule x) { return new AstNodeRule(label, x); } public static Rule UntilEndOfLine() { return NoFail(WhileNot(AnyChar(), NL()), "expected a new line"); } public static Rule LineComment() { return Seq(CharSeq("//"), UntilEndOfLine()); } public static Rule BlockComment() { return Seq(CharSeq("/*"), NoFail(WhileNot(AnyChar(), CharSeq("*/")), "expected a new line")); } public static Rule MetaDataContent() { return CatAstNode(AstLabel.MetaDataContent, UntilEndOfLine()); } public static Rule MetaDataLabel() { return CatAstNode(AstLabel.MetaDataLabel, Seq(Star(CharSet(" \t")), Ident(), SingleChar(':'))); } public static Rule MetaDataEntry() { return Seq(Opt(MetaDataLabel()), Star(CharSet(" \t")), MetaDataContent()); } public static Rule StartMetaDataBlock() { return Seq(WS(), CharSeq("{{"), UntilEndOfLine()); } public static Rule EndMetaDataBlock() { return Seq(WS(), CharSeq("}}"), UntilEndOfLine()); } public static Rule MetaDataBlock() { return Seq(CatAstNode(AstLabel.MetaDataBlock, Seq(StartMetaDataBlock(), WhileNot(MetaDataEntry(), EndMetaDataBlock()))), WS()); } public static Rule Comment() { return Choice(BlockComment(), LineComment()); } public static Rule WS() { return Star(Choice(CharSet(" \t\n\r"), Comment())); } public static Rule CatIdentChar() { return Choice(IdentNextChar(), CharSet("~`!@#$%^&*-+=|:;<>.?/")); } public static Rule CatIdent() { return Plus(CatIdentChar()); ; } public static Rule Token(string s) { return Token(CharSeq(s)); } public static Rule Token(Rule r) { return Seq(r, WS()); } public static Rule Word(string s) { return Seq(CharSeq(s), EOW(), WS()); } public static Rule Quote() { // Note the usage of Delay which breaks circular references in the grammar return CatAstNode(AstLabel.Quote, Seq(Token("["), Star(Delay(Expr)), NoFail(Token("]"), "missing ']'"))); } public static Rule IntegerLiteral() { return CatAstNode(AstLabel.Int, Seq(Opt(SingleChar('-')), Plus(Digit()), Not(CharSet(".")))); } public static Rule EscapeChar() { return Seq(SingleChar('\\'), AnyChar()); } public static Rule StringCharLiteral() { return Choice(EscapeChar(), NotChar('"')); } public static Rule CharLiteral() { return CatAstNode(AstLabel.Char, Seq(SingleChar('\''), StringCharLiteral(), SingleChar('\''))); } public static Rule StringLiteral() { return CatAstNode(AstLabel.String, Seq(SingleChar('\"'), Star(StringCharLiteral()), SingleChar('\"'))); } public static Rule FloatLiteral() { return CatAstNode(AstLabel.Float, Seq(Opt(SingleChar('-')), Plus(Digit()), SingleChar('.'), Plus(Digit()))); } public static Rule HexValue() { return CatAstNode(AstLabel.Hex, Plus(HexDigit())); } public static Rule HexLiteral() { return Seq(CharSeq("0x"), NoFail(HexValue(), "expected at least one hexadecimal digit")); } public static Rule BinaryValue() { return CatAstNode(AstLabel.Bin, Plus(BinaryDigit())); } public static Rule BinaryLiteral() { return Seq(CharSeq("0b"), NoFail(BinaryValue(), "expected at least one binary digit")); } public static Rule NumLiteral() { return Choice(HexLiteral(), BinaryLiteral(), FloatLiteral(), IntegerLiteral()); } public static Rule Literal() { return Choice(StringLiteral(), CharLiteral(), NumLiteral()); } public static Rule Symbol() { // The "()" together is treated as a single symbol return Choice(CharSeq("()"), CharSet("(),")); } public static Rule Name() { return Token(CatAstNode(AstLabel.Name, Choice(Symbol(), CatIdent()))); } public static Rule Lambda() { return CatAstNode(AstLabel.Lambda, Seq(CharSeq("\\"), NoFail(Seq(Param(), CharSeq("."), Choice(Delay(Lambda), NoFail(Quote(), "expected a quotation or lambda expression"))), "expected a lambda expression"))); } public static Rule Expr() { return Token(Choice(Lambda(), Literal(), Quote(), Name())); } public static Rule Statement() { return Delay(FxnDef); } public static Rule CodeBlock() { return Seq(Token("{"), Star(Choice(Statement(), Expr())), NoFail(Token("}"), "missing '}'")); } public static Rule Param() { return Token(CatAstNode(AstLabel.Param, Ident())); } public static Rule Params() { return Seq(Token("("), Star(Param()), NoFail(Token(")"), "missing ')'")); } public static Rule TypeVar() { return CatAstNode(AstLabel.TypeVar, Seq(Opt(CharSeq("$")), LowerCaseLetter(), Star(IdentNextChar()))); } public static Rule StackVar() { return CatAstNode(AstLabel.StackVar, Seq(Opt(CharSeq("$")), UpperCaseLetter(), Star(IdentNextChar()))); } public static Rule TypeOrStackVar() { return Seq(SingleChar('\''), NoFail(Choice(TypeVar(), StackVar()), "invalid type or stack variable name"), WS()); } public static Rule TypeName() { return Token(CatAstNode(AstLabel.TypeName, Ident())); } public static Rule TypeComponent() { return Choice(TypeName(), TypeOrStackVar(), Delay(FxnType)); } public static Rule Production() { return CatAstNode(AstLabel.Stack, Token(Star(TypeComponent()))); } public static Rule Consumption() { return CatAstNode(AstLabel.Stack, Token(Star(TypeComponent()))); } public static Rule Arrow() { return CatAstNode(AstLabel.Arrow, Choice(Token("->"), Token("~>"))); } public static Rule FxnType() { return CatAstNode(AstLabel.FxnType, Seq(Token("("), Production(), NoFail(Arrow(), "expected either -> or ~>"), Consumption(), NoFail(Token(")"), "expected closing paranthesis"))); } public static Rule TypeDecl() { return Seq(Token(":"), NoFail(FxnType(), "expected function type declaration"), WS()); } public static Rule FxnDef() { return CatAstNode(AstLabel.Def, Seq(Word("define"), NoFail(Name(), "expected name"), Opt(Params()), Opt(TypeDecl()), Opt(MetaDataBlock()), NoFail(CodeBlock(), "expected a code block"))); } public static Rule FxnDecl() { return CatAstNode(AstLabel.Decl, Seq(Word("declare"), NoFail(Name(), "expected name"), Opt(Seq(TypeDecl(), Opt(MetaDataBlock()))))); } #region macros public static Rule MacroTypeVarName() { return CatAstNode(AstLabel.MacroTypeVarName, Seq(LowerCaseLetter(), Star(IdentNextChar()))); } public static Rule MacroTypeVar() { return CatAstNode(AstLabel.MacroTypeVar, MacroTypeVarName()); } public static Rule MacroStackVarName() { return CatAstNode(AstLabel.MacroStackVarName, Seq(UpperCaseLetter(), Star(IdentNextChar()))); } public static Rule MacroStackVar() { return CatAstNode(AstLabel.MacroStackVar, Seq(MacroStackVarName(), WS(), Opt(TypeDecl()))); } public static Rule MacroVar() { return Seq(SingleChar('$'), NoFail(Choice(MacroTypeVar(), MacroStackVar()), "expected a valid macro type variable or stack variable")); } public static Rule MacroName() { return CatAstNode(AstLabel.MacroName, Choice(Symbol(), CatIdent())); } public static Rule MacroTerm() { return Token(Choice(MacroQuote(), MacroVar(), MacroName())); } public static Rule MacroQuote() { return CatAstNode(AstLabel.MacroQuote, Seq(Token("["), Star(Delay(MacroTerm)), NoFail(Token("]"), "missing ']'"))); } public static Rule MacroPattern() { return CatAstNode(AstLabel.MacroPattern, Seq(Token("{"), Star(MacroTerm()), NoFail(Token("}"), "missing '}'"))); } public static Rule MacroDef() { return CatAstNode(AstLabel.MacroRule, Seq(Word("rule"), Seq(MacroPattern(), Token("=>"), MacroPattern()))); } public static Rule MacroProp() { return CatAstNode(AstLabel.MacroProp, Seq(Word("rule"), Seq(MacroPattern(), Token("=="), MacroPattern()))); } #endregion public static Rule CatProgram() { return Seq(WS(), Star(Choice(MetaDataBlock(), FxnDef(), MacroDef(), Expr())), WS(), NoFail(EndOfInput(), "expected macro or function defintion")); } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using CookComputing.XmlRpc; namespace XenAPI { /// <summary> /// machines serving blocks of data for provisioning VMs /// </summary> public partial class PVS_site : XenObject<PVS_site> { public PVS_site() { } public PVS_site(string uuid, string name_label, string name_description, string PVS_uuid, List<XenRef<PVS_cache_storage>> cache_storage, List<XenRef<PVS_server>> servers, List<XenRef<PVS_proxy>> proxies) { this.uuid = uuid; this.name_label = name_label; this.name_description = name_description; this.PVS_uuid = PVS_uuid; this.cache_storage = cache_storage; this.servers = servers; this.proxies = proxies; } /// <summary> /// Creates a new PVS_site from a Proxy_PVS_site. /// </summary> /// <param name="proxy"></param> public PVS_site(Proxy_PVS_site proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(PVS_site update) { uuid = update.uuid; name_label = update.name_label; name_description = update.name_description; PVS_uuid = update.PVS_uuid; cache_storage = update.cache_storage; servers = update.servers; proxies = update.proxies; } internal void UpdateFromProxy(Proxy_PVS_site proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; name_label = proxy.name_label == null ? null : (string)proxy.name_label; name_description = proxy.name_description == null ? null : (string)proxy.name_description; PVS_uuid = proxy.PVS_uuid == null ? null : (string)proxy.PVS_uuid; cache_storage = proxy.cache_storage == null ? null : XenRef<PVS_cache_storage>.Create(proxy.cache_storage); servers = proxy.servers == null ? null : XenRef<PVS_server>.Create(proxy.servers); proxies = proxy.proxies == null ? null : XenRef<PVS_proxy>.Create(proxy.proxies); } public Proxy_PVS_site ToProxy() { Proxy_PVS_site result_ = new Proxy_PVS_site(); result_.uuid = (uuid != null) ? uuid : ""; result_.name_label = (name_label != null) ? name_label : ""; result_.name_description = (name_description != null) ? name_description : ""; result_.PVS_uuid = (PVS_uuid != null) ? PVS_uuid : ""; result_.cache_storage = (cache_storage != null) ? Helper.RefListToStringArray(cache_storage) : new string[] {}; result_.servers = (servers != null) ? Helper.RefListToStringArray(servers) : new string[] {}; result_.proxies = (proxies != null) ? Helper.RefListToStringArray(proxies) : new string[] {}; return result_; } /// <summary> /// Creates a new PVS_site from a Hashtable. /// </summary> /// <param name="table"></param> public PVS_site(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); name_label = Marshalling.ParseString(table, "name_label"); name_description = Marshalling.ParseString(table, "name_description"); PVS_uuid = Marshalling.ParseString(table, "PVS_uuid"); cache_storage = Marshalling.ParseSetRef<PVS_cache_storage>(table, "cache_storage"); servers = Marshalling.ParseSetRef<PVS_server>(table, "servers"); proxies = Marshalling.ParseSetRef<PVS_proxy>(table, "proxies"); } public bool DeepEquals(PVS_site other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._name_label, other._name_label) && Helper.AreEqual2(this._name_description, other._name_description) && Helper.AreEqual2(this._PVS_uuid, other._PVS_uuid) && Helper.AreEqual2(this._cache_storage, other._cache_storage) && Helper.AreEqual2(this._servers, other._servers) && Helper.AreEqual2(this._proxies, other._proxies); } public override string SaveChanges(Session session, string opaqueRef, PVS_site server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_name_label, server._name_label)) { PVS_site.set_name_label(session, opaqueRef, _name_label); } if (!Helper.AreEqual2(_name_description, server._name_description)) { PVS_site.set_name_description(session, opaqueRef, _name_description); } if (!Helper.AreEqual2(_PVS_uuid, server._PVS_uuid)) { PVS_site.set_PVS_uuid(session, opaqueRef, _PVS_uuid); } return null; } } /// <summary> /// Get a record containing the current state of the given PVS_site. /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_site">The opaque_ref of the given pvs_site</param> public static PVS_site get_record(Session session, string _pvs_site) { return new PVS_site((Proxy_PVS_site)session.proxy.pvs_site_get_record(session.uuid, (_pvs_site != null) ? _pvs_site : "").parse()); } /// <summary> /// Get a reference to the PVS_site instance with the specified UUID. /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<PVS_site> get_by_uuid(Session session, string _uuid) { return XenRef<PVS_site>.Create(session.proxy.pvs_site_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse()); } /// <summary> /// Get all the PVS_site instances with the given label. /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_label">label of object to return</param> public static List<XenRef<PVS_site>> get_by_name_label(Session session, string _label) { return XenRef<PVS_site>.Create(session.proxy.pvs_site_get_by_name_label(session.uuid, (_label != null) ? _label : "").parse()); } /// <summary> /// Get the uuid field of the given PVS_site. /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_site">The opaque_ref of the given pvs_site</param> public static string get_uuid(Session session, string _pvs_site) { return (string)session.proxy.pvs_site_get_uuid(session.uuid, (_pvs_site != null) ? _pvs_site : "").parse(); } /// <summary> /// Get the name/label field of the given PVS_site. /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_site">The opaque_ref of the given pvs_site</param> public static string get_name_label(Session session, string _pvs_site) { return (string)session.proxy.pvs_site_get_name_label(session.uuid, (_pvs_site != null) ? _pvs_site : "").parse(); } /// <summary> /// Get the name/description field of the given PVS_site. /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_site">The opaque_ref of the given pvs_site</param> public static string get_name_description(Session session, string _pvs_site) { return (string)session.proxy.pvs_site_get_name_description(session.uuid, (_pvs_site != null) ? _pvs_site : "").parse(); } /// <summary> /// Get the PVS_uuid field of the given PVS_site. /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_site">The opaque_ref of the given pvs_site</param> public static string get_PVS_uuid(Session session, string _pvs_site) { return (string)session.proxy.pvs_site_get_pvs_uuid(session.uuid, (_pvs_site != null) ? _pvs_site : "").parse(); } /// <summary> /// Get the cache_storage field of the given PVS_site. /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_site">The opaque_ref of the given pvs_site</param> public static List<XenRef<PVS_cache_storage>> get_cache_storage(Session session, string _pvs_site) { return XenRef<PVS_cache_storage>.Create(session.proxy.pvs_site_get_cache_storage(session.uuid, (_pvs_site != null) ? _pvs_site : "").parse()); } /// <summary> /// Get the servers field of the given PVS_site. /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_site">The opaque_ref of the given pvs_site</param> public static List<XenRef<PVS_server>> get_servers(Session session, string _pvs_site) { return XenRef<PVS_server>.Create(session.proxy.pvs_site_get_servers(session.uuid, (_pvs_site != null) ? _pvs_site : "").parse()); } /// <summary> /// Get the proxies field of the given PVS_site. /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_site">The opaque_ref of the given pvs_site</param> public static List<XenRef<PVS_proxy>> get_proxies(Session session, string _pvs_site) { return XenRef<PVS_proxy>.Create(session.proxy.pvs_site_get_proxies(session.uuid, (_pvs_site != null) ? _pvs_site : "").parse()); } /// <summary> /// Set the name/label field of the given PVS_site. /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_site">The opaque_ref of the given pvs_site</param> /// <param name="_label">New value to set</param> public static void set_name_label(Session session, string _pvs_site, string _label) { session.proxy.pvs_site_set_name_label(session.uuid, (_pvs_site != null) ? _pvs_site : "", (_label != null) ? _label : "").parse(); } /// <summary> /// Set the name/description field of the given PVS_site. /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_site">The opaque_ref of the given pvs_site</param> /// <param name="_description">New value to set</param> public static void set_name_description(Session session, string _pvs_site, string _description) { session.proxy.pvs_site_set_name_description(session.uuid, (_pvs_site != null) ? _pvs_site : "", (_description != null) ? _description : "").parse(); } /// <summary> /// Introduce new PVS site /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_name_label">name of the PVS site</param> /// <param name="_name_description">description of the PVS site</param> /// <param name="_pvs_uuid">unique identifier of the PVS site</param> public static XenRef<PVS_site> introduce(Session session, string _name_label, string _name_description, string _pvs_uuid) { return XenRef<PVS_site>.Create(session.proxy.pvs_site_introduce(session.uuid, (_name_label != null) ? _name_label : "", (_name_description != null) ? _name_description : "", (_pvs_uuid != null) ? _pvs_uuid : "").parse()); } /// <summary> /// Introduce new PVS site /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_name_label">name of the PVS site</param> /// <param name="_name_description">description of the PVS site</param> /// <param name="_pvs_uuid">unique identifier of the PVS site</param> public static XenRef<Task> async_introduce(Session session, string _name_label, string _name_description, string _pvs_uuid) { return XenRef<Task>.Create(session.proxy.async_pvs_site_introduce(session.uuid, (_name_label != null) ? _name_label : "", (_name_description != null) ? _name_description : "", (_pvs_uuid != null) ? _pvs_uuid : "").parse()); } /// <summary> /// Remove a site's meta data /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_site">The opaque_ref of the given pvs_site</param> public static void forget(Session session, string _pvs_site) { session.proxy.pvs_site_forget(session.uuid, (_pvs_site != null) ? _pvs_site : "").parse(); } /// <summary> /// Remove a site's meta data /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_site">The opaque_ref of the given pvs_site</param> public static XenRef<Task> async_forget(Session session, string _pvs_site) { return XenRef<Task>.Create(session.proxy.async_pvs_site_forget(session.uuid, (_pvs_site != null) ? _pvs_site : "").parse()); } /// <summary> /// Update the PVS UUID of the PVS site /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_site">The opaque_ref of the given pvs_site</param> /// <param name="_value">PVS UUID to be used</param> public static void set_PVS_uuid(Session session, string _pvs_site, string _value) { session.proxy.pvs_site_set_pvs_uuid(session.uuid, (_pvs_site != null) ? _pvs_site : "", (_value != null) ? _value : "").parse(); } /// <summary> /// Update the PVS UUID of the PVS site /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_site">The opaque_ref of the given pvs_site</param> /// <param name="_value">PVS UUID to be used</param> public static XenRef<Task> async_set_PVS_uuid(Session session, string _pvs_site, string _value) { return XenRef<Task>.Create(session.proxy.async_pvs_site_set_pvs_uuid(session.uuid, (_pvs_site != null) ? _pvs_site : "", (_value != null) ? _value : "").parse()); } /// <summary> /// Return a list of all the PVS_sites known to the system. /// Experimental. First published in . /// </summary> /// <param name="session">The session</param> public static List<XenRef<PVS_site>> get_all(Session session) { return XenRef<PVS_site>.Create(session.proxy.pvs_site_get_all(session.uuid).parse()); } /// <summary> /// Get all the PVS_site Records at once, in a single XML RPC call /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<PVS_site>, PVS_site> get_all_records(Session session) { return XenRef<PVS_site>.Create<Proxy_PVS_site>(session.proxy.pvs_site_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// Experimental. First published in . /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// a human-readable name /// Experimental. First published in . /// </summary> public virtual string name_label { get { return _name_label; } set { if (!Helper.AreEqual(value, _name_label)) { _name_label = value; Changed = true; NotifyPropertyChanged("name_label"); } } } private string _name_label; /// <summary> /// a notes field containing human-readable description /// Experimental. First published in . /// </summary> public virtual string name_description { get { return _name_description; } set { if (!Helper.AreEqual(value, _name_description)) { _name_description = value; Changed = true; NotifyPropertyChanged("name_description"); } } } private string _name_description; /// <summary> /// Unique identifier of the PVS site, as configured in PVS /// Experimental. First published in . /// </summary> public virtual string PVS_uuid { get { return _PVS_uuid; } set { if (!Helper.AreEqual(value, _PVS_uuid)) { _PVS_uuid = value; Changed = true; NotifyPropertyChanged("PVS_uuid"); } } } private string _PVS_uuid; /// <summary> /// The SR used by PVS proxy for the cache /// Experimental. First published in . /// </summary> public virtual List<XenRef<PVS_cache_storage>> cache_storage { get { return _cache_storage; } set { if (!Helper.AreEqual(value, _cache_storage)) { _cache_storage = value; Changed = true; NotifyPropertyChanged("cache_storage"); } } } private List<XenRef<PVS_cache_storage>> _cache_storage; /// <summary> /// The set of PVS servers in the site /// Experimental. First published in . /// </summary> public virtual List<XenRef<PVS_server>> servers { get { return _servers; } set { if (!Helper.AreEqual(value, _servers)) { _servers = value; Changed = true; NotifyPropertyChanged("servers"); } } } private List<XenRef<PVS_server>> _servers; /// <summary> /// The set of proxies associated with the site /// Experimental. First published in . /// </summary> public virtual List<XenRef<PVS_proxy>> proxies { get { return _proxies; } set { if (!Helper.AreEqual(value, _proxies)) { _proxies = value; Changed = true; NotifyPropertyChanged("proxies"); } } } private List<XenRef<PVS_proxy>> _proxies; } }
#region License /* * Copyright (C) 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Collections; using System.Collections.Generic; using System.Threading; using Java.Util.Concurrent.Helpers; using Java.Util.Concurrent.Locks; #endregion namespace Java.Util.Concurrent { /// <summary> /// An implementation of <see cref="IBlockingQueue{T}"/> by wrapping a /// regular queue. /// </summary> /// <remarks> /// This class supports an optional fairness policy for ordering waiting /// producer and consumer threads. By default, this ordering is not /// guaranteed. However, a queue constructed with fairness set to /// <see langword="true"/> grants threads access in FIFO order. Fairness /// generally decreases throughput but reduces variability and avoids /// starvation. /// </remarks> /// <author>Doug Lea</author> /// <author>Griffin Caprio (.NET)</author> /// <author>Kenneth Xu</author> [Serializable] public class BlockingQueueWrapper<T> : AbstractBlockingQueue<T> //BACKPORT_2_2 { /// <summary>Main lock guarding all access </summary> private readonly ReentrantLock _lock; /// <summary>Condition for waiting takes </summary> private readonly ICondition _notEmptyCondition; /// <summary>Condition for waiting puts </summary> private readonly ICondition _notFullCondition; /// <summary> /// The wrapped regular queue. /// </summary> readonly IQueue<T> _wrapped; private readonly int _capacity; #region Constructors /// <summary> /// Construct a blocking queue that based on the given regular /// <paramref name="queue"/>. /// </summary> /// <param name="queue"> /// A regular queue to be wrapped as blocking queue. /// </param> /// <param name="capacity"> /// The capacity of the queue. zero (<c>0</c>) to indicate an /// unbounded queue. /// </param> /// <param name="isFair"> /// <c>true</c> to grant access to longest waiting threads, otherwise /// it does not guarantee any particular access order. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="queue"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="capacity"/> is negative. /// </exception> public BlockingQueueWrapper(IQueue<T> queue, int capacity, bool isFair) { if (queue == null) throw new ArgumentNullException(nameof(queue)); if (capacity < 0) throw new ArgumentOutOfRangeException( nameof(capacity), capacity, "must not be negative."); _lock = new ReentrantLock(isFair); _wrapped = queue; _capacity = capacity; _notEmptyCondition = _lock.NewCondition(); _notFullCondition = _lock.NewCondition(); } /// <summary> /// Construct a blocking queue that based on the given regular /// <paramref name="queue"/>. There is no guarantee to the order of /// the blocked threads being given access. /// </summary> /// <param name="queue"> /// A regular queue to be wrapped as blocking queue. /// </param> /// <param name="capacity"> /// The capacity of the queue. zero (<c>0</c>) to indicate an /// unbounded queue. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="queue"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="capacity"/> is negative. /// </exception> public BlockingQueueWrapper(IQueue<T> queue, int capacity) : this(queue, capacity, false) { } /// <summary> /// Construct a blocking queue that based on the given regular /// unbounded <paramref name="queue"/>. /// </summary> /// <param name="queue"> /// A regular queue to be wrapped as blocking queue. /// </param> /// <param name="isFair"> /// <c>true</c> to grant access to longest waiting threads, otherwise /// it does not guarantee any particular access order. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="queue"/> is <c>null</c>. /// </exception> public BlockingQueueWrapper(IQueue<T> queue, bool isFair) : this(queue, 0, isFair) { } /// <summary> /// Construct a blocking queue that based on the given regular /// unbounded <paramref name="queue"/>. There is no guarantee to the /// order of the blocked threads being given access. /// </summary> /// <param name="queue"> /// A regular queue to be wrapped as blocking queue. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="queue"/> is <c>null</c>. /// </exception> public BlockingQueueWrapper(IQueue<T> queue) : this(queue, 0, false) { } #endregion #region Properties /// <summary> /// Returns the current capacity of this queue. /// </summary> public override int Capacity { get { return _capacity == 0 ? int.MaxValue : _capacity; } } /// <summary> /// Determine if the current instance is fair to blocking threads. /// </summary> public virtual bool IsFair { get { return _lock.IsFair; } } #endregion /// <summary> /// Atomically removes all of the elements from this queue. /// The queue will be empty after this call returns. /// </summary> public sealed override void Clear() { using (_lock.Lock()) { _wrapped.Clear(); _notFullCondition.SignalAll(); } } /// <summary> /// Returns a <see cref="string"/> that represents the current /// <see cref="ICollection{T}"/>. /// </summary> /// <remarks> /// This implmentation list out all the elements separated by comma. /// </remarks> /// <returns> /// A <see cref="string"/> that represents the current collection. /// </returns> /// <filterpriority>2</filterpriority> public override string ToString() { using (_lock.Lock()) { return base.ToString(); } } /// <summary> /// Returns <see langword="true"/> if this queue contains the specified /// element. /// </summary> /// <remarks> /// More formally, returns <see langword="true"/> if and only if this /// queue contains at least one element <i>element</i> such that /// <i>elementToSearchFor.equals(element)</i>. /// </remarks> /// <param name="elementToSearchFor"> /// Object to be checked for containment in this queue. /// </param> /// <returns> /// <see langword="true"/> /// If this queue contains the specified element. /// </returns> public override bool Contains(T elementToSearchFor) { using (_lock.Lock()) { return _wrapped.Contains(elementToSearchFor); } } /// <summary> /// Removes a single instance of the specified element from this queue, /// if it is present. More formally, removes an <i>element</i> such /// that <i>elementToRemove.Equals(element)</i>, if this queue contains /// one or more such elements. /// </summary> /// <param name="elementToRemove"> /// element to be removed from this queue, if present. /// </param> /// <returns> <see langword="true"/> if this queue contained the /// specified element or if this queue changed as a result of the call, /// <see langword="false"/> otherwise. /// </returns> public override bool Remove(T elementToRemove) { using (_lock.Lock()) { bool isSuccess = _wrapped.Remove(elementToRemove); if (isSuccess) _notFullCondition.Signal(); return isSuccess; } } /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an /// <see cref="Array"/>, starting at a particular <see cref="Array"/> /// index. /// </summary> /// /// <param name="array"> /// The one-dimensional <see cref="Array"/> that is the destination /// of the elements copied from <see cref="ICollection"/>. The /// <see cref="Array"/> must have zero-based indexing. /// </param> /// <param name="index"> /// The zero-based index in array at which copying begins. /// </param> /// <exception cref="ArgumentNullException">array is null. </exception> /// <exception cref="ArgumentOutOfRangeException"> /// index is less than zero. /// </exception> /// <exception cref="ArgumentException"> /// array is multidimensional.-or- index is equal to or greater than /// the length of array. /// -or- /// The number of elements in the source <see cref="ICollection"/> /// is greater than the available space from index to the end of the /// destination array. /// </exception> /// <exception cref="InvalidCastException"> /// The type of the source <see cref="ICollection"/> cannot be cast /// automatically to the type of the destination array. /// </exception> /// <filterpriority>2</filterpriority> protected override void CopyTo(Array array, int index) { using (_lock.Lock()) { base.CopyTo(array, index); } } /// <summary> /// Does the actual work of copying to array. Calls the base method in /// synchronized context. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="Array"/> that is the /// destination of the elements copied from <see cref="ICollection{T}"/>. /// The <see cref="Array"/> must have zero-based indexing. /// </param> /// <param name="arrayIndex"> /// The zero-based index in array at which copying begins. /// </param> /// <param name="ensureCapacity"> /// If is <c>true</c>, calls <see cref="AbstractCollection{T}.EnsureCapacity"/> /// </param> /// <returns> /// A new array of same runtime type as <paramref name="array"/> if /// <paramref name="array"/> is too small to hold all elements and /// <paramref name="ensureCapacity"/> is <c>false</c>. Otherwise /// the <paramref name="array"/> instance itself. /// </returns> protected override T[] DoCopyTo(T[] array, int arrayIndex, bool ensureCapacity) { using (_lock.Lock()) { return base.DoCopyTo(array, arrayIndex, ensureCapacity); } } /// <summary> /// Returns the number of additional elements that this queue can ideally /// (in the absence of memory or resource constraints) accept without /// blocking, or <see cref="System.Int32.MaxValue"/> if there is no intrinsic /// limit. /// </summary> /// <remarks> /// <b>Important</b>: You <b>cannot</b> always tell if an attempt to insert /// an element will succeed by inspecting <see cref="RemainingCapacity"/> /// because it may be the case that another thread is about to /// insert or remove an element. /// </remarks> /// <returns>The remaining capacity.</returns> public override int RemainingCapacity { get { return _capacity == 0 ? int.MaxValue : _capacity - Count; } } /// <summary> /// Returns the number of elements in this queue. /// </summary> /// <returns>The number of elements in this queue.</returns> public override int Count { get { using (_lock.Lock()) { return _wrapped.Count; } } } /// <summary> /// Inserts the specified element into this queue if it is possible to /// do so immediately without violating capacity restrictions. /// </summary> /// <remarks> /// When using a capacity-restricted queue, this method is generally /// preferable to <see cref="AbstractQueue{T}.Add(T)"/>, which can fail to /// insert an element only by throwing an exception. /// </remarks> /// <param name="element">The element to add.</param> /// <returns> /// <c>true</c> if the element was added to this queue. Otherwise /// <c>false</c>. /// </returns> /// <exception cref="ArgumentNullException"> /// If the <paramref name="element"/> is <c>null</c> and the queue /// implementation doesn't allow <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// If some property of the supplied <paramref name="element"/> /// prevents it from being added to this queue. /// </exception> public override bool Offer(T element) { using (_lock.Lock()) { bool isSuccess = _wrapped.Offer(element); if (isSuccess) _notEmptyCondition.Signal(); return isSuccess; } } /// <summary> /// Retrieves and removes the head of this queue into out parameter /// <paramref name="element"/>. /// </summary> /// <param name="element"> /// Set to the head of this queue. <c>default(T)</c> if queue is empty. /// </param> /// <returns> /// <c>false</c> if the queue is empty. Otherwise <c>true</c>. /// </returns> public override bool Poll(out T element) { using (_lock.Lock()) { bool isSuccess = _wrapped.Poll(out element); if (isSuccess) _notFullCondition.Signal(); return isSuccess; } } /// <summary> /// Inserts the specified element into this queue, waiting if necessary /// for space to become available. /// </summary> /// <param name="element">the element to add</param> /// <exception cref="System.ArgumentNullException"> /// If the specified element is <see langword="null"/> and this queue /// does not permit <see langword="null"/> elements. /// </exception> /// <exception cref="System.ArgumentException"> /// If some property of the supplied <paramref name="element"/> prevents /// it from being added to this queue. /// </exception> public override void Put(T element) { using (_lock.LockInterruptibly()) { try { while (!_wrapped.Offer(element)) _notFullCondition.Await(); _notEmptyCondition.Signal(); } catch (ThreadInterruptedException e) { _notFullCondition.Signal(); throw SystemExtensions.PreserveStackTrace(e); } } } /// <summary> /// Inserts the specified element into this queue, waiting up to the /// specified wait time if necessary for space to become available. /// </summary> /// <param name="element">The element to add.</param> /// <param name="duration">How long to wait before giving up.</param> /// <returns> /// <see langword="true"/> if successful, or <see langword="false"/> if /// the specified waiting time elapses before space is available. /// </returns> /// <exception cref="System.ArgumentNullException"> /// If the specified element is <see langword="null"/> and this queue /// does not permit <see langword="null"/> elements. /// </exception> /// <exception cref="System.ArgumentException"> /// If some property of the supplied <paramref name="element"/> prevents /// it from being added to this queue. /// </exception> public override bool Offer(T element, TimeSpan duration) { DateTime deadline = WaitTime.Deadline(duration); using (_lock.LockInterruptibly()) { while (!_wrapped.Offer(element)) { if (duration.Ticks <= 0) return false; try { _notFullCondition.Await(WaitTime.Cap(duration)); duration = deadline.Subtract(DateTime.UtcNow); } catch (ThreadInterruptedException e) { _notFullCondition.Signal(); throw SystemExtensions.PreserveStackTrace(e); } } _notEmptyCondition.Signal(); return true; } } /// <summary> /// Retrieves and removes the head of this queue, waiting if necessary /// until an element becomes available. /// </summary> /// <returns> the head of this queue</returns> public override T Take() { using (_lock.LockInterruptibly()) { try { T element; while (!_wrapped.Poll(out element)) _notEmptyCondition.Await(); _notFullCondition.Signal(); return element; } catch (ThreadInterruptedException e) { _notEmptyCondition.Signal(); throw SystemExtensions.PreserveStackTrace(e); } } } /// <summary> /// Retrieves and removes the head of this queue, waiting up to the /// specified wait time if necessary for an element to become available. /// </summary> /// <param name="element"> /// Set to the head of this queue. <c>default(T)</c> if queue is empty. /// </param> /// <param name="duration">How long to wait before giving up.</param> /// <returns> /// <c>false</c> if the queue is still empty after waited for the time /// specified by the <paramref name="duration"/>. Otherwise <c>true</c>. /// </returns> public override bool Poll(TimeSpan duration, out T element) { DateTime deadline = WaitTime.Deadline(duration); using (_lock.LockInterruptibly()) { while (!_wrapped.Poll(out element)) { if (duration.Ticks <= 0) { element = default(T); return false; } try { _notEmptyCondition.Await(WaitTime.Cap(duration)); duration = deadline.Subtract(DateTime.UtcNow); } catch (ThreadInterruptedException e) { _notEmptyCondition.Signal(); throw SystemExtensions.PreserveStackTrace(e); } } _notFullCondition.Signal(); return true; } } /// <summary> /// Does the real work for all drain methods. Caller must /// guarantee the <paramref name="action"/> is not <c>null</c> and /// <paramref name="maxElements"/> is greater then zero (0). /// </summary> /// <seealso cref="IQueue{T}.Drain(System.Action{T})"/> /// <seealso cref="IQueue{T}.Drain(System.Action{T}, int)"/> /// <seealso cref="IQueue{T}.Drain(System.Action{T}, Predicate{T})"/> /// <seealso cref="IQueue{T}.Drain(System.Action{T}, int, Predicate{T})"/> internal protected override int DoDrain(Action<T> action, int maxElements, Predicate<T> criteria) { using (_lock.Lock()) { int n = _wrapped.Drain(action, maxElements, criteria); if (n == 1) { _notFullCondition.Signal(); } else if (n != 0) { _notFullCondition.SignalAll(); } return n; } } /// <summary> /// Retrieves, but does not remove, the head of this queue into out /// parameter <paramref name="element"/>. /// </summary> /// <param name="element"> /// The head of this queue. <c>default(T)</c> if queue is empty. /// </param> /// <returns> /// <c>false</c> is the queue is empty. Otherwise <c>true</c>. /// </returns> public override bool Peek(out T element) { using (_lock.Lock()) { return _wrapped.Peek(out element); } } /// <summary> /// Always return true as blocking queue is always synchronized /// (thread-safe). /// </summary> protected override bool IsSynchronized { get { return true; } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate /// through the collection. /// </returns> /// <filterpriority>1</filterpriority> public override IEnumerator<T> GetEnumerator() { using (_lock.Lock()) { return new BlockingQueueEnumeratorWrapper(_wrapped.GetEnumerator(), _lock); } } private class BlockingQueueEnumeratorWrapper : AbstractEnumerator<T> { private readonly ReentrantLock _lock; private readonly IEnumerator<T> _wrapped; protected override T FetchCurrent() { using (_lock.Lock()) { return _wrapped.Current; } } internal BlockingQueueEnumeratorWrapper( IEnumerator<T> enumerator, ReentrantLock reentrantLock) { _wrapped = enumerator; _lock = reentrantLock; } protected override bool GoNext() { using (_lock.Lock()) { return _wrapped.MoveNext(); } } protected override void DoReset() { using (_lock.Lock()) { _wrapped.Reset(); } } } } }
using System; using System.IO; using System.Net; using System.Text; using Newtonsoft.Json; using System.Net.Http; using System.Reflection; using Nexmo.Api.Logging; namespace Nexmo.Api.Request { /// <summary> /// Responsible for sending all Nexmo API requests that require Application authentication. /// For older forms of authentication, see ApiRequest. /// </summary> public static class VersionedApiRequest { public enum AuthType { Basic, Bearer } private static readonly ILog Logger = LogProvider.GetLogger(typeof(ApiRequest), "Nexmo.Api.Request.ApiRequest"); private static StringBuilder GetQueryStringBuilderFor(object parameters) { var apiParams = ApiRequest.GetParameters(parameters); var sb = new StringBuilder(); foreach (var key in apiParams.Keys) { sb.AppendFormat("{0}={1}&", WebUtility.UrlEncode(key), WebUtility.UrlEncode(apiParams[key])); } return sb; } private static string DoRequest(Uri uri, AuthType authType, Credentials creds = null) { var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"]; var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"]; var apiKey = (creds?.ApiKey ?? Configuration.Instance.Settings["appSettings:Nexmo.api_key"])?.ToLower(); var apiSecret = creds?.ApiSecret ?? Configuration.Instance.Settings["appSettings:Nexmo.api_secret"]; var req = new HttpRequestMessage { RequestUri = uri, Method = HttpMethod.Get, }; SetUserAgent(ref req, creds); // attempt bearer token auth if(authType == AuthType.Bearer) { req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Jwt.CreateToken(appId, appKeyPath)); } else if(authType == AuthType.Basic) { var authBytes = Encoding.UTF8.GetBytes(apiKey + ":" + apiSecret); req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authBytes)); } using (LogProvider.OpenMappedContext("VersionedApiRequest.DoRequest",uri.GetHashCode())) { Logger.Debug($"GET {uri}"); var sendTask = Configuration.Instance.Client.SendAsync(req); sendTask.Wait(); if (!sendTask.Result.IsSuccessStatusCode) { Logger.Error($"FAIL: {sendTask.Result.StatusCode}"); if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"], "true", StringComparison.OrdinalIgnoreCase) == 0) { sendTask.Result.EnsureSuccessStatusCode(); } } string json; var readTask = sendTask.Result.Content.ReadAsStreamAsync(); readTask.Wait(); using (var sr = new StreamReader(readTask.Result)) { json = sr.ReadToEnd(); } Logger.Debug(json); return json; } } private static string _userAgent; internal static void SetUserAgent(ref HttpRequestMessage request, Credentials creds) { if (string.IsNullOrEmpty(_userAgent)) { #if NETSTANDARD1_6 || NETSTANDARD2_0 // TODO: watch the next core release; may have functionality to make this cleaner var runtimeVersion = (System.Runtime.InteropServices.RuntimeInformation.OSDescription + System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription) .Replace(" ", "") .Replace("/", "") .Replace(":", "") .Replace(";", "") .Replace("_", "") ; #else var runtimeVersion = System.Diagnostics.FileVersionInfo .GetVersionInfo(typeof(int).Assembly.Location) .ProductVersion; #endif var libraryVersion = typeof(VersionedApiRequest) .GetTypeInfo() .Assembly .GetCustomAttribute<AssemblyInformationalVersionAttribute>() .InformationalVersion; _userAgent = $"nexmo-dotnet/{libraryVersion} dotnet/{runtimeVersion}"; var appVersion = creds?.AppUserAgent ?? Configuration.Instance.Settings["appSettings:Nexmo.UserAgent"]; if (!string.IsNullOrWhiteSpace(appVersion)) { _userAgent += $" {appVersion}"; } } request.Headers.UserAgent.ParseAdd(_userAgent); } /// <summary> /// Send a request to the versioned Nexmo API. /// Do not include credentials in the parameters object. If you need to override credentials, use the optional Credentials parameter. /// </summary> /// <param name="method">HTTP method (POST, PUT, DELETE, etc)</param> /// <param name="uri">The URI to communicate with</param> /// <param name="payload">Parameters required by the endpoint (do not include credentials)</param> /// <param name="creds">(Optional) Overridden credentials for only this request</param> /// <returns></returns> public static NexmoResponse DoRequest(string method, Uri uri, object payload, Credentials creds = null) { var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"]; var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"]; var apiKey = (creds?.ApiKey ?? Configuration.Instance.Settings["appSettings:Nexmo.api_key"])?.ToLower(); var apiSecret = creds?.ApiSecret ?? Configuration.Instance.Settings["appSettings:Nexmo.api_secret"]; var req = new HttpRequestMessage { RequestUri = uri, Method = new HttpMethod(method), }; SetUserAgent(ref req, creds); // do we need to use basic auth? // TODO / HACK: this is a newer auth method that needs to be incorporated better in the future if (uri.AbsolutePath.StartsWith("/accounts/") || uri.AbsolutePath.StartsWith("/v2/applications") || uri.AbsolutePath.StartsWith("/v1/redact/transaction")) { var authBytes = Encoding.UTF8.GetBytes(apiKey + ":" + apiSecret); req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authBytes)); } else { // attempt bearer token auth req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Jwt.CreateToken(appId, appKeyPath)); } var data = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(payload, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore })); req.Content = new ByteArrayContent(data); req.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); using (LogProvider.OpenMappedContext("VersionedApiRequest.DoRequest",uri.GetHashCode())) { Logger.Debug($"{method} {uri} {payload}"); var sendTask = Configuration.Instance.Client.SendAsync(req); sendTask.Wait(); if (!sendTask.Result.IsSuccessStatusCode) { Logger.Error($"FAIL: {sendTask.Result.StatusCode}"); if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"], "true", StringComparison.OrdinalIgnoreCase) == 0) { sendTask.Result.EnsureSuccessStatusCode(); } return new NexmoResponse { Status = sendTask.Result.StatusCode }; } string json; var readTask = sendTask.Result.Content.ReadAsStreamAsync(); readTask.Wait(); using (var sr = new StreamReader(readTask.Result)) { json = sr.ReadToEnd(); } Logger.Debug(json); return new NexmoResponse { Status = sendTask.Result.StatusCode, JsonResponse = json }; } } /// <summary> /// Send a GET request to the versioned Nexmo API. /// Do not include credentials in the parameters object. If you need to override credentials, use the optional Credentials parameter. /// </summary> /// <param name="uri">The URI to GET</param> /// <param name="parameters">Parameters required by the endpoint (do not include credentials)</param> /// <param name="creds">(Optional) Overridden credentials for only this request</param> /// <returns></returns> public static string DoRequest(Uri uri, object parameters, AuthType authType, Credentials creds = null) { var sb = GetQueryStringBuilderFor(parameters); return DoRequest(new Uri(uri, "?" + sb), authType, creds); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Linq; using System.Net.Http.Headers; using System.Net.Test.Common; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; [ActiveIssue(20470, TargetFrameworkMonikers.UapAot)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetEventSource is only part of .NET Core.")] public class DiagnosticsTest : HttpClientTestBase { [Fact] public static void EventSource_ExistsWithCorrectId() { Type esType = typeof(HttpClient).GetTypeInfo().Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false); Assert.NotNull(esType); Assert.Equal("Microsoft-System-Net-Http", EventSource.GetName(esType)); Assert.Equal(Guid.Parse("bdd9a83e-1929-5482-0d73-2fe5e1c0e16d"), EventSource.GetGuid(esType)); Assert.NotEmpty(EventSource.GenerateManifest(esType, "assemblyPathToIncludeInManifest")); } // Diagnostic tests are each invoked in their own process as they enable/disable // process-wide EventSource-based tracing, and other tests in the same process // could interfere with the tests, as well as the enabling of tracing interfering // with those tests. /// <remarks> /// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler /// DiagnosticSources, since the global logging mechanism makes them conflict inherently. /// </remarks> [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticSourceLogging() { RemoteInvoke(useManagedHandlerString => { bool requestLogged = false; Guid requestGuid = Guid.Empty; bool responseLogged = false; Guid responseGuid = Guid.Empty; bool exceptionLogged = false; bool activityLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Request")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); requestGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId"); requestLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Response")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response"); responseGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId"); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.RanToCompletion, requestStatus); responseLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { exceptionLogged = true; } else if (kvp.Key.StartsWith("System.Net.Http.HttpRequestOut")) { activityLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable( s => !s.Contains("HttpRequestOut")); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } Assert.True(requestLogged, "Request was not logged."); // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1), "Response was not logged within 1 second timeout."); Assert.Equal(requestGuid, responseGuid); Assert.False(exceptionLogged, "Exception was logged for successful request"); Assert.False(activityLogged, "HttpOutReq was logged while HttpOutReq logging was disabled"); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } /// <remarks> /// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler /// DiagnosticSources, since the global logging mechanism makes them conflict inherently. /// </remarks> [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticSourceNoLogging() { RemoteInvoke(useManagedHandlerString => { bool requestLogged = false; bool responseLogged = false; bool activityStartLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { LoopbackServer.CreateServerAsync(async (server, url) => { Task<List<string>> requestLines = LoopbackServer.AcceptSocketAsync(server, (s, stream, reader, writer) => LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer)); Task<HttpResponseMessage> response = client.GetAsync(url); await Task.WhenAll(response, requestLines); AssertNoHeadersAreInjected(requestLines.Result); response.Result.Dispose(); }).Wait(); } Assert.False(requestLogged, "Request was logged while logging disabled."); Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while logging disabled."); WaitForFalse(() => responseLogged, TimeSpan.FromSeconds(1), "Response was logged while logging disabled."); Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while logging disabled."); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [ActiveIssue(23771, TestPlatforms.AnyUnix)] [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_HttpTracingEnabled_Succeeds() { RemoteInvoke(async useManagedHandlerString => { using (var listener = new TestEventListener("Microsoft-System-Net-Http", EventLevel.Verbose)) { var events = new ConcurrentQueue<EventWrittenEventArgs>(); await listener.RunWithCallbackAsync(events.Enqueue, async () => { // Exercise various code paths to get coverage of tracing using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { // Do a get to a loopback server await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( LoopbackServer.ReadRequestAndSendResponseAsync(server), client.GetAsync(url)); }); // Do a post to a remote server byte[] expectedData = Enumerable.Range(0, 20000).Select(i => unchecked((byte)i)).ToArray(); HttpContent content = new ByteArrayContent(expectedData); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData); using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.RemoteEchoServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } }); // We don't validate receiving specific events, but rather that we do at least // receive some events, and that enabling tracing doesn't cause other failures // in processing. Assert.DoesNotContain(events, ev => ev.EventId == 0); // make sure there are no event source error messages Assert.InRange(events.Count, 1, int.MaxValue); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticExceptionLogging() { RemoteInvoke(useManagedHandlerString => { bool exceptionLogged = false; bool responseLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Response")) { Assert.NotNull(kvp.Value); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.Faulted, requestStatus); responseLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception"); exceptionLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut")); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait(); } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1), "Response with exception was not logged within 1 second timeout."); Assert.True(exceptionLogged, "Exception was not logged"); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [ActiveIssue(23209)] [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticCancelledLogging() { RemoteInvoke(useManagedHandlerString => { bool cancelLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Response")) { Assert.NotNull(kvp.Value); var status = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.Canceled, status); Volatile.Write(ref cancelLogged, true); } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut")); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { LoopbackServer.CreateServerAsync(async (server, url) => { CancellationTokenSource tcs = new CancellationTokenSource(); Task request = LoopbackServer.AcceptSocketAsync(server, (s, stream, reader, writer) => { tcs.Cancel(); return LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer); }); Task response = client.GetAsync(url, tcs.Token); await Assert.ThrowsAnyAsync<Exception>(() => TestHelper.WhenAllCompletedOrAnyFailed(response, request)); }).Wait(); } } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => Volatile.Read(ref cancelLogged), TimeSpan.FromSeconds(1), "Cancellation was not logged within 1 second timeout."); diagnosticListenerObserver.Disable(); return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticSourceActivityLogging() { RemoteInvoke(useManagedHandlerString => { bool requestLogged = false; bool responseLogged = false; bool activityStartLogged = false; bool activityStopLogged = false; bool exceptionLogged = false; Activity parentActivity = new Activity("parent"); parentActivity.AddBaggage("correlationId", Guid.NewGuid().ToString()); parentActivity.AddBaggage("moreBaggage", Guid.NewGuid().ToString()); parentActivity.AddTag("tag", "tag"); //add tag to ensure it is not injected into request parentActivity.Start(); var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true;} else if (kvp.Key.Equals("System.Net.Http.Exception")) { exceptionLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { Assert.NotNull(kvp.Value); Assert.NotNull(Activity.Current); Assert.Equal(parentActivity, Activity.Current.Parent); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); activityStartLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { Assert.NotNull(kvp.Value); Assert.NotNull(Activity.Current); Assert.Equal(parentActivity, Activity.Current.Parent); Assert.True(Activity.Current.Duration != TimeSpan.Zero); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response"); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.RanToCompletion, requestStatus); activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => s.Contains("HttpRequestOut")); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { LoopbackServer.CreateServerAsync(async (server, url) => { Task<List<string>> requestLines = LoopbackServer.AcceptSocketAsync(server, (s, stream, reader, writer) => LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer)); Task<HttpResponseMessage> response = client.GetAsync(url); await Task.WhenAll(response, requestLines); AssertHeadersAreInjected(requestLines.Result, parentActivity); response.Result.Dispose(); }).Wait(); } Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged."); Assert.False(requestLogged, "Request was logged when Activity logging was enabled."); // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout."); Assert.False(exceptionLogged, "Exception was logged for successful request"); Assert.False(responseLogged, "Response was logged when Activity logging was enabled."); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticSourceUrlFilteredActivityLogging() { RemoteInvoke(useManagedHandlerString => { bool activityStartLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")){activityStartLogged = true;} else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) {activityStopLogged = true;} }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable((s, r, _) => { if (s.StartsWith("System.Net.Http.HttpRequestOut")) { var request = r as HttpRequestMessage; if (request != null) return !request.RequestUri.Equals(Configuration.Http.RemoteEchoServer); } return true; }); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while URL disabled."); // Poll with a timeout since logging response is not synchronized with returning a response. Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while URL disabled."); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticExceptionActivityLogging() { RemoteInvoke(useManagedHandlerString => { bool exceptionLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.Faulted, requestStatus); activityStopLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception"); exceptionLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait(); } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "Response with exception was not logged within 1 second timeout."); Assert.True(exceptionLogged, "Exception was not logged"); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticSourceNewAndDeprecatedEventsLogging() { RemoteInvoke(useManagedHandlerString => { bool requestLogged = false; bool responseLogged = false; bool activityStartLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true;} else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged."); Assert.True(requestLogged, "Request was not logged."); // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout."); Assert.True(responseLogged, "Response was not logged."); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticExceptionOnlyActivityLogging() { RemoteInvoke(useManagedHandlerString => { bool exceptionLogged = false; bool activityLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception"); exceptionLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.Exception")); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait(); } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => exceptionLogged, TimeSpan.FromSeconds(1), "Exception was not logged within 1 second timeout."); Assert.False(activityLogged, "HttpOutReq was logged when logging was disabled"); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticStopOnlyActivityLogging() { RemoteInvoke(useManagedHandlerString => { bool activityStartLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { Assert.NotNull(Activity.Current); activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.HttpRequestOut")); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout."); Assert.False(activityStartLogged, "HttpRequestOut.Start was logged when start logging was disabled"); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticCancelledActivityLogging() { RemoteInvoke(useManagedHandlerString => { bool cancelLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key == "System.Net.Http.HttpRequestOut.Stop") { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); var status = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.Canceled, status); Volatile.Write(ref cancelLogged, true); } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { LoopbackServer.CreateServerAsync(async (server, url) => { CancellationTokenSource tcs = new CancellationTokenSource(); Task request = LoopbackServer.AcceptSocketAsync(server, (s, stream, reader, writer) => { tcs.Cancel(); return LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer); }); Task response = client.GetAsync(url, tcs.Token); await Assert.ThrowsAnyAsync<Exception>(() => TestHelper.WhenAllCompletedOrAnyFailed(response, request)); }).Wait(); } } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => Volatile.Read(ref cancelLogged), TimeSpan.FromSeconds(1), "Cancellation was not logged within 1 second timeout."); diagnosticListenerObserver.Disable(); return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } private static T GetPropertyValueFromAnonymousTypeInstance<T>(object obj, string propertyName) { Type t = obj.GetType(); PropertyInfo p = t.GetRuntimeProperty(propertyName); object propertyValue = p.GetValue(obj); Assert.NotNull(propertyValue); Assert.IsAssignableFrom<T>(propertyValue); return (T)propertyValue; } private static void WaitForTrue(Func<bool> p, TimeSpan timeout, string message) { // Assert that spin doesn't time out. Assert.True(SpinWait.SpinUntil(p, timeout), message); } private static void WaitForFalse(Func<bool> p, TimeSpan timeout, string message) { // Assert that spin times out. Assert.False(SpinWait.SpinUntil(p, timeout), message); } private void AssertHeadersAreInjected(List<string> requestLines, Activity parent) { string requestId = null; var correlationContext = new List<NameValueHeaderValue>(); foreach (var line in requestLines) { if (line.StartsWith("Request-Id")) { requestId = line.Substring("Request-Id".Length).Trim(' ', ':'); } if (line.StartsWith("Correlation-Context")) { var corrCtxString = line.Substring("Correlation-Context".Length).Trim(' ', ':'); foreach (var kvp in corrCtxString.Split(',')) { correlationContext.Add(NameValueHeaderValue.Parse(kvp)); } } } Assert.True(requestId != null, "Request-Id was not injected when instrumentation was enabled"); Assert.True(requestId.StartsWith(parent.Id)); Assert.NotEqual(parent.Id, requestId); List<KeyValuePair<string, string>> baggage = parent.Baggage.ToList(); Assert.Equal(baggage.Count, correlationContext.Count); foreach (var kvp in baggage) { Assert.Contains(new NameValueHeaderValue(kvp.Key, kvp.Value), correlationContext); } } private void AssertNoHeadersAreInjected(List<string> requestLines) { foreach (var line in requestLines) { Assert.False(line.StartsWith("Request-Id"), "Request-Id header was injected when instrumentation was disabled"); Assert.False(line.StartsWith("Correlation-Context"), "Correlation-Context header was injected when instrumentation was disabled"); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Authorization { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// ClassicAdministratorsOperations operations. /// </summary> internal partial class ClassicAdministratorsOperations : IServiceOperations<AuthorizationManagementClient>, IClassicAdministratorsOperations { /// <summary> /// Initializes a new instance of the ClassicAdministratorsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ClassicAdministratorsOperations(AuthorizationManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AuthorizationManagementClient /// </summary> public AuthorizationManagementClient Client { get; private set; } /// <summary> /// Gets a list of classic administrators for the subscription. /// </summary> /// <param name='apiVersion'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<ClassicAdministrator>>> ListWithHttpMessagesAsync(string apiVersion, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (apiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "apiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ClassicAdministrator>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<ClassicAdministrator>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of classic administrators for the subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<ClassicAdministrator>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ClassicAdministrator>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<ClassicAdministrator>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { /// <summary> /// This is the base class of all code elements. /// </summary> public abstract class AbstractCodeElement : AbstractCodeModelObject, ICodeElementContainer<AbstractCodeElement>, EnvDTE.CodeElement, EnvDTE80.CodeElement2 { private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly int? _nodeKind; internal AbstractCodeElement( CodeModelState state, FileCodeModel fileCodeModel, int? nodeKind = null) : base(state) { Debug.Assert(fileCodeModel != null); _fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel); _nodeKind = nodeKind; } internal FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } protected SyntaxTree GetSyntaxTree() { return FileCodeModel.GetSyntaxTree(); } protected Document GetDocument() { return FileCodeModel.GetDocument(); } protected SemanticModel GetSemanticModel() { return FileCodeModel.GetSemanticModel(); } protected ProjectId GetProjectId() { return FileCodeModel.GetProjectId(); } internal bool IsValidNode() { if (!TryLookupNode(out var node)) { return false; } if (_nodeKind != null && _nodeKind.Value != node.RawKind) { return false; } return true; } internal virtual SyntaxNode LookupNode() { if (!TryLookupNode(out var node)) { throw Exceptions.ThrowEFail(); } return node; } internal abstract bool TryLookupNode(out SyntaxNode node); internal virtual ISymbol LookupSymbol() { var semanticModel = GetSemanticModel(); var node = LookupNode(); return semanticModel.GetDeclaredSymbol(node); } protected void UpdateNode<T>(Action<SyntaxNode, T> updater, T value) { FileCodeModel.EnsureEditor(() => { var node = LookupNode(); updater(node, value); }); } public abstract EnvDTE.vsCMElement Kind { get; } protected virtual string GetName() { var node = LookupNode(); return CodeModelService.GetName(node); } protected virtual void SetName(string value) { UpdateNode(FileCodeModel.UpdateName, value); } public string Name { get { return GetName(); } set { SetName(value); } } protected virtual string GetFullName() { var node = LookupNode(); var semanticModel = GetSemanticModel(); return CodeModelService.GetFullName(node, semanticModel); } public string FullName { get { return GetFullName(); } } public abstract object Parent { get; } public abstract EnvDTE.CodeElements Children { get; } EnvDTE.CodeElements ICodeElementContainer<AbstractCodeElement>.GetCollection() { return Children; } protected virtual EnvDTE.CodeElements GetCollection() { return GetCollection<AbstractCodeElement>(Parent); } public virtual EnvDTE.CodeElements Collection { get { return GetCollection(); } } public EnvDTE.TextPoint StartPoint { get { var point = CodeModelService.GetStartPoint(LookupNode()); if (point == null) { return null; } return FileCodeModel.TextManagerAdapter.CreateTextPoint(FileCodeModel, point.Value); } } public EnvDTE.TextPoint EndPoint { get { var point = CodeModelService.GetEndPoint(LookupNode()); if (point == null) { return null; } return FileCodeModel.TextManagerAdapter.CreateTextPoint(FileCodeModel, point.Value); } } public virtual EnvDTE.TextPoint GetStartPoint(EnvDTE.vsCMPart part) { var point = CodeModelService.GetStartPoint(LookupNode(), part); if (point == null) { return null; } return FileCodeModel.TextManagerAdapter.CreateTextPoint(FileCodeModel, point.Value); } public virtual EnvDTE.TextPoint GetEndPoint(EnvDTE.vsCMPart part) { var point = CodeModelService.GetEndPoint(LookupNode(), part); if (point == null) { return null; } return FileCodeModel.TextManagerAdapter.CreateTextPoint(FileCodeModel, point.Value); } public virtual EnvDTE.vsCMInfoLocation InfoLocation { get { // The default implementation assumes project-located elements... return EnvDTE.vsCMInfoLocation.vsCMInfoLocationProject; } } public virtual bool IsCodeType { get { return false; } } public EnvDTE.ProjectItem ProjectItem { get { return FileCodeModel.Parent; } } public string ExtenderCATID { get { throw new NotImplementedException(); } } protected virtual object GetExtenderNames() { throw Exceptions.ThrowENotImpl(); } public object ExtenderNames { get { return GetExtenderNames(); } } protected virtual object GetExtender(string name) { throw Exceptions.ThrowENotImpl(); } public object get_Extender(string extenderName) { return GetExtender(extenderName); } public string ElementID { get { throw new NotImplementedException(); } } public virtual void RenameSymbol(string newName) { if (string.IsNullOrEmpty(newName)) { throw new ArgumentException(); } CodeModelService.Rename(LookupSymbol(), newName, this.Workspace.CurrentSolution); } protected virtual Document DeleteCore(Document document) { var node = LookupNode(); return CodeModelService.Delete(document, node); } /// <summary> /// Delete the element from the source file. /// </summary> internal void Delete() { FileCodeModel.PerformEdit(document => { return DeleteCore(document); }); } [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Required by interface")] public string get_Prototype(int flags) { return CodeModelService.GetPrototype(LookupNode(), LookupSymbol(), (PrototypeFlags)flags); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Miracle.Arguments { /// <summary> /// Implementation of an argument definition /// </summary> /// <typeparam name="T">Any type that can be converted from string</typeparam> class ArgumentDefinition<T> : IArgumentDefinition { private readonly PropertyInfo _propertyInfo; private readonly List<T> _values = new List<T>(); /// <summary> /// Constructor /// </summary> /// <param name="propertyInfo"></param> public ArgumentDefinition(PropertyInfo propertyInfo) { _propertyInfo = propertyInfo; } #region IArgumentDefinition Members private object ChangeType(string value, Type conversionType) { if(conversionType.IsEnum) return Enum.Parse(conversionType, value, true); if (conversionType == typeof (Guid)) #if NET35 return new Guid(value); #else return Guid.Parse(value); #endif if (conversionType == typeof(TimeSpan)) return TimeSpan.Parse(value); return Convert.ChangeType(value, conversionType); } /// <summary> /// Add value to list of values /// </summary> /// <param name="value">String value that are to be converted to T</param> public void AddValue(string value) { Type type = typeof(T); try { if (value == null && IsBoolean) value = true.ToString(); object convertedValue = null; if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { Type underlyingType = Nullable.GetUnderlyingType(type); if (value != null) convertedValue = ChangeType(value, underlyingType); else { if(underlyingType.IsEnum) throw new CommandLineParserException("Missing enum value for nullable argument"); } } else convertedValue = ChangeType(value, type); AddRawValue(convertedValue); } catch (Exception ex) { throw new RetryableCommandLineArgumentException(string.Format("Unable to convert [{0}] into {1}", value, type.Name), ex); } } public void AddRawValue(object value) { if (IsMultiValue || (!HasValue)) _values.Add((T)value); else _values[0] = (T)value; } /// <summary> /// Get collected value(s) for this argument /// </summary> /// <param name="argumentClass">class that are to recieve value</param> public void GetValues(object argumentClass) { // has value been set if (_values.Count > 0) { _propertyInfo.SetValue(argumentClass, IsMultiValue ? (object)_values.ToArray() : _values[0], null); } // Otherwise leave it alone! } public void Clear() { _values.Clear(); } /// <summary> /// Is this a required argument? /// </summary> public bool IsRequired { get { return _propertyInfo.GetCustomAttributes(typeof(ArgumentRequiredAttribute), true).Any(); } } /// <summary> /// Is this a multi value argument? /// </summary> public bool IsMultiValue { get { return _propertyInfo.PropertyType.IsArray; } } /// <summary> /// Is this a boolean argument? /// </summary> public bool IsBoolean { get { return (typeof(T) == typeof(bool) || typeof(T) == typeof(bool?)); } } /// <summary> /// Is this a boolean argument? /// </summary> public bool IsString { get { return (typeof(T) == typeof(string)); } } private Type ArgumentType { get { Type type = typeof (T); if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof (Nullable<>))) { type = Nullable.GetUnderlyingType(type); } return type; } } public bool IsEnum { get { return ArgumentType.IsEnum; } } public string[] EnumValueList { get { Type type = ArgumentType; return type.IsEnum ? Enum.GetNames(type) : new string[] {}; } } /// <summary> /// Does this argument contain at least one value? /// </summary> public bool HasValue { get { return _values.Count > 0; } } public object Value { get { return HasValue ? (object) _values[0] : null; } } public PropertyInfo Property { get { return _propertyInfo; } } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Providers.Streams.AzureQueue; using Orleans.Runtime; using Orleans.Serialization.TypeSystem; using Orleans.Streams; using Orleans.TestingHost; using Tester; using Tester.AzureUtils; using Tester.AzureUtils.Streaming; using Tester.AzureUtils.Utilities; using TestExtensions; using UnitTests.GrainInterfaces; using UnitTests.Grains; using Xunit; using Xunit.Abstractions; namespace UnitTests.StreamingTests { [TestCategory("Streaming"), TestCategory("Limits")] public class StreamLimitTests : TestClusterPerTest { public const string AzureQueueStreamProviderName = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME; public const string SmsStreamProviderName = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME; private static int MaxExpectedPerStream = 500; private static int MaxConsumersPerStream; private static int MaxProducersPerStream; private const int MessagePipelineSize = 1000; private const int InitPipelineSize = 500; private IManagementGrain mgmtGrain; private string StreamNamespace; private readonly ITestOutputHelper output; private const int queueCount = 8; protected override void ConfigureTestCluster(Orleans.TestingHost.TestClusterBuilder builder) { TestUtils.CheckForAzureStorage(); builder.AddSiloBuilderConfigurator<TestClusterBuilder>(); builder.AddClientBuilderConfigurator<TestClusterBuilder>(); } private class TestClusterBuilder : ISiloConfigurator, IClientBuilderConfigurator { public void Configure(ISiloBuilder hostBuilder) { hostBuilder .AddSimpleMessageStreamProvider(SmsStreamProviderName) .AddSimpleMessageStreamProvider("SMSProviderDoNotOptimizeForImmutableData", options => options.OptimizeForImmutableData = false) .AddAzureTableGrainStorage("AzureStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.ConfigureTestDefaults(); options.DeleteStateOnClear = true; })) .AddAzureTableGrainStorage("PubSubStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.DeleteStateOnClear = true; options.ConfigureTestDefaults(); })) .AddAzureQueueStreams(AzureQueueStreamProviderName, ob => ob.Configure<IOptions<ClusterOptions>>( (options, dep) => { options.ConfigureTestDefaults(); options.QueueNames = AzureQueueUtilities.GenerateQueueNames(dep.Value.ClusterId, queueCount); })) .AddAzureQueueStreams("AzureQueueProvider2", ob=>ob.Configure<IOptions<ClusterOptions>>( (options, dep) => { options.ConfigureTestDefaults(); options.QueueNames = AzureQueueUtilities.GenerateQueueNames($"{dep.Value.ClusterId}2", queueCount); })) .AddMemoryGrainStorage("MemoryStore", options => options.NumStorageGrains = 1); } public void Configure(IConfiguration configuration, Orleans.IClientBuilder clientBuilder) => clientBuilder.AddStreaming(); } public StreamLimitTests(ITestOutputHelper output) { this.output = output; StreamNamespace = StreamTestsConstants.StreamLifecycleTestsNamespace; } public override async Task InitializeAsync() { await base.InitializeAsync(); this.mgmtGrain = this.GrainFactory.GetGrain<IManagementGrain>(0); } public override async Task DisposeAsync() { await base.DisposeAsync(); if (!string.IsNullOrWhiteSpace(TestDefaultConfiguration.DataConnectionString)) { await AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance, AzureQueueUtilities.GenerateQueueNames(this.HostedCluster.Options.ClusterId, queueCount), new AzureQueueOptions().ConfigureTestDefaults()); await AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance, AzureQueueUtilities.GenerateQueueNames($"{this.HostedCluster.Options.ClusterId}2", queueCount), new AzureQueueOptions().ConfigureTestDefaults()); } } [SkippableFact] public async Task SMS_Limits_FindMax_Consumers() { // 1 Stream, 1 Producer, X Consumers Guid streamId = Guid.NewGuid(); string streamProviderName = SmsStreamProviderName; output.WriteLine("Starting search for MaxConsumersPerStream value using stream {0}", streamId); IStreamLifecycleProducerGrain producer = this.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamId, this.StreamNamespace, streamProviderName); int loopCount = 0; try { // Loop until something breaks! for (loopCount = 1; loopCount <= MaxExpectedPerStream; loopCount++) { IStreamLifecycleConsumerGrain consumer = this.GrainFactory.GetGrain<IStreamLifecycleConsumerGrain>(Guid.NewGuid()); await consumer.BecomeConsumer(streamId, this.StreamNamespace, streamProviderName); } } catch (Exception exc) { this.output.WriteLine("Stopping loop at loopCount={0} due to exception {1}", loopCount, exc); } MaxConsumersPerStream = loopCount - 1; output.WriteLine("Finished search for MaxConsumersPerStream with value {0}", MaxConsumersPerStream); Assert.NotEqual(0, MaxConsumersPerStream); // "MaxConsumersPerStream should be greater than zero." output.WriteLine("MaxConsumersPerStream={0}", MaxConsumersPerStream); } [SkippableFact, TestCategory("Functional")] public async Task SMS_Limits_FindMax_Producers() { // 1 Stream, X Producers, 1 Consumer Guid streamId = Guid.NewGuid(); string streamProviderName = SmsStreamProviderName; output.WriteLine("Starting search for MaxProducersPerStream value using stream {0}", streamId); IStreamLifecycleConsumerGrain consumer = this.GrainFactory.GetGrain<IStreamLifecycleConsumerGrain>(Guid.NewGuid()); await consumer.BecomeConsumer(streamId, this.StreamNamespace, streamProviderName); int loopCount = 0; try { // Loop until something breaks! for (loopCount = 1; loopCount <= MaxExpectedPerStream; loopCount++) { IStreamLifecycleProducerGrain producer = this.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamId, this.StreamNamespace, streamProviderName); } } catch (Exception exc) { this.output.WriteLine("Stopping loop at loopCount={0} due to exception {1}", loopCount, exc); } MaxProducersPerStream = loopCount - 1; output.WriteLine("Finished search for MaxProducersPerStream with value {0}", MaxProducersPerStream); Assert.NotEqual(0, MaxProducersPerStream); // "MaxProducersPerStream should be greater than zero." output.WriteLine("MaxProducersPerStream={0}", MaxProducersPerStream); } [SkippableFact, TestCategory("Functional")] public async Task SMS_Limits_P1_C128_S1() { // 1 Stream, 1 Producer, 128 Consumers await Test_Stream_Limits( SmsStreamProviderName, 1, 1, 128); } [SkippableFact, TestCategory("Failures")] public async Task SMS_Limits_P128_C1_S1() { // 1 Stream, 128 Producers, 1 Consumer await Test_Stream_Limits( SmsStreamProviderName, 1, 128, 1); } [SkippableFact, TestCategory("Failures")] public async Task SMS_Limits_P128_C128_S1() { // 1 Stream, 128 Producers, 128 Consumers await Test_Stream_Limits( SmsStreamProviderName, 1, 128, 128); } [SkippableFact, TestCategory("Failures")] public async Task SMS_Limits_P1_C400_S1() { // 1 Stream, 1 Producer, 400 Consumers int numConsumers = 400; await Test_Stream_Limits( SmsStreamProviderName, 1, 1, numConsumers); } [SkippableFact, TestCategory("Burst")] public async Task SMS_Limits_Max_Producers_Burst() { if (MaxProducersPerStream == 0) await SMS_Limits_FindMax_Producers(); output.WriteLine("Using MaxProducersPerStream={0}", MaxProducersPerStream); // 1 Stream, Max Producers, 1 Consumer await Test_Stream_Limits( SmsStreamProviderName, 1, MaxProducersPerStream, 1, useFanOut: true); } [SkippableFact, TestCategory("Functional")] public async Task SMS_Limits_Max_Producers_NoBurst() { if (MaxProducersPerStream == 0) await SMS_Limits_FindMax_Producers(); output.WriteLine("Using MaxProducersPerStream={0}", MaxProducersPerStream); // 1 Stream, Max Producers, 1 Consumer await Test_Stream_Limits( SmsStreamProviderName, 1, MaxProducersPerStream, 1, useFanOut: false); } [SkippableFact, TestCategory("Burst")] public async Task SMS_Limits_Max_Consumers_Burst() { if (MaxConsumersPerStream == 0) await SMS_Limits_FindMax_Consumers(); output.WriteLine("Using MaxConsumersPerStream={0}", MaxConsumersPerStream); // 1 Stream, Max Producers, 1 Consumer await Test_Stream_Limits( SmsStreamProviderName, 1, 1, MaxConsumersPerStream, useFanOut: true); } [SkippableFact] public async Task SMS_Limits_Max_Consumers_NoBurst() { if (MaxConsumersPerStream == 0) await SMS_Limits_FindMax_Consumers(); output.WriteLine("Using MaxConsumersPerStream={0}", MaxConsumersPerStream); // 1 Stream, Max Producers, 1 Consumer await Test_Stream_Limits( SmsStreamProviderName, 1, 1, MaxConsumersPerStream, useFanOut: false); } [SkippableFact, TestCategory("Failures"), TestCategory("Burst")] public async Task SMS_Limits_P9_C9_S152_Burst() { // 152 * 9 ~= 1360 target per second // 152 Streams, x9 Producers, x9 Consumers int numStreams = 152; await Test_Stream_Limits( SmsStreamProviderName, numStreams, 9, 9, useFanOut: true); } [SkippableFact, TestCategory("Failures")] public async Task SMS_Limits_P9_C9_S152_NoBurst() { // 152 * 9 ~= 1360 target per second // 152 Streams, x9 Producers, x9 Consumers int numStreams = 152; await Test_Stream_Limits( SmsStreamProviderName, numStreams, 9, 9, useFanOut: false); } [SkippableFact, TestCategory("Failures"), TestCategory("Burst")] public async Task SMS_Limits_P1_C9_S152_Burst() { // 152 * 9 ~= 1360 target per second // 152 Streams, x1 Producer, x9 Consumers int numStreams = 152; await Test_Stream_Limits( SmsStreamProviderName, numStreams, 1, 9, useFanOut: true); } [SkippableFact, TestCategory("Failures")] public async Task SMS_Limits_P1_C9_S152_NoBurst() { // 152 * 9 ~= 1360 target per second // 152 Streams, x1 Producer, x9 Consumers int numStreams = 152; await Test_Stream_Limits( SmsStreamProviderName, numStreams, 1, 9, useFanOut: false); } [SkippableFact(Skip = "Ignore"), TestCategory("Performance"), TestCategory("Burst")] public async Task SMS_Churn_Subscribers_P0_C10_ManyStreams() { int numStreams = 2000; int pipelineSize = 10000; await Test_Stream_Churn_NumStreams( SmsStreamProviderName, pipelineSize, numStreams, numConsumers: 10, numProducers: 0 ); } //[SkippableFact, TestCategory("Performance"), TestCategory("Burst")] //public async Task SMS_Churn_Subscribers_P1_C9_ManyStreams_TimePeriod() //{ // await Test_Stream_Churn_TimePeriod( // StreamReliabilityTests.SMS_STREAM_PROVIDER_NAME, // InitPipelineSize, // TimeSpan.FromSeconds(60), // numProducers: 1 // ); //} [SkippableFact, TestCategory("Performance"), TestCategory("Burst")] public async Task SMS_Churn_FewPublishers_C9_ManyStreams() { int numProducers = 0; int numStreams = 1000; int pipelineSize = 100; await Test_Stream_Churn_NumStreams_FewPublishers( SmsStreamProviderName, pipelineSize, numStreams, numProducers: numProducers, warmUpPubSub: true ); } [SkippableFact, TestCategory("Performance"), TestCategory("Burst")] public async Task SMS_Churn_FewPublishers_C9_ManyStreams_PubSubDirect() { int numProducers = 0; int numStreams = 1000; int pipelineSize = 100; await Test_Stream_Churn_NumStreams_FewPublishers( SmsStreamProviderName, pipelineSize, numStreams, numProducers: numProducers, warmUpPubSub: true, normalSubscribeCalls: false ); } private Task Test_Stream_Churn_NumStreams_FewPublishers( string streamProviderName, int pipelineSize, int numStreams, int numConsumers = 9, int numProducers = 4, bool warmUpPubSub = true, bool warmUpProducers = false, bool normalSubscribeCalls = true) { output.WriteLine("Testing churn with {0} Streams on {1} Producers with {2} Consumers per Stream", numStreams, numProducers, numConsumers); AsyncPipeline pipeline = new AsyncPipeline(pipelineSize); // Create streamId Guids StreamId[] streamIds = new StreamId[numStreams]; for (int i = 0; i < numStreams; i++) { streamIds[i] = StreamId.Create(this.StreamNamespace, Guid.NewGuid()); } int activeConsumerGrains = ActiveGrainCount(typeof(StreamLifecycleConsumerGrain)); Assert.Equal(0, activeConsumerGrains); // "Initial Consumer count should be zero" int activeProducerGrains = ActiveGrainCount(typeof(StreamLifecycleProducerGrain)); Assert.Equal(0, activeProducerGrains); // "Initial Producer count should be zero" if (warmUpPubSub) { WarmUpPubSub(streamProviderName, streamIds, pipeline); pipeline.Wait(); int activePubSubGrains = ActiveGrainCount(typeof(PubSubRendezvousGrain)); Assert.Equal(streamIds.Length, activePubSubGrains); // "Initial PubSub count -- should all be warmed up" } Guid[] producerIds = new Guid[numProducers]; if (numProducers > 0 && warmUpProducers) { // Warm up Producers to pre-create grains for (int i = 0; i < numProducers; i++) { producerIds[i] = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(producerIds[i]); Task promise = grain.Ping(); pipeline.Add(promise); } pipeline.Wait(); int activePublisherGrains = this.ActiveGrainCount(typeof(StreamLifecycleProducerGrain)); Assert.Equal(numProducers, activePublisherGrains); // "Initial Publisher count -- should all be warmed up" } var promises = new List<Task>(); Stopwatch sw = Stopwatch.StartNew(); if (numProducers > 0) { // Producers for (int i = 0; i < numStreams; i++) { StreamId streamId = streamIds[i]; Guid producerId = producerIds[i % numProducers]; var grain = this.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(producerId); Task promise = grain.BecomeProducer(streamId, streamProviderName); promises.Add(promise); pipeline.Add(promise); } pipeline.Wait(); promises.Clear(); } // Consumers for (int i = 0; i < numStreams; i++) { StreamId streamId = streamIds[i]; Task promise = SetupOneStream(streamId, streamProviderName, pipeline, numConsumers, 0, normalSubscribeCalls); promises.Add(promise); } pipeline.Wait(); Task.WhenAll(promises).Wait(); sw.Stop(); int consumerCount = ActiveGrainCount(typeof(StreamLifecycleConsumerGrain)); Assert.Equal(activeConsumerGrains + (numStreams * numConsumers), consumerCount); // "The right number of Consumer grains are active" int producerCount = ActiveGrainCount(typeof(StreamLifecycleProducerGrain)); Assert.Equal(activeProducerGrains + (numStreams * numProducers), producerCount); // "The right number of Producer grains are active" int pubSubCount = ActiveGrainCount(typeof(PubSubRendezvousGrain)); Assert.Equal(streamIds.Length, pubSubCount); // "Final PubSub count -- no more started" TimeSpan elapsed = sw.Elapsed; int totalSubscriptions = numStreams * numConsumers; double rps = totalSubscriptions / elapsed.TotalSeconds; output.WriteLine("Subscriptions-per-second = {0} during period {1}", rps, elapsed); Assert.NotEqual(0.0, rps); // "RPS greater than zero" return Task.CompletedTask; } private Task Test_Stream_Churn_NumStreams( string streamProviderName, int pipelineSize, int numStreams, int numConsumers = 9, int numProducers = 1, bool warmUpPubSub = true, bool normalSubscribeCalls = true) { output.WriteLine("Testing churn with {0} Streams with {1} Consumers and {2} Producers per Stream NormalSubscribe={3}", numStreams, numConsumers, numProducers, normalSubscribeCalls); AsyncPipeline pipeline = new AsyncPipeline(pipelineSize); var promises = new List<Task>(); // Create streamId Guids StreamId[] streamIds = new StreamId[numStreams]; for (int i = 0; i < numStreams; i++) { streamIds[i] = StreamId.Create(this.StreamNamespace, Guid.NewGuid()); } if (warmUpPubSub) { WarmUpPubSub(streamProviderName, streamIds, pipeline); pipeline.Wait(); int activePubSubGrains = ActiveGrainCount(typeof(PubSubRendezvousGrain)); Assert.Equal(streamIds.Length, activePubSubGrains); // "Initial PubSub count -- should all be warmed up" } int activeConsumerGrains = ActiveGrainCount(typeof(StreamLifecycleConsumerGrain)); Assert.Equal(0, activeConsumerGrains); // "Initial Consumer count should be zero" Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < numStreams; i++) { Task promise = SetupOneStream(streamIds[i], streamProviderName, pipeline, numConsumers, numProducers, normalSubscribeCalls); promises.Add(promise); } Task.WhenAll(promises).Wait(); sw.Stop(); int consumerCount = ActiveGrainCount(typeof(StreamLifecycleConsumerGrain)); Assert.Equal(activeConsumerGrains + (numStreams * numConsumers), consumerCount); // "The correct number of new Consumer grains are active" TimeSpan elapsed = sw.Elapsed; int totalSubscriptions = numStreams * numConsumers; double rps = totalSubscriptions / elapsed.TotalSeconds; output.WriteLine("Subscriptions-per-second = {0} during period {1}", rps, elapsed); Assert.NotEqual(0.0, rps); // "RPS greater than zero" return Task.CompletedTask; } //private async Task Test_Stream_Churn_TimePeriod( // string streamProviderName, // int pipelineSize, // TimeSpan duration, // int numConsumers = 9, // int numProducers = 1) //{ // output.WriteLine("Testing Subscription churn for duration {0} with {1} Consumers and {2} Producers per Stream", // duration, numConsumers, numProducers); // AsyncPipeline pipeline = new AsyncPipeline(pipelineSize); // var promises = new List<Task>(); // Stopwatch sw = Stopwatch.StartNew(); // for (int i = 0; sw.Elapsed <= duration; i++) // { // Guid streamId = Guid.NewGuid(); // Task promise = SetupOneStream(streamId, streamProviderName, pipeline, numConsumers, numProducers); // promises.Add(promise); // } // await Task.WhenAll(promises); // sw.Stop(); // TimeSpan elapsed = sw.Elapsed; // int totalSubscription = numSt* numConsumers); // double rps = totalSubscription/elapsed.TotalSeconds; // output.WriteLine("Subscriptions-per-second = {0} during period {1}", rps, elapsed); // Assert.NotEqual(0.0, rps, "RPS greater than zero"); //} private void WarmUpPubSub(string streamProviderName, StreamId[] streamIds, AsyncPipeline pipeline) { int numStreams = streamIds.Length; // Warm up PubSub for the appropriate streams for (int i = 0; i < numStreams; i++) { var streamId = new InternalStreamId(streamProviderName, streamIds[i]); _ = streamProviderName + "_" + this.StreamNamespace; IPubSubRendezvousGrain pubsub = this.GrainFactory.GetGrain<IPubSubRendezvousGrain>(streamId.ToString()); Task promise = pubsub.Validate(); pipeline.Add(promise); } pipeline.Wait(); } private static bool producersFirst = true; private SimpleGrainStatistic[] grainCounts; private Task SetupOneStream( StreamId streamId, string streamProviderName, AsyncPipeline pipeline, int numConsumers, int numProducers, bool normalSubscribeCalls) { //output.WriteLine("Initializing Stream {0} with Consumers={1} Producers={2}", streamId, numConsumers, numProducers); List<Task> promises = new List<Task>(); if (producersFirst && numProducers > 0) { // Producers var p1 = SetupProducers(streamId, this.StreamNamespace, streamProviderName, pipeline, numProducers); promises.AddRange(p1); } // Consumers if (numConsumers > 0) { var c = SetupConsumers(streamId, this.StreamNamespace, streamProviderName, pipeline, numConsumers, normalSubscribeCalls); promises.AddRange(c); } if (!producersFirst && numProducers > 0) { // Producers var p2 = SetupProducers(streamId, this.StreamNamespace, streamProviderName, pipeline, numProducers); promises.AddRange(p2); } return Task.WhenAll(promises); } private IList<Task> SetupProducers(StreamId streamId, string streamNamespace, string streamProviderName, AsyncPipeline pipeline, int numProducers) { var producers = new List<IStreamLifecycleProducerGrain>(); var promises = new List<Task>(); for (int loopCount = 0; loopCount < numProducers; loopCount++) { var grain = this.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(Guid.NewGuid()); producers.Add(grain); Task promise = grain.BecomeProducer(streamId, streamProviderName); if (loopCount == 0) { // First call for this stream, so wait for call to complete successfully so we know underlying infrastructure is set up. promise.Wait(); } promises.Add(promise); pipeline.Add(promise); } return promises; } private IList<Task> SetupConsumers(StreamId streamId, string streamNamespace, string streamProviderName, AsyncPipeline pipeline, int numConsumers, bool normalSubscribeCalls) { var consumers = new List<IStreamLifecycleConsumerGrain>(); var promises = new List<Task>(); _ = random.Next(); for (int loopCount = 0; loopCount < numConsumers; loopCount++) { var grain = this.GrainFactory.GetGrain<IStreamLifecycleConsumerGrain>(Guid.NewGuid()); consumers.Add(grain); Task promise; if (normalSubscribeCalls) { promise = grain.BecomeConsumer(streamId, streamProviderName); } else { promise = grain.TestBecomeConsumerSlim(streamId, streamProviderName); } //if (loopCount == 0) //{ // // First call for this stream, so wait for call to complete successfully so we know underlying infrastructure is set up. // promise.Wait(); //} promises.Add(promise); pipeline.Add(promise); } return promises; } private async Task Test_Stream_Limits( string streamProviderName, int numStreams, int numProducers, int numConsumers, int numMessages = 1, bool useFanOut = true) { output.WriteLine("Testing {0} Streams x Producers={1} Consumers={2} per stream with {3} messages each", 1, numProducers, numConsumers, numMessages); Stopwatch sw = Stopwatch.StartNew(); var promises = new List<Task<double>>(); for (int s = 0; s < numStreams; s++) { Guid streamId = Guid.NewGuid(); Task<double> promise = Task.Run( () => TestOneStream(streamId, streamProviderName, numProducers, numConsumers, numMessages, useFanOut)); promises.Add(promise); if (!useFanOut) { await promise; } } if (useFanOut) { output.WriteLine("Test: Waiting for {0} streams to finish", promises.Count); } double rps = (await Task.WhenAll(promises)).Sum(); promises.Clear(); output.WriteLine("Got total {0} RPS on {1} streams, or {2} RPS per streams", rps, numStreams, rps/numStreams); sw.Stop(); int totalMessages = numMessages * numStreams * numProducers; output.WriteLine("Sent {0} messages total on {1} Streams from {2} Producers to {3} Consumers in {4} at {5} RPS", totalMessages, numStreams, numStreams * numProducers, numStreams * numConsumers, sw.Elapsed, totalMessages / sw.Elapsed.TotalSeconds); } private async Task<double> TestOneStream(Guid streamId, string streamProviderName, int numProducers, int numConsumers, int numMessages, bool useFanOut = true) { output.WriteLine("Testing Stream {0} with Producers={1} Consumers={2} x {3} messages", streamId, numProducers, numConsumers, numMessages); Stopwatch sw = Stopwatch.StartNew(); List<IStreamLifecycleConsumerGrain> consumers = new List<IStreamLifecycleConsumerGrain>(); List<IStreamLifecycleProducerGrain> producers = new List<IStreamLifecycleProducerGrain>(); await InitializeTopology(streamId, this.StreamNamespace, streamProviderName, numProducers, numConsumers, producers, consumers, useFanOut); var promises = new List<Task>(); // Producers send M message each int item = 1; AsyncPipeline pipeline = new AsyncPipeline(MessagePipelineSize); foreach (var grain in producers) { for (int m = 0; m < numMessages; m++) { Task promise = grain.SendItem(item++); if (useFanOut) { pipeline.Add(promise); promises.Add(promise); } else { await promise; } } } if (useFanOut) { //output.WriteLine("Test: Waiting for {0} producers to finish sending {1} messages", producers.Count, promises.Count); await Task.WhenAll(promises); promises.Clear(); } var pubSub = StreamTestUtils.GetStreamPubSub(this.InternalClient); // Check Consumer counts var streamId1 = new InternalStreamId(streamProviderName, StreamId.Create(StreamNamespace, streamId)); int consumerCount = await pubSub.ConsumerCount(streamId1); Assert.Equal(numConsumers, consumerCount); // "ConsumerCount for Stream {0}", streamId // Check Producer counts int producerCount = await pubSub.ProducerCount(streamId1); Assert.Equal(numProducers, producerCount); // "ProducerCount for Stream {0}", streamId // Check message counts received by consumers int totalMessages = (numMessages + 1) * numProducers; foreach (var grain in consumers) { int count = await grain.GetReceivedCount(); Assert.Equal(totalMessages, count); // "ReceivedCount for Consumer grain {0}", grain.GetPrimaryKey()); } double rps = totalMessages/sw.Elapsed.TotalSeconds; //output.WriteLine("Sent {0} messages total from {1} Producers to {2} Consumers in {3} at {4} RPS", // totalMessages, numProducers, numConsumers, // sw.Elapsed, rps); return rps; } private async Task InitializeTopology(Guid streamId, string streamNamespace, string streamProviderName, int numProducers, int numConsumers, List<IStreamLifecycleProducerGrain> producers, List<IStreamLifecycleConsumerGrain> consumers, bool useFanOut) { //var promises = new List<Task>(); AsyncPipeline pipeline = new AsyncPipeline(InitPipelineSize); // Consumers for (int loopCount = 0; loopCount < numConsumers; loopCount++) { var grain = this.GrainFactory.GetGrain<IStreamLifecycleConsumerGrain>(Guid.NewGuid()); consumers.Add(grain); Task promise = grain.BecomeConsumer(streamId, streamNamespace, streamProviderName); if (useFanOut) { pipeline.Add(promise); //promises.Add(promise); //if (loopCount%WaitBatchSize == 0) //{ // output.WriteLine("InitializeTopology: Waiting for {0} consumers to initialize", promises.Count); // await Task.WhenAll(promises); // promises.Clear(); //} } else { await promise; } } if (useFanOut) { //output.WriteLine("InitializeTopology: Waiting for {0} consumers to initialize", promises.Count); //await Task.WhenAll(promises); //promises.Clear(); //output.WriteLine("InitializeTopology: Waiting for {0} consumers to initialize", pipeline.Count); pipeline.Wait(); } // Producers pipeline = new AsyncPipeline(InitPipelineSize); for (int loopCount = 0; loopCount < numProducers; loopCount++) { var grain = this.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(Guid.NewGuid()); producers.Add(grain); Task promise = grain.BecomeProducer(streamId, streamNamespace, streamProviderName); if (useFanOut) { pipeline.Add(promise); //promises.Add(promise); } else { await promise; } } if (useFanOut) { //output.WriteLine("InitializeTopology: Waiting for {0} producers to initialize", promises.Count); //await Task.WhenAll(promises); //promises.Clear(); //output.WriteLine("InitializeTopology: Waiting for {0} producers to initialize", pipeline.Count); pipeline.Wait(); } //nextGrainId += numProducers; } private int ActiveGrainCount(Type grainType) { var grainTypeName = RuntimeTypeNameFormatter.Format(grainType); grainCounts = mgmtGrain.GetSimpleGrainStatistics().Result; // Blocking Wait int grainCount = grainCounts .Where(g => g.GrainType == grainTypeName) .Select(s => s.ActivationCount) .Sum(); return grainCount; } } }
//------------------------------------------------------------------------------ // <copyright file="HtmlForm.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ // HtmlForm.cs // namespace System.Web.UI.HtmlControls { using System.ComponentModel; using System; using System.Collections; using System.Globalization; using System.IO; using System.Text; using System.Web.Configuration; using System.Web.Util; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Security; using System.Security.Permissions; /// <devdoc> /// <para> /// The <see langword='HtmlForm'/> class defines the methods, properties, and /// events for the HtmlForm control. This class provides programmatic access to the /// HTML &lt;form&gt; element on the server. /// </para> /// </devdoc> public class HtmlForm : HtmlContainerControl { private string _defaultFocus; private string _defaultButton; private bool _submitDisabledControls; private const string _aspnetFormID = "aspnetForm"; /// <devdoc> /// </devdoc> public HtmlForm() : base("form") { } [ WebCategory("Behavior"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string Action { get { string s = Attributes["action"]; return ((s != null) ? s : String.Empty); } set { Attributes["action"] = MapStringAttributeToString(value); } } /// <devdoc> /// Gets or sets default button for the form /// </devdoc> [ WebCategory("Behavior"), DefaultValue(""), ] public string DefaultButton { get { if (_defaultButton == null) { return String.Empty; } return _defaultButton; } set { _defaultButton = value; } } /// <devdoc> /// Gets or sets default focused control for the form /// </devdoc> [ WebCategory("Behavior"), DefaultValue(""), ] public string DefaultFocus { get { if (_defaultFocus == null) { return String.Empty; } return _defaultFocus; } set { _defaultFocus = value; } } /* * Encode Type property. */ /// <devdoc> /// <para> /// Gets or sets the Enctype attribute of the form. This is /// the encoding type that browsers /// use when posting the form's data to the server. /// </para> /// </devdoc> [ WebCategory("Behavior"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string Enctype { get { string s = Attributes["enctype"]; return ((s != null) ? s : String.Empty); } set { Attributes["enctype"] = MapStringAttributeToString(value); } } /* * Method property. */ /// <devdoc> /// <para> /// Gets or sets the Method attribute for the form. This defines how a browser /// posts form data to the server for processing. The two common methods supported /// by all browsers are GET and POST. /// </para> /// </devdoc> [ WebCategory("Behavior"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string Method { get { string s = Attributes["method"]; return ((s != null) ? s : "post"); } set { Attributes["method"] = MapStringAttributeToString(value); } } /* * Name property. */ /// <devdoc> /// <para> /// Gets the value of the HTML Name attribute that will be rendered to the /// browser. /// </para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public virtual string Name { get { return UniqueID; } set { // no-op setter to prevent the name from being set } } /// <devdov> /// If true, forces controls disabled on the client to submit their values (thus preserving their previous postback state) /// </devdoc> [ WebCategory("Behavior"), DefaultValue(false) ] public virtual bool SubmitDisabledControls { get { return _submitDisabledControls; } set { _submitDisabledControls = value; } } /* * Target property. */ /// <devdoc> /// <para> /// Gets or sets the Uri of the frame or window to render the results of a Form /// POST request. Developers can use this property to redirect these results to /// another browser window or frame. /// </para> /// </devdoc> [ WebCategory("Behavior"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string Target { get { string s = Attributes["target"]; return ((s != null) ? s : String.Empty); } set { Attributes["target"] = MapStringAttributeToString(value); } } /// <devdoc> /// Overridden to return a constant value or tack the ID onto the same constant value. /// This fixes a bug in PocketPC which doesn't allow the name and ID of a form to be different /// </devdoc> public override string UniqueID { get { if (NamingContainer == Page) { return base.UniqueID; } else if (this.EffectiveClientIDMode != ClientIDMode.AutoID) { return ID ?? _aspnetFormID; } return _aspnetFormID; } } public override string ClientID { get { if (this.EffectiveClientIDMode != ClientIDMode.AutoID) { return ID; } return base.ClientID; } } protected internal override void Render(HtmlTextWriter output) { Page p = Page; if (p == null) throw new HttpException(SR.GetString(SR.Form_Needs_Page)); #pragma warning disable 0618 // To avoid deprecation warning if (p.SmartNavigation) { #pragma warning restore 0618 ((IAttributeAccessor)this).SetAttribute("__smartNavEnabled", "true"); // Output the IFrame StringBuilder sb = new StringBuilder("<IFRAME id=\"__hifSmartNav\" name=\"__hifSmartNav\" style=\"display:none\" src=\""); sb.Append(HttpEncoderUtility.UrlEncodeSpaces(HttpUtility.HtmlAttributeEncode(Page.ClientScript.GetWebResourceUrl(typeof(HtmlForm), "SmartNav.htm")))); sb.Append("\"></IFRAME>"); output.WriteLine(sb.ToString()); } base.Render(output); } private string GetActionAttribute() { // If the Action property is nonempty, we use it instead of the current page. This allows the developer // to support scenarios like PathInfo, UrlMapping, etc. (DevDiv Bugs 164390) string actionProperty = Action; if (!String.IsNullOrEmpty(actionProperty)) { return actionProperty; } string action; VirtualPath clientFilePath = Context.Request.ClientFilePath; // ASURT 15075/11054/59970: always set the action to the current page. // DevDiv Servicing 215795/Dev10 567580: The IIS URL Rewrite module and other rewrite // scenarios need the postback action to be the original URL. Note however, if Server.Transfer/Execute // is used, the action will be set to the transferred/executed page, that is, the value of // CurrentExecutionFilePathObject. This is because of ASURT 59970 and the document attached to // that bug, which indirectly states that things should behave this way when Transfer/Execute is used. if (Context.ServerExecuteDepth == 0) { // There hasn't been any Server.Transfer or RewritePath. // ASURT 15979: need to use a relative path, not absolute action = clientFilePath.VirtualPathString; int iPos = action.LastIndexOf('/'); if (iPos >= 0) { action = action.Substring(iPos + 1); } } else { VirtualPath currentFilePath = Context.Request.CurrentExecutionFilePathObject; // Server.Transfer or RewritePath case. We need to make the form action relative // to the original ClientFilePath (since that's where the browser thinks we are). currentFilePath = clientFilePath.MakeRelative(currentFilePath); action = currentFilePath.VirtualPathString; } // VSWhidbey 202380: If cookieless is on, we need to add the app path modifier to the form action bool cookieless = CookielessHelperClass.UseCookieless(Context, false, FormsAuthentication.CookieMode); if (cookieless && Context.Request != null && Context.Response != null) { action = Context.Response.ApplyAppPathModifier(action); } // Dev11 406986: <form> elements must have non-empty 'action' attributes to pass W3 validation. // The only time this might happen is that the current file path is "", which meant that the // incoming URL ended in a slash, so we can just point 'action' back to the current directory. if (String.IsNullOrEmpty(action) && RenderingCompatibility >= VersionUtil.Framework45) { action = "./"; } // Dev11 177096: The action may be empty if the RawUrl does not point to a file (for e.g. http://localhost:8080/) but is never null. // Empty action values work fine since the form does not emit the action attribute. Debug.Assert(action != null); string queryString = Page.ClientQueryString; // ASURT 15355: Don't lose the query string if there is one. // In scriptless mobile HTML, we prepend __EVENTTARGET, et. al. to the query string. These have to be // removed from the form action. Use new HttpValueCollection to leverage ToString(bool encoded). if (!String.IsNullOrEmpty(queryString)) { action += "?" + queryString; } return action; } /// <internalonly/> /// <devdoc> /// <para> Call RegisterViewStateHandler().</para> /// </devdoc> protected internal override void OnInit(EventArgs e) { base.OnInit(e); Page.SetForm(this); // Make sure view state is calculated (see ASURT 73020) Page.RegisterViewStateHandler(); } /// <devdoc> /// Overridden to handle focus stuff /// </devdoc> protected internal override void OnPreRender(EventArgs e) { base.OnPreRender(e); #pragma warning disable 0618 // To avoid deprecation warning if (Page.SmartNavigation) { #pragma warning restore 0618 // Register the smartnav script file reference so it gets rendered Page.ClientScript.RegisterClientScriptResource(typeof(HtmlForm), "SmartNav.js"); } } /// <internalonly/> /// <devdoc> /// </devdoc> protected override void RenderAttributes(HtmlTextWriter writer) { ArrayList invalidAttributes = new ArrayList(); foreach (String key in Attributes.Keys) { if (!writer.IsValidFormAttribute(key)) { invalidAttributes.Add(key); } } foreach (String key in invalidAttributes) { Attributes.Remove(key); } bool enableLegacyRendering = EnableLegacyRendering; Page page = Page; if (writer.IsValidFormAttribute("name")) { // DevDiv 27328 Do not render name attribute for uplevel browser if (page != null && page.RequestInternal != null && RenderingCompatibility < VersionUtil.Framework40 && (page.RequestInternal.Browser.W3CDomVersion.Major == 0 || page.XhtmlConformanceMode != XhtmlConformanceMode.Strict)) { writer.WriteAttribute("name", Name); } Attributes.Remove("name"); } writer.WriteAttribute("method", Method); Attributes.Remove("method"); // Encode the action attribute - ASURT 66784 writer.WriteAttribute("action", GetActionAttribute(), true /*encode*/); Attributes.Remove("action"); // see if the page has a submit event if (page != null) { string onSubmit = page.ClientOnSubmitEvent; if (!String.IsNullOrEmpty(onSubmit)) { if (Attributes["onsubmit"] != null) { // If there was an onsubmit on the form, register it as an onsubmit statement and remove it from the attribute collection string formOnSubmit = Attributes["onsubmit"]; if (formOnSubmit.Length > 0) { if (!StringUtil.StringEndsWith(formOnSubmit, ';')) { formOnSubmit += ";"; } if (page.ClientSupportsJavaScript || !formOnSubmit.ToLower(CultureInfo.CurrentCulture).Contains("javascript")) { page.ClientScript.RegisterOnSubmitStatement(typeof(HtmlForm), "OnSubmitScript", formOnSubmit); } Attributes.Remove("onsubmit"); } } // Don't render the on submit if it contains javascript and the page doesn't support it if (page.ClientSupportsJavaScript || !onSubmit.ToLower(CultureInfo.CurrentCulture).Contains("javascript")) { if (enableLegacyRendering) { writer.WriteAttribute("language", "javascript", false); } writer.WriteAttribute("onsubmit", onSubmit); } } if ((page.RequestInternal != null) && (page.RequestInternal.Browser.EcmaScriptVersion.Major > 0) && (page.RequestInternal.Browser.W3CDomVersion.Major > 0)) { if (DefaultButton.Length > 0) { // Find control from the page if it's a hierarchical ID. // Dev11 bug 19915 Control c = FindControlFromPageIfNecessary(DefaultButton); if (c is IButtonControl) { page.ClientScript.RegisterDefaultButtonScript(c, writer, false /* UseAddAttribute */); } else { throw new InvalidOperationException(SR.GetString(SR.HtmlForm_OnlyIButtonControlCanBeDefaultButton, ID)); } } } } // We always want the form to have an id on the client // base.RenderAttributes takes care of actually rendering it. EnsureID(); base.RenderAttributes(writer); } /// <internalonly/> /// <devdoc> /// </devdoc> protected internal override void RenderChildren(HtmlTextWriter writer) { // We need to register the script here since other controls might register // for focus during PreRender Page page = Page; if (page != null) { page.OnFormRender(); page.BeginFormRender(writer, UniqueID); } // DevDiv Bugs 154630: move custom hidden fields to the begining of the form HttpWriter httpWriter = writer.InnerWriter as HttpWriter; if (page != null && httpWriter != null && RuntimeConfig.GetConfig(Context).Pages.RenderAllHiddenFieldsAtTopOfForm) { // If the response is flushed or cleared during render, we won't be able // to move the hidden fields. Set HasBeenClearedRecently to false and // then check again when we're ready to move the fields. httpWriter.HasBeenClearedRecently = false; // Remember the index where the form begins int formBeginIndex = httpWriter.GetResponseBufferCountAfterFlush(); base.RenderChildren(writer); // Remember the index where the custom hidden fields begin int fieldsBeginIndex = httpWriter.GetResponseBufferCountAfterFlush(); page.EndFormRenderHiddenFields(writer, UniqueID); // we can only move the hidden fields if the response has not been flushed or cleared if (!httpWriter.HasBeenClearedRecently) { int fieldsEndIndex = httpWriter.GetResponseBufferCountAfterFlush(); httpWriter.MoveResponseBufferRangeForward(fieldsBeginIndex, fieldsEndIndex - fieldsBeginIndex, formBeginIndex); } page.EndFormRenderArrayAndExpandoAttribute(writer, UniqueID); page.EndFormRenderPostBackAndWebFormsScript(writer, UniqueID); page.OnFormPostRender(writer); } else { base.RenderChildren(writer); if (page != null) { page.EndFormRender(writer, UniqueID); page.OnFormPostRender(writer); } } } public override void RenderControl(HtmlTextWriter writer) { if (DesignMode) { // User Control Designer scenario base.RenderChildren(writer); } else { base.RenderControl(writer); } } protected override ControlCollection CreateControlCollection() { return new ControlCollection(this, 100, 2); } } }
using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.EntityFrameworkCore; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.EagerLoading { public sealed class EagerLoadingTests : IClassFixture<IntegrationTestContext<TestableStartup<EagerLoadingDbContext>, EagerLoadingDbContext>> { private readonly IntegrationTestContext<TestableStartup<EagerLoadingDbContext>, EagerLoadingDbContext> _testContext; private readonly EagerLoadingFakers _fakers = new(); public EagerLoadingTests(IntegrationTestContext<TestableStartup<EagerLoadingDbContext>, EagerLoadingDbContext> testContext) { _testContext = testContext; testContext.UseController<StreetsController>(); testContext.UseController<StatesController>(); testContext.UseController<BuildingsController>(); testContext.ConfigureServicesAfterStartup(services => { services.AddResourceRepository<BuildingRepository>(); }); } [Fact] public async Task Can_get_primary_resource_with_eager_loads() { // Arrange Building building = _fakers.Building.Generate(); building.Windows = _fakers.Window.Generate(4); building.PrimaryDoor = _fakers.Door.Generate(); building.SecondaryDoor = _fakers.Door.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Buildings.Add(building); await dbContext.SaveChangesAsync(); }); string route = $"/buildings/{building.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(building.StringId); responseDocument.Data.SingleValue.Attributes["number"].Should().Be(building.Number); responseDocument.Data.SingleValue.Attributes["windowCount"].Should().Be(4); responseDocument.Data.SingleValue.Attributes["primaryDoorColor"].Should().Be(building.PrimaryDoor.Color); responseDocument.Data.SingleValue.Attributes["secondaryDoorColor"].Should().Be(building.SecondaryDoor.Color); } [Fact] public async Task Can_get_primary_resource_with_nested_eager_loads() { // Arrange Street street = _fakers.Street.Generate(); street.Buildings = _fakers.Building.Generate(2); street.Buildings[0].Windows = _fakers.Window.Generate(2); street.Buildings[0].PrimaryDoor = _fakers.Door.Generate(); street.Buildings[1].Windows = _fakers.Window.Generate(3); street.Buildings[1].PrimaryDoor = _fakers.Door.Generate(); street.Buildings[1].SecondaryDoor = _fakers.Door.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Streets.Add(street); await dbContext.SaveChangesAsync(); }); string route = $"/streets/{street.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(street.StringId); responseDocument.Data.SingleValue.Attributes["name"].Should().Be(street.Name); responseDocument.Data.SingleValue.Attributes["buildingCount"].Should().Be(2); responseDocument.Data.SingleValue.Attributes["doorTotalCount"].Should().Be(3); responseDocument.Data.SingleValue.Attributes["windowTotalCount"].Should().Be(5); } [Fact] public async Task Can_get_primary_resource_with_fieldset() { // Arrange Street street = _fakers.Street.Generate(); street.Buildings = _fakers.Building.Generate(1); street.Buildings[0].Windows = _fakers.Window.Generate(3); street.Buildings[0].PrimaryDoor = _fakers.Door.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Streets.Add(street); await dbContext.SaveChangesAsync(); }); string route = $"/streets/{street.StringId}?fields[streets]=windowTotalCount"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(street.StringId); responseDocument.Data.SingleValue.Attributes.Should().HaveCount(1); responseDocument.Data.SingleValue.Attributes["windowTotalCount"].Should().Be(3); responseDocument.Data.SingleValue.Relationships.Should().BeNull(); } [Fact] public async Task Can_get_primary_resource_with_includes() { // Arrange State state = _fakers.State.Generate(); state.Cities = _fakers.City.Generate(1); state.Cities[0].Streets = _fakers.Street.Generate(1); state.Cities[0].Streets[0].Buildings = _fakers.Building.Generate(1); state.Cities[0].Streets[0].Buildings[0].PrimaryDoor = _fakers.Door.Generate(); state.Cities[0].Streets[0].Buildings[0].Windows = _fakers.Window.Generate(3); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.States.Add(state); await dbContext.SaveChangesAsync(); }); string route = $"/states/{state.StringId}?include=cities.streets"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(state.StringId); responseDocument.Data.SingleValue.Attributes["name"].Should().Be(state.Name); responseDocument.Included.Should().HaveCount(2); responseDocument.Included[0].Type.Should().Be("cities"); responseDocument.Included[0].Id.Should().Be(state.Cities[0].StringId); responseDocument.Included[0].Attributes["name"].Should().Be(state.Cities[0].Name); responseDocument.Included[1].Type.Should().Be("streets"); responseDocument.Included[1].Id.Should().Be(state.Cities[0].Streets[0].StringId); responseDocument.Included[1].Attributes["buildingCount"].Should().Be(1); responseDocument.Included[1].Attributes["doorTotalCount"].Should().Be(1); responseDocument.Included[1].Attributes["windowTotalCount"].Should().Be(3); } [Fact] public async Task Can_get_secondary_resources_with_include_and_fieldsets() { // Arrange State state = _fakers.State.Generate(); state.Cities = _fakers.City.Generate(1); state.Cities[0].Streets = _fakers.Street.Generate(1); state.Cities[0].Streets[0].Buildings = _fakers.Building.Generate(1); state.Cities[0].Streets[0].Buildings[0].PrimaryDoor = _fakers.Door.Generate(); state.Cities[0].Streets[0].Buildings[0].SecondaryDoor = _fakers.Door.Generate(); state.Cities[0].Streets[0].Buildings[0].Windows = _fakers.Window.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.States.Add(state); await dbContext.SaveChangesAsync(); }); string route = $"/states/{state.StringId}/cities?include=streets&fields[cities]=name&fields[streets]=doorTotalCount,windowTotalCount"; // 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(state.Cities[0].StringId); responseDocument.Data.ManyValue[0].Attributes.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Attributes["name"].Should().Be(state.Cities[0].Name); responseDocument.Data.ManyValue[0].Relationships.Should().BeNull(); responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Type.Should().Be("streets"); responseDocument.Included[0].Id.Should().Be(state.Cities[0].Streets[0].StringId); responseDocument.Included[0].Attributes.Should().HaveCount(2); responseDocument.Included[0].Attributes["doorTotalCount"].Should().Be(2); responseDocument.Included[0].Attributes["windowTotalCount"].Should().Be(1); responseDocument.Included[0].Relationships.Should().BeNull(); } [Fact] public async Task Can_create_resource() { // Arrange Building newBuilding = _fakers.Building.Generate(); var requestBody = new { data = new { type = "buildings", attributes = new { number = newBuilding.Number } } }; const string route = "/buildings"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Attributes["number"].Should().Be(newBuilding.Number); responseDocument.Data.SingleValue.Attributes["windowCount"].Should().Be(0); responseDocument.Data.SingleValue.Attributes["primaryDoorColor"].Should().BeNull(); responseDocument.Data.SingleValue.Attributes["secondaryDoorColor"].Should().BeNull(); int newBuildingId = int.Parse(responseDocument.Data.SingleValue.Id); await _testContext.RunOnDatabaseAsync(async dbContext => { // @formatter:wrap_chained_method_calls chop_always // @formatter:keep_existing_linebreaks true Building buildingInDatabase = await dbContext.Buildings .Include(building => building.PrimaryDoor) .Include(building => building.SecondaryDoor) .Include(building => building.Windows) .FirstWithIdOrDefaultAsync(newBuildingId); // @formatter:keep_existing_linebreaks restore // @formatter:wrap_chained_method_calls restore buildingInDatabase.Should().NotBeNull(); buildingInDatabase.Number.Should().Be(newBuilding.Number); buildingInDatabase.PrimaryDoor.Should().NotBeNull(); buildingInDatabase.SecondaryDoor.Should().BeNull(); buildingInDatabase.Windows.Should().BeEmpty(); }); } [Fact] public async Task Can_update_resource() { // Arrange Building existingBuilding = _fakers.Building.Generate(); existingBuilding.PrimaryDoor = _fakers.Door.Generate(); existingBuilding.SecondaryDoor = _fakers.Door.Generate(); existingBuilding.Windows = _fakers.Window.Generate(2); string newBuildingNumber = _fakers.Building.Generate().Number; string newPrimaryDoorColor = _fakers.Door.Generate().Color; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Buildings.Add(existingBuilding); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "buildings", id = existingBuilding.StringId, attributes = new { number = newBuildingNumber, primaryDoorColor = newPrimaryDoorColor } } }; string route = $"/buildings/{existingBuilding.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { // @formatter:wrap_chained_method_calls chop_always // @formatter:keep_existing_linebreaks true Building buildingInDatabase = await dbContext.Buildings .Include(building => building.PrimaryDoor) .Include(building => building.SecondaryDoor) .Include(building => building.Windows) .FirstWithIdOrDefaultAsync(existingBuilding.Id); // @formatter:keep_existing_linebreaks restore // @formatter:wrap_chained_method_calls restore buildingInDatabase.Should().NotBeNull(); buildingInDatabase.Number.Should().Be(newBuildingNumber); buildingInDatabase.PrimaryDoor.Should().NotBeNull(); buildingInDatabase.PrimaryDoor.Color.Should().Be(newPrimaryDoorColor); buildingInDatabase.SecondaryDoor.Should().NotBeNull(); buildingInDatabase.Windows.Should().HaveCount(2); }); } [Fact] public async Task Can_delete_resource() { // Arrange Building existingBuilding = _fakers.Building.Generate(); existingBuilding.PrimaryDoor = _fakers.Door.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Buildings.Add(existingBuilding); await dbContext.SaveChangesAsync(); }); string route = $"/buildings/{existingBuilding.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 => { Building buildingInDatabase = await dbContext.Buildings.FirstWithIdOrDefaultAsync(existingBuilding.Id); buildingInDatabase.Should().BeNull(); }); } } }
// 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.IO; using System.Net.Test.Common; using System.Threading; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class SendPacketsAsync { private readonly ITestOutputHelper _log; private IPAddress _serverAddress = IPAddress.IPv6Loopback; // In the current directory private const string TestFileName = "NCLTest.Socket.SendPacketsAsync.testpayload"; private static int s_testFileSize = 1024; #region Additional test attributes public SendPacketsAsync(ITestOutputHelper output) { _log = TestLogging.GetInstance(); byte[] buffer = new byte[s_testFileSize]; for (int i = 0; i < s_testFileSize; i++) { buffer[i] = (byte)(i % 255); } try { _log.WriteLine("Creating file {0} with size: {1}", TestFileName, s_testFileSize); using (FileStream fs = new FileStream(TestFileName, FileMode.CreateNew)) { fs.Write(buffer, 0, buffer.Length); } } catch (IOException) { // Test payload file already exists. _log.WriteLine("Payload file exists: {0}", TestFileName); } } #endregion Additional test attributes #region Basic Arguments [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void Disposed_Throw(SocketImplementationType type) { int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); sock.Dispose(); Assert.Throws<ObjectDisposedException>(() => { sock.SendPacketsAsync(new SocketAsyncEventArgs()); }); } } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null SAEA argument")] [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NullArgs_Throw(SocketImplementationType type) { int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => { sock.SendPacketsAsync(null); }); Assert.Equal("e", ex.ParamName); } } } [Fact] public void NotConnected_Throw() { Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); // Needs to be connected before send Assert.Throws<NotSupportedException>(() => { socket.SendPacketsAsync(new SocketAsyncEventArgs { SendPacketsElements = new SendPacketsElement[0] }); }); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null m_SendPacketsElementsInternal array")] [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NullList_Throws(SocketImplementationType type) { ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => { SendPackets(type, (SendPacketsElement[])null, SocketError.Success, 0); }); Assert.Equal("e.SendPacketsElements", ex.ParamName); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NullElement_Ignored(SocketImplementationType type) { SendPackets(type, (SendPacketsElement)null, 0); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void EmptyList_Ignored(SocketImplementationType type) { SendPackets(type, new SendPacketsElement[0], SocketError.Success, 0); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SocketAsyncEventArgs_DefaultSendSize_0() { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); Assert.Equal(0, args.SendPacketsSendSize); } #endregion Basic Arguments #region Buffers [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NormalBuffer_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10]), 10); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NormalBufferRange_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 5, 5), 5); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void EmptyBuffer_Ignored(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[0]), 0); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void BufferZeroCount_Ignored(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 4, 0), 0); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void BufferMixedBuffers_ZeroCountBufferIgnored(SocketImplementationType type) { SendPacketsElement[] elements = new SendPacketsElement[] { new SendPacketsElement(new byte[10], 4, 0), // Ignored new SendPacketsElement(new byte[10], 4, 4), new SendPacketsElement(new byte[10], 0, 4) }; SendPackets(type, elements, SocketError.Success, 8); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void BufferZeroCountThenNormal_ZeroCountIgnored(SocketImplementationType type) { Assert.True(Capability.IPv6Support()); EventWaitHandle completed = new ManualResetEvent(false); int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); using (SocketAsyncEventArgs args = new SocketAsyncEventArgs()) { args.Completed += OnCompleted; args.UserToken = completed; // First do an empty send, ignored args.SendPacketsElements = new SendPacketsElement[] { new SendPacketsElement(new byte[5], 3, 0) }; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Equal(0, args.BytesTransferred); completed.Reset(); // Now do a real send args.SendPacketsElements = new SendPacketsElement[] { new SendPacketsElement(new byte[5], 1, 4) }; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Equal(4, args.BytesTransferred); } } } } #endregion Buffers #region TransmitFileOptions [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SocketDisconnected_TransmitFileOptionDisconnect(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect, 4); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SocketDisconnectedAndReusable_TransmitFileOptionReuseSocket(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket, 4); } #endregion #region Files [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_EmptyFileName_Throws(SocketImplementationType type) { Assert.Throws<ArgumentException>(() => { SendPackets(type, new SendPacketsElement(String.Empty), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // whitespace-only is a valid name on Unix public void SendPacketsElement_BlankFileName_Throws(SocketImplementationType type) { Assert.Throws<ArgumentException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement(" \t "), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // valid filename chars on Unix public void SendPacketsElement_BadCharactersFileName_Throws(SocketImplementationType type) { Assert.Throws<ArgumentException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement("blarkd@dfa?/sqersf"), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_MissingDirectoryName_Throws(SocketImplementationType type) { Assert.Throws<DirectoryNotFoundException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement(Path.Combine("nodir", "nofile")), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_MissingFile_Throws(SocketImplementationType type) { Assert.Throws<FileNotFoundException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement("DoesntExit"), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_File_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(TestFileName), s_testFileSize); // Whole File } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FileZeroCount_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(TestFileName, 0, 0), s_testFileSize); // Whole File } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FilePart_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(TestFileName, 10, 20), 20); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FileMultiPart_Success(SocketImplementationType type) { SendPacketsElement[] elements = new SendPacketsElement[] { new SendPacketsElement(TestFileName, 10, 20), new SendPacketsElement(TestFileName, 30, 10), new SendPacketsElement(TestFileName, 0, 10), }; SendPackets(type, elements, SocketError.Success, 40); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FileLargeOffset_Throws(SocketImplementationType type) { // Length is validated on Send SendPackets(type, new SendPacketsElement(TestFileName, 11000, 1), SocketError.InvalidArgument, 0); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FileLargeCount_Throws(SocketImplementationType type) { // Length is validated on Send SendPackets(type, new SendPacketsElement(TestFileName, 5, 10000), SocketError.InvalidArgument, 0); } #endregion Files #region Helpers private void SendPackets(SocketImplementationType type, SendPacketsElement element, TransmitFileOptions flags, int bytesExpected) { Assert.True(Capability.IPv6Support()); EventWaitHandle completed = new ManualResetEvent(false); int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); using (SocketAsyncEventArgs args = new SocketAsyncEventArgs()) { args.Completed += OnCompleted; args.UserToken = completed; args.SendPacketsElements = new[] { element }; args.SendPacketsFlags = flags; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Equal(bytesExpected, args.BytesTransferred); } switch (flags) { case TransmitFileOptions.Disconnect: // Sending data again throws with socket shut down error. Assert.Throws<SocketException>(() => { sock.Send(new byte[1] { 01 }); }); break; case TransmitFileOptions.ReuseSocket & TransmitFileOptions.Disconnect: // Able to send data again with reuse socket flag set. Assert.Equal(1, sock.Send(new byte[1] { 01 })); break; } } } } private void SendPackets(SocketImplementationType type, SendPacketsElement element, int bytesExpected) { SendPackets(type, new SendPacketsElement[] { element }, SocketError.Success, bytesExpected); } private void SendPackets(SocketImplementationType type, SendPacketsElement element, SocketError expectedResut, int bytesExpected) { SendPackets(type, new SendPacketsElement[] { element }, expectedResut, bytesExpected); } private void SendPackets(SocketImplementationType type, SendPacketsElement[] elements, SocketError expectedResut, int bytesExpected) { Assert.True(Capability.IPv6Support()); EventWaitHandle completed = new ManualResetEvent(false); int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); using (SocketAsyncEventArgs args = new SocketAsyncEventArgs()) { args.Completed += OnCompleted; args.UserToken = completed; args.SendPacketsElements = elements; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(expectedResut, args.SocketError); Assert.Equal(bytesExpected, args.BytesTransferred); } } } } private void OnCompleted(object sender, SocketAsyncEventArgs e) { EventWaitHandle handle = (EventWaitHandle)e.UserToken; handle.Set(); } #endregion Helpers } }
//---------------------------------------------------------------------------- // <copyright file="MirrorController.cs" company="Delft University of Technology"> // Copyright 2015, Delft University of Technology // // This software is licensed under the terms of the MIT License. // A copy of the license should be included with this software. If not, // see http://opensource.org/licenses/MIT for the full license. // </copyright> //---------------------------------------------------------------------------- namespace Core { using System; using System.Diagnostics.CodeAnalysis; using Core.Receiver; using Network; using Projection; using UnityEngine; using UnityEngine.Assertions; /// <summary> /// Provides selection and rotation functionality to Mirrors. /// </summary> public class MirrorController : MonoBehaviour { /// <summary> /// The Highlighted Material of the Mirror. /// </summary> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Unity Property")] public Material Highlight; /// <summary> /// The original Material of the Mirror. /// </summary> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Unity Property")] public Material Original; /// <summary> /// The selected Mirror. /// </summary> private Mirror selected; /// <summary> /// Current rotation speed of mirror. /// </summary> private float rotationSpeed = 0.0f; /// <summary> /// Gets or sets the selected Mirror. /// </summary> public Mirror SelectedMirror { get { return this.selected; } set { if (this.selected != value) { this.ResetHighlight(this.selected); this.selected = value; this.HighlightMirror(this.selected); } } } /// <summary> /// Updates the selected Mirror if the 'M' key is pressed and updates the /// rotation of the selected Mirror. /// </summary> public void Update() { if (Input.GetKeyDown(KeyCode.M)) { this.UpdateSelectedMirror(); } this.Rotate(); if (Input.GetMouseButtonDown(0)) { RaycastHit hitInfo; bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo); if (hit) { // Find closest mirror to point Mirror[] mirrors = GameObject.FindObjectsOfType<Mirror>(); float closestDistance = float.PositiveInfinity; Mirror closestMirror = null; foreach (Mirror mirror in mirrors) { float d = (hitInfo.point - mirror.transform.position).magnitude; if (d < closestDistance) { closestDistance = d; closestMirror = mirror; } } this.SelectedMirror = closestMirror; } else { this.SelectedMirror = null; } } } /// <summary> /// Sends a message with the current rotation of the selected mirror. /// <para> /// The selected mirror should not be null. /// </para> /// </summary> public void SendRotationUpdate() { Assert.IsNotNull(this.SelectedMirror, "SendRotationUpdate: No Mirror Selected"); RemoteMarker marker = this.SelectedMirror.GetComponent<RemoteMarker>(); float rotation = marker.ObjectRotation; RotationUpdate update = new RotationUpdate(UpdateType.UpdateRotation, rotation, marker.Id); this.SendMessage("OnRotationChanged", update); this.SendMessage("OnRotationUpdate", update); } /// <summary> /// Changes the selected Mirror to the next Mirror in sequence. /// </summary> private void UpdateSelectedMirror() { Mirror[] mirrors = GameObject.FindObjectsOfType<Mirror>(); if (mirrors.Length == 0) { this.SelectedMirror = null; return; } // We need the Mirror at 'index + 2' because: // 'index' is the current mirror. // 'index + 1' is the other side of the same mirror. // 'index + 2' if the first side of the next mirror. int index = Array.IndexOf(mirrors, this.SelectedMirror); if (index + 2 >= mirrors.Length) { this.SelectedMirror = mirrors[0]; } else { this.SelectedMirror = mirrors[index + 2]; } } /// <summary> /// Rotates the mirror corresponding with whether the left or right arrow key, /// or the left or right mouse button is pressed. /// </summary> private void Rotate() { if (this.SelectedMirror != null) { if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.Mouse1) || Input.GetKeyDown(KeyCode.Mouse0) || Input.GetKeyDown(KeyCode.RightArrow)) { this.rotationSpeed = 0.0f; } if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.Mouse0)) { float t = Time.deltaTime * -this.rotationSpeed; this.rotationSpeed = Mathf.Min(90f, this.rotationSpeed + (Time.deltaTime * 45.0f)); this.SelectedMirror.GetComponent<RemoteMarker>().ObjectRotation += t; this.SendRotationUpdate(); } else if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.Mouse1)) { float t = Time.deltaTime * this.rotationSpeed; this.rotationSpeed = Mathf.Min(90.0f, this.rotationSpeed + (Time.deltaTime * 45.0f)); this.SelectedMirror.GetComponent<RemoteMarker>().ObjectRotation += t; this.SendRotationUpdate(); } } } /// <summary> /// Highlights the mirror. /// </summary> /// <param name="mirror">The Mirror to highlight.</param> private void HighlightMirror(Mirror mirror) { if (mirror != null) { Transform frame = mirror.transform.Find("Frame"); MeshRenderer mesh = frame.GetComponent<MeshRenderer>(); mesh.material = this.Highlight; } } /// <summary> /// Resets the Highlight. /// </summary> /// <param name="mirror">The Mirror to reset.</param> private void ResetHighlight(Mirror mirror) { if (mirror != null) { Transform frame = mirror.transform.Find("Frame"); MeshRenderer mesh = frame.GetComponent<MeshRenderer>(); mesh.material = this.Original; } } } }
// Copyright (c) Russlan Akiev. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace IdentityBase.Actions.Consent { using System.Linq; using System.Threading.Tasks; using IdentityServer4; using IdentityServer4.Models; using IdentityServer4.Services; using IdentityServer4.Stores; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; public class ConsentController : WebController { private readonly ILogger<ConsentController> _logger; private readonly IClientStore _clientStore; private readonly IIdentityServerInteractionService _interaction; private readonly IResourceStore _resourceStore; public ConsentController( ILogger<ConsentController> logger, IIdentityServerInteractionService interaction, IClientStore clientStore, IResourceStore resourceStore) { this._logger = logger; this._interaction = interaction; this._clientStore = clientStore; this._resourceStore = resourceStore; } [HttpGet("consent", Name = "Consent")] public async Task<IActionResult> Index(string returnUrl) { ConsentViewModel vm = await this.BuildViewModelAsync(returnUrl); if (vm != null) { return this.View("Index", vm); } return this.View("Error"); } [HttpPost("consent", Name = "Consent")] [ValidateAntiForgeryToken] public async Task<IActionResult> Index( string button, ConsentInputModel model) { AuthorizationRequest request = await this._interaction .GetAuthorizationContextAsync(model.ReturnUrl); ConsentResponse response = null; if (button == "no") { response = ConsentResponse.Denied; } else if (button == "yes" && model != null) { if (model.ScopesConsented != null && model.ScopesConsented.Any()) { response = new ConsentResponse { RememberConsent = model.RememberConsent, ScopesConsented = model.ScopesConsented }; } else { this.ModelState.AddModelError( "You must pick at least one permission."); } } else { this.ModelState.AddModelError("Invalid Selection"); } if (response != null) { await this._interaction.GrantConsentAsync(request, response); return this.Redirect(model.ReturnUrl); } ConsentViewModel vm = await this.BuildViewModelAsync(model.ReturnUrl, model); if (vm != null) { return this.View("Index", vm); } return this.View("Error"); } [NonAction] private async Task<ConsentViewModel> BuildViewModelAsync( string returnUrl, ConsentInputModel model = null) { AuthorizationRequest request = await this._interaction .GetAuthorizationContextAsync(returnUrl); if (request != null) { Client client = await this._clientStore .FindEnabledClientByIdAsync(request.ClientId); if (client != null) { Resources resources = await this._resourceStore .FindEnabledResourcesByScopeAsync( request.ScopesRequested); if (resources != null && (resources.IdentityResources.Any() || resources.ApiResources.Any())) { return this.CreateConsentViewModel(model, returnUrl, request, client, resources); } else { this._logger.LogError( "No scopes matching: {0}", request.ScopesRequested .Aggregate((x, y) => x + ", " + y)); } } else { this._logger.LogError( "Invalid client id: {0}", request.ClientId); } } else { this._logger.LogError( "No consent request matching request: {0}", returnUrl); } return null; } [NonAction] private ConsentViewModel CreateConsentViewModel( ConsentInputModel model, string returnUrl, AuthorizationRequest request, Client client, Resources resources) { ConsentViewModel vm = new ConsentViewModel() { RememberConsent = model?.RememberConsent ?? true, ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(), ReturnUrl = returnUrl, ClientName = client.ClientName, ClientUrl = client.ClientUri, ClientLogoUrl = client.LogoUri, AllowRememberConsent = client.AllowRememberConsent }; vm.IdentityScopes = resources.IdentityResources .Select(x => CreateScopeViewModel(x, vm.ScopesConsented .Contains(x.Name) || model == null)) .ToArray(); vm.ResourceScopes = resources.ApiResources .SelectMany(x => x.Scopes) .Select(x => CreateScopeViewModel(x, vm.ScopesConsented .Contains(x.Name) || model == null)) .ToArray(); // TODO: make use of application settings if (resources.OfflineAccess) { vm.ResourceScopes = vm.ResourceScopes .Union(new ScopeViewModel[] { this.GetOfflineAccessScope(vm.ScopesConsented.Contains( IdentityServerConstants.StandardScopes.OfflineAccess) || model == null ) }); // You must prompt for consent every time offline_access is requested. // https://github.com/IdentityServer/IdentityServer3/issues/2057 vm.AllowRememberConsent = false; } return vm; } [NonAction] private ScopeViewModel CreateScopeViewModel( IdentityResource identity, bool check) { return new ScopeViewModel { Name = identity.Name, DisplayName = identity.DisplayName, Description = identity.Description, Emphasize = identity.Emphasize, Required = identity.Required, Checked = check || identity.Required, }; } [NonAction] private ScopeViewModel CreateScopeViewModel(Scope scope, bool check) { return new ScopeViewModel { Name = scope.Name, DisplayName = scope.DisplayName, Description = scope.Description, Emphasize = scope.Emphasize, Required = scope.Required, Checked = check || scope.Required, }; } [NonAction] private ScopeViewModel GetOfflineAccessScope(bool check) { return new ScopeViewModel { Name = IdentityServerConstants.StandardScopes.OfflineAccess, DisplayName = "Offline Access", Description = "Access to your applications and resources, even when you are offline", Emphasize = true, Checked = check }; } } }
/* * 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.Binary.Serializable { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Serialization; using System.Xml; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using NUnit.Framework; /// <summary> /// Tests additional [Serializable] scenarios. /// </summary> public class AdvancedSerializationTest { /// <summary> /// Set up routine. /// </summary> [TestFixtureSetUp] public void SetUp() { Ignition.Start(TestUtils.GetTestConfiguration()); } /// <summary> /// Tear down routine. /// </summary> [TestFixtureTearDown] public void TearDown() { Ignition.StopAll(true); } /// <summary> /// Test complex file serialization. /// </summary> [Test] public void TestSerializableXmlDoc() { var grid = Ignition.GetIgnite(null); var cache = grid.GetOrCreateCache<int, SerializableXmlDoc>("cache"); var doc = new SerializableXmlDoc(); doc.LoadXml("<document><test1>val</test1><test2 attr=\"x\" /></document>"); for (var i = 0; i < 50; i++) { // Test cache cache.Put(i, doc); var resultDoc = cache.Get(i); Assert.AreEqual(doc.OuterXml, resultDoc.OuterXml); // Test task with document arg CheckTask(grid, doc); } } /// <summary> /// Checks task execution. /// </summary> /// <param name="grid">Grid.</param> /// <param name="arg">Task arg.</param> private static void CheckTask(IIgnite grid, object arg) { var jobResult = grid.GetCompute().Execute(new CombineStringsTask(), arg); var nodeCount = grid.GetCluster().GetNodes().Count; var expectedRes = CombineStringsTask.CombineStrings(Enumerable.Range(0, nodeCount).Select(x => arg.ToString())); Assert.AreEqual(expectedRes, jobResult.InnerXml); } /// <summary> /// Tests custom serialization binder. /// </summary> [Test] public void TestSerializationBinder() { const int count = 50; var cache = Ignition.GetIgnite(null).GetOrCreateCache<int, object>("cache"); // Put multiple objects from multiple same-named assemblies to cache for (var i = 0; i < count; i++) { dynamic val = Activator.CreateInstance(GenerateDynamicType()); val.Id = i; val.Name = "Name_" + i; cache.Put(i, val); } // Verify correct deserialization for (var i = 0; i < count; i++) { dynamic val = cache.Get(i); Assert.AreEqual(val.Id, i); Assert.AreEqual(val.Name, "Name_" + i); } } /// <summary> /// Generates a Type in runtime, puts it into a dynamic assembly. /// </summary> /// <returns></returns> private static Type GenerateDynamicType() { var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName("GridSerializationTestDynamicAssembly"), AssemblyBuilderAccess.Run); var moduleBuilder = asmBuilder.DefineDynamicModule("GridSerializationTestDynamicModule"); var typeBuilder = moduleBuilder.DefineType("GridSerializationTestDynamicType", TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Serializable); typeBuilder.DefineField("Id", typeof (int), FieldAttributes.Public); typeBuilder.DefineField("Name", typeof (string), FieldAttributes.Public); return typeBuilder.CreateType(); } } [Serializable] [DataContract] public sealed class SerializableXmlDoc : XmlDocument, ISerializable { /// <summary> /// Default ctor. /// </summary> public SerializableXmlDoc() { // No-op } /// <summary> /// Serialization ctor. /// </summary> private SerializableXmlDoc(SerializationInfo info, StreamingContext context) { LoadXml(info.GetString("xmlDocument")); } /** <inheritdoc /> */ public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("xmlDocument", OuterXml, typeof(string)); } } [Serializable] public class CombineStringsTask : IComputeTask<object, string, SerializableXmlDoc> { public IDictionary<IComputeJob<string>, IClusterNode> Map(IList<IClusterNode> subgrid, object arg) { return subgrid.ToDictionary(x => (IComputeJob<string>) new ToStringJob {Arg = arg}, x => x); } public ComputeJobResultPolicy OnResult(IComputeJobResult<string> res, IList<IComputeJobResult<string>> rcvd) { return ComputeJobResultPolicy.Wait; } public SerializableXmlDoc Reduce(IList<IComputeJobResult<string>> results) { var result = new SerializableXmlDoc(); result.LoadXml(CombineStrings(results.Select(x => x.Data))); return result; } public static string CombineStrings(IEnumerable<string> strings) { var text = string.Concat(strings.Select(x => string.Format("<val>{0}</val>", x))); return string.Format("<document>{0}</document>", text); } } [Serializable] public class ToStringJob : IComputeJob<string> { /// <summary> /// Job argument. /// </summary> public object Arg { get; set; } /** <inheritdoc /> */ public string Execute() { return Arg.ToString(); } /** <inheritdoc /> */ public void Cancel() { // No-op. } } }
namespace Macabresoft.Macabre2D.UI.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using Macabresoft.AvaloniaEx; using Macabresoft.Macabre2D.Framework; using ReactiveUI; /// <summary> /// Interface for a service which handles the <see cref="IScene" /> open in the editor. /// </summary> public interface ISceneService : ISelectionService<object> { /// <summary> /// Gets the current scene. /// </summary> /// <value>The current scene.</value> IScene CurrentScene { get; } /// <summary> /// Gets the current scene metadata. /// </summary> ContentMetadata CurrentSceneMetadata { get; } /// <summary> /// Gets the implied selected object. /// </summary> object ImpliedSelected { get; } /// <summary> /// Gets a value indicating whether or not the state of the program is in an entity context. /// </summary> bool IsEntityContext { get; } /// <summary> /// Saves the current scene. /// </summary> void SaveScene(); /// <summary> /// Saves the provided scene and metadata. /// </summary> void SaveScene(ContentMetadata metadata, IScene scene); /// <summary> /// Tries to load a scene. /// </summary> /// <param name="contentId">The content identifier of the scene.</param> /// <param name="sceneAsset">The scene asset.</param> /// <returns>A value indicating whether or not the scene was loaded.</returns> bool TryLoadScene(Guid contentId, out SceneAsset sceneAsset); } /// <summary> /// A service which handles the <see cref="IScene" /> open in the editor. /// </summary> public sealed class SceneService : ReactiveObject, ISceneService { private readonly IEntityService _entityService; private readonly IFileSystemService _fileSystem; private readonly IPathService _pathService; private readonly ISerializer _serializer; private readonly IEditorSettingsService _settingsService; private readonly ISystemService _systemService; private ContentMetadata _currentSceneMetadata; private object _impliedSelected; private bool _isEntityContext; private object _selected; /// <summary> /// Initializes a new instance of the <see cref="SceneService" /> class. /// </summary> /// <param name="entityService">The entity service.</param> /// <param name="fileSystem">The file system service.</param> /// <param name="pathService">The path service.</param> /// <param name="serializer">The serializer.</param> /// <param name="settingsService">The settings service.</param> /// <param name="systemService">The system service.</param> public SceneService( IEntityService entityService, IFileSystemService fileSystem, IPathService pathService, ISerializer serializer, IEditorSettingsService settingsService, ISystemService systemService) { this._entityService = entityService; this._fileSystem = fileSystem; this._pathService = pathService; this._serializer = serializer; this._settingsService = settingsService; this._systemService = systemService; } /// <inheritdoc /> public IScene CurrentScene => (this._currentSceneMetadata?.Asset as SceneAsset)?.Content; /// <inheritdoc /> public IReadOnlyCollection<ValueControlCollection> Editors { get { return this._selected switch { IEntity => this._entityService.Editors, IUpdateableSystem => this._systemService.Editors, _ => null }; } } /// <inheritdoc /> public ContentMetadata CurrentSceneMetadata { get => this._currentSceneMetadata; private set { this.RaiseAndSetIfChanged(ref this._currentSceneMetadata, value); this.RaisePropertyChanged(nameof(this.CurrentScene)); } } /// <inheritdoc /> public object ImpliedSelected { get => this._impliedSelected; private set => this.RaiseAndSetIfChanged(ref this._impliedSelected, value); } /// <inheritdoc /> public bool IsEntityContext { get => this._isEntityContext; private set => this.RaiseAndSetIfChanged(ref this._isEntityContext, value); } /// <inheritdoc /> public object Selected { get => this._selected; set { this.RaiseAndSetIfChanged(ref this._selected, value); this._entityService.Selected = null; this._systemService.Selected = null; this.IsEntityContext = false; switch (this._selected) { case IScene scene: this._entityService.Selected = scene; this.ImpliedSelected = this._selected; break; case IUpdateableSystem system: this._systemService.Selected = system; this.ImpliedSelected = this._selected; break; case IEntity entity: this._entityService.Selected = entity; this.ImpliedSelected = this._selected; this.IsEntityContext = true; break; case SystemCollection: this._entityService.Selected = this.CurrentScene; this.ImpliedSelected = this.CurrentScene; break; case EntityCollection: this.IsEntityContext = true; this._entityService.Selected = this.CurrentScene; this.ImpliedSelected = this.CurrentScene; break; } this.RaisePropertyChanged(nameof(this.Editors)); } } /// <inheritdoc /> public void SaveScene() { this.SaveScene(this.CurrentSceneMetadata, this.CurrentScene); } /// <inheritdoc /> public void SaveScene(ContentMetadata metadata, IScene scene) { if (metadata != null && scene != null && metadata.Asset is IAsset<Scene>) { var metadataPath = this._pathService.GetMetadataFilePath(metadata.ContentId); this._serializer.Serialize(metadata, metadataPath); var filePath = Path.Combine(this._pathService.ContentDirectoryPath, metadata.GetContentPath()); this._serializer.Serialize(scene, filePath); } } /// <inheritdoc /> public bool TryLoadScene(Guid contentId, out SceneAsset sceneAsset) { if (contentId == Guid.Empty) { sceneAsset = null; } else { var metadataFilePath = this._pathService.GetMetadataFilePath(contentId); if (this._fileSystem.DoesFileExist(metadataFilePath)) { var metadata = this._serializer.Deserialize<ContentMetadata>(metadataFilePath); sceneAsset = metadata?.Asset as SceneAsset; if (metadata != null && sceneAsset != null) { var contentPath = Path.Combine(this._pathService.ContentDirectoryPath, metadata.GetContentPath()); if (this._fileSystem.DoesFileExist(contentPath)) { var scene = this._serializer.Deserialize<Scene>(contentPath); if (scene != null) { sceneAsset.LoadContent(scene); this.CurrentSceneMetadata = metadata; this._settingsService.Settings.LastSceneOpened = metadata.ContentId; this._entityService.Selected = scene; this._systemService.Selected = scene.Systems.FirstOrDefault(); } } } } else { sceneAsset = null; } } return sceneAsset != null; } }
// 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.Immutable; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Threading; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal abstract class ExpressionCompiler : IDkmClrExpressionCompiler, IDkmClrExpressionCompilerCallback, IDkmModuleModifiedNotification { static ExpressionCompiler() { FatalError.Handler = FailFast.OnFatalException; } DkmCompiledClrLocalsQuery IDkmClrExpressionCompiler.GetClrLocalVariableQuery( DkmInspectionContext inspectionContext, DkmClrInstructionAddress instructionAddress, bool argumentsOnly) { try { var references = instructionAddress.RuntimeInstance.GetMetadataBlocks(instructionAddress.ModuleInstance.AppDomain); var context = this.CreateMethodContext(instructionAddress, references); var builder = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals( builder, argumentsOnly, out typeName, testData: null); Debug.Assert((builder.Count == 0) == (assembly.Count == 0)); var locals = new ReadOnlyCollection<DkmClrLocalVariableInfo>(builder.SelectAsArray(l => DkmClrLocalVariableInfo.Create(l.LocalName, l.MethodName, l.Flags, DkmEvaluationResultCategory.Data))); builder.Free(); return DkmCompiledClrLocalsQuery.Create(inspectionContext.RuntimeInstance, null, this.CompilerId, assembly, typeName, locals); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } void IDkmClrExpressionCompiler.CompileExpression( DkmLanguageExpression expression, DkmClrInstructionAddress instructionAddress, DkmInspectionContext inspectionContext, out string error, out DkmCompiledClrInspectionQuery result) { try { var appDomain = instructionAddress.ModuleInstance.AppDomain; var references = instructionAddress.RuntimeInstance.GetMetadataBlocks(appDomain); ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; ResultProperties resultProperties; CompileResult compileResult; do { var context = this.CreateMethodContext(instructionAddress, references); compileResult = context.CompileExpression( RuntimeInspectionContext.Create(inspectionContext), expression.Text, expression.CompilationFlags, this.DiagnosticFormatter, out resultProperties, out error, out missingAssemblyIdentities, preferredUICulture: null, testData: null); } while (ShouldTryAgainWithMoreMetadataBlocks(appDomain, missingAssemblyIdentities, ref references)); result = compileResult.ToQueryResult(this.CompilerId, resultProperties, instructionAddress.RuntimeInstance); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } void IDkmClrExpressionCompiler.CompileAssignment( DkmLanguageExpression expression, DkmClrInstructionAddress instructionAddress, DkmEvaluationResult lValue, out string error, out DkmCompiledClrInspectionQuery result) { try { var appDomain = instructionAddress.ModuleInstance.AppDomain; var references = instructionAddress.RuntimeInstance.GetMetadataBlocks(appDomain); ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; CompileResult compileResult; do { var context = this.CreateMethodContext(instructionAddress, references); compileResult = context.CompileAssignment( RuntimeInspectionContext.Create(lValue.InspectionContext), lValue.FullName, expression.Text, this.DiagnosticFormatter, out resultProperties, out error, out missingAssemblyIdentities, preferredUICulture: null, testData: null); } while (ShouldTryAgainWithMoreMetadataBlocks(appDomain, missingAssemblyIdentities, ref references)); Debug.Assert((resultProperties.Flags & DkmClrCompilationResultFlags.PotentialSideEffect) == DkmClrCompilationResultFlags.PotentialSideEffect); result = compileResult.ToQueryResult(this.CompilerId, resultProperties, instructionAddress.RuntimeInstance); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } void IDkmClrExpressionCompilerCallback.CompileDisplayAttribute( DkmLanguageExpression expression, DkmClrModuleInstance moduleInstance, int token, out string error, out DkmCompiledClrInspectionQuery result) { try { var appDomain = moduleInstance.AppDomain; var references = moduleInstance.RuntimeInstance.GetMetadataBlocks(appDomain); ResultProperties unusedResultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; CompileResult compileResult; do { var context = this.CreateTypeContext(moduleInstance, references, token); compileResult = context.CompileExpression( RuntimeInspectionContext.Empty, expression.Text, DkmEvaluationFlags.TreatAsExpression, this.DiagnosticFormatter, out unusedResultProperties, out error, out missingAssemblyIdentities, preferredUICulture: null, testData: null); } while (ShouldTryAgainWithMoreMetadataBlocks(appDomain, missingAssemblyIdentities, ref references)); result = compileResult.ToQueryResult(this.CompilerId, default(ResultProperties), moduleInstance.RuntimeInstance); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } private static bool ShouldTryAgainWithMoreMetadataBlocks(DkmClrAppDomain appDomain, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, ref ImmutableArray<MetadataBlock> references) { return ShouldTryAgainWithMoreMetadataBlocks( (AssemblyIdentity assemblyIdentity, out uint size) => appDomain.GetMetaDataBytesPtr(assemblyIdentity.GetDisplayName(), out size), missingAssemblyIdentities, ref references); } /// <remarks> /// Internal for testing. /// </remarks> internal static bool ShouldTryAgainWithMoreMetadataBlocks(DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, ref ImmutableArray<MetadataBlock> references) { var newReferences = DkmUtilities.GetMetadataBlocks(getMetaDataBytesPtrFunction, missingAssemblyIdentities); if (newReferences.Length > 0) { references = references.AddRange(newReferences); return true; } return false; } void IDkmModuleModifiedNotification.OnModuleModified(DkmModuleInstance moduleInstance) { // If the module is not a managed module, the module change has no effect. var module = moduleInstance as DkmClrModuleInstance; if (module == null) { return; } // Drop any context cached on the AppDomain. var appDomain = module.AppDomain; RemoveDataItem(appDomain); } internal abstract DiagnosticFormatter DiagnosticFormatter { get; } internal abstract DkmCompilerId CompilerId { get; } internal abstract EvaluationContextBase CreateTypeContext( DkmClrAppDomain appDomain, ImmutableArray<MetadataBlock> metadataBlocks, Guid moduleVersionId, int typeToken); internal abstract EvaluationContextBase CreateMethodContext( DkmClrAppDomain appDomain, ImmutableArray<MetadataBlock> metadataBlocks, Lazy<ImmutableArray<AssemblyReaders>> lazyAssemblyReaders, object symReader, Guid moduleVersionId, int methodToken, int methodVersion, int ilOffset, int localSignatureToken); internal abstract bool RemoveDataItem(DkmClrAppDomain appDomain); private EvaluationContextBase CreateTypeContext(DkmClrModuleInstance moduleInstance, ImmutableArray<MetadataBlock> references, int typeToken) { return this.CreateTypeContext( moduleInstance.AppDomain, references, moduleInstance.Mvid, typeToken); } private EvaluationContextBase CreateMethodContext(DkmClrInstructionAddress instructionAddress, ImmutableArray<MetadataBlock> metadataBlocks) { var moduleInstance = instructionAddress.ModuleInstance; var methodToken = instructionAddress.MethodId.Token; int localSignatureToken; try { localSignatureToken = moduleInstance.GetLocalSignatureToken(methodToken); } catch (InvalidOperationException) { // No local signature. May occur when debugging .dmp. localSignatureToken = 0; } catch (FileNotFoundException) { // No local signature. May occur when debugging heapless dumps. localSignatureToken = 0; } return this.CreateMethodContext( moduleInstance.AppDomain, metadataBlocks, new Lazy<ImmutableArray<AssemblyReaders>>(() => instructionAddress.MakeAssemblyReaders(), LazyThreadSafetyMode.None), symReader: moduleInstance.GetSymReader(), moduleVersionId: moduleInstance.Mvid, methodToken: methodToken, methodVersion: (int)instructionAddress.MethodId.Version, ilOffset: (int)instructionAddress.ILOffset, localSignatureToken: localSignatureToken); } } }
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace Hydra.Framework.ManagedInformationBase { // //********************************************************************** /// <summary> /// Summary description for PerformanceCounters. /// </summary> //********************************************************************** // public class PerformanceCounters { #region Public Externs // //********************************************************************** /// <summary> /// Inports the QueryPerformanceFrequency method into the class. This method is used to /// measure the current tickcount of the system /// </summary> /// <param name="ticks"></param> //********************************************************************** // [DllImport("Kernel32.dll")] public static extern void QueryPerformanceCounter(ref long ticks); #endregion #region Private Constants // // Performance counters // private const string PERF_CNT_CATEGORY = "Tap.Concerto.WorkAllocator.InferenceEngine"; private const string PERF_CNT_CATEGORY_DESC = "WorkAllocator Inference Engine Performance Characteristics"; private const string PERF_CNT_TOTAL_RQSTS_MADE = "TotalRequestsMade"; private const string PERF_CNT_TOTAL_RQSTS_MADE_DESC = "Total number of requests made"; private const string PERF_CNT_RQSTS_PER_SCND = "RequestsPerSecond"; private const string PERF_CNT_RQSTS_PER_SCND_DESC = "Requests/Sec rate"; private const string PERF_CNT_TOTAL_RQSTS_CMPLTD = "TotalRequestsCompleted"; private const string PERF_CNT_TOTAL_RQSTS_CMPLTD_DESC = "Total number of requests completed"; private const string PERF_CNT_RQSTS_CMPLT_PER_SCND = "RequestsCompletedPerSecond"; private const string PERF_CNT_RQSTS_CMPLT_PER_SCND_DESC = "Requests completed/Sec rate"; private const string PERF_CNT_RQSTS_CMPLT_PER_SCND_BASE = "RequestsCompletedPerSecondBase"; private const string PERF_CNT_RQSTS_CMPLT_PER_SCND_BASE_DESC = "Requests completed/Sec rate (base counter)"; private const string PERF_CNT_ITEMS_PER_SCND = "ItemsProcessedPerSecond"; private const string PERF_CNT_ITEMS_PER_SCND_DESC = "Number of items processed each second (service specific)"; private const string PERF_CNT_AVG_RQST_CMPLT_TIME = "AverageRequestCompletionTime"; private const string PERF_CNT_AVG_RQST_CMPLT_TIME_DESC = "Average time required to complete a request"; private const string PERF_CNT_AVG_RQST_CMPLT_TIME_BASE = "AverageRequestCompletionTimeBase"; private const string PERF_CNT_AVG_RQST_CMPLT_TIME__BASE_DESC = "Average time required to complete a request (base counter)"; private const string PERF_CNT_NUM_THREADS = "NumRunningThreads"; private const string PERF_CNT_NUM_THREADS_DESC = "Number of running threads"; private const string PERF_CNT_NUM_TASKS = "NumActiveTasks"; private const string PERF_CNT_NUM_TASKS_DESC = "Number of active Tasks in the TaskPreProcessor Queue"; private const string PERF_CNT_NUM_COMPLETED_TASKS = "NumCompletedTasks"; private const string PERF_CNT_NUM_COMPLETED_TASKS_DESC = "Number of completed Tasks (run through Inference successfully)"; private const string PERF_CNT_NUM_FAILED_TASKS = "NumFailedTasks"; private const string PERF_CNT_NUM_FAILED_TASKS_DESC = "Number of failed Tasks (failed in Inference)"; private const string PERF_CNT_NUM_SCRIPT_ENGINES = "NumActiveScriptEngines"; private const string PERF_CNT_NUM_SCRIPT_ENGINES_DESC = "Number of active Script Engines performing a single task"; private const string PERF_CNT_NUM_CAPABILITIES = "NumActiveCapabilities"; private const string PERF_CNT_NUM_CAPABILITIES_DESC = "Number of active Capabilities that the Inference Engine can process"; #endregion #region Private Attributes // //********************************************************************** /// <summary> /// Performance counters - Total Requests Made /// </summary> //********************************************************************** // private PerformanceCounter m_totalRequestsMade; // //********************************************************************** /// <summary> /// Performance counters - Requests Per Second /// </summary> //********************************************************************** // private PerformanceCounter m_requestsPerSecond; // //********************************************************************** /// <summary> /// Performance counters - Total Requests Completed /// </summary> //********************************************************************** // private PerformanceCounter m_totalRequestsCompleted; // //********************************************************************** /// <summary> /// Performance counters - Requests Completed Per Second /// </summary> //********************************************************************** // private PerformanceCounter m_requestsCompletedPerSecond; // //********************************************************************** /// <summary> /// Performance counters - Items Per Second /// </summary> //********************************************************************** // private PerformanceCounter m_itemsPerSecond; // //********************************************************************** /// <summary> /// Performance counters - Average Request Completion Time /// </summary> //********************************************************************** // private PerformanceCounter m_averageRequestCompletionTime; // //********************************************************************** /// <summary> /// Performance countersAverage Request Completion Time Base /// </summary> //********************************************************************** // private PerformanceCounter m_averageRequestCompletionTimeBase; // //********************************************************************** /// <summary> /// Performance counters - Num Running Threads /// </summary> //********************************************************************** // private PerformanceCounter m_numRunningThreads; // //********************************************************************** /// <summary> /// Performance counters - Number of Active Tasks /// </summary> //********************************************************************** // private PerformanceCounter m_numActiveTasks; // //********************************************************************** /// <summary> /// Performance counters - Number of Completed Tasks /// </summary> //********************************************************************** // private PerformanceCounter m_numCompletedTasks; // //********************************************************************** /// <summary> /// Performance counters - Number of Failed Tasks /// </summary> //********************************************************************** // private PerformanceCounter m_numFailedTasks; // //********************************************************************** /// <summary> /// Performance counters - Number of active script engines /// </summary> //********************************************************************** // private PerformanceCounter m_numActiveScriptEngines; // //********************************************************************** /// <summary> /// Performance counters - Number of active capabilities /// </summary> //********************************************************************** // private PerformanceCounter m_numActiveCapabilities; // //********************************************************************** /// <summary> /// The Current Time based on last call /// </summary> //********************************************************************** // private DateTime CurrentTime; // //********************************************************************** /// <summary> /// Start Time (Number of Ticks) /// </summary> //********************************************************************** // private long startTime = 0; // //********************************************************************** /// <summary> /// End Time (Number of Ticks) /// </summary> //********************************************************************** // private long endTime = 0; // //********************************************************************** /// <summary> /// Mutex Lock /// </summary> //********************************************************************** // private object pcLock = new object(); #endregion #region Constructors // //********************************************************************** /// <summary> /// Constructor /// </summary> //********************************************************************** // public PerformanceCounters(bool RemoveIfExists) { // // Setup and create performance counters // SetupPerformanceCounters(RemoveIfExists); CreatePerformanceCounters(); CurrentTime = DateTime.Now; } #endregion #region Performance Counter setup // //********************************************************************** /// <summary> /// Set up the performance counters. /// </summary> //********************************************************************** // private void SetupPerformanceCounters(bool RemoveIfExists) { // // Does the category exists? // if (PerformanceCounterCategory.Exists(PERF_CNT_CATEGORY)) { if (RemoveIfExists) PerformanceCounterCategory.Delete(PERF_CNT_CATEGORY); } if (!PerformanceCounterCategory.Exists(PERF_CNT_CATEGORY)) { // // Allways attempt to create the category // CounterCreationDataCollection CCDC = new CounterCreationDataCollection(); // // Add the standard counters // // Total requests made CounterCreationData totalRequestsMade = new CounterCreationData(); totalRequestsMade.CounterName = PERF_CNT_TOTAL_RQSTS_MADE; totalRequestsMade.CounterHelp = PERF_CNT_TOTAL_RQSTS_MADE_DESC; totalRequestsMade.CounterType = PerformanceCounterType.NumberOfItems32; CCDC.Add(totalRequestsMade); // // Requests per seond // CounterCreationData requestsPerSecond = new CounterCreationData(); requestsPerSecond.CounterName = PERF_CNT_RQSTS_PER_SCND; requestsPerSecond.CounterHelp = PERF_CNT_RQSTS_PER_SCND_DESC; requestsPerSecond.CounterType = PerformanceCounterType.RateOfCountsPerSecond32; CCDC.Add(requestsPerSecond); // // Total requests completed // CounterCreationData totalRequestsCompleted = new CounterCreationData(); totalRequestsCompleted.CounterName = PERF_CNT_TOTAL_RQSTS_CMPLTD; totalRequestsCompleted.CounterHelp = PERF_CNT_TOTAL_RQSTS_CMPLTD_DESC; totalRequestsCompleted.CounterType = PerformanceCounterType.NumberOfItems32; CCDC.Add(totalRequestsCompleted); // // Number of running threads // CounterCreationData numRunningThreads = new CounterCreationData(); numRunningThreads.CounterName = PERF_CNT_NUM_THREADS; numRunningThreads .CounterHelp = PERF_CNT_NUM_THREADS_DESC; numRunningThreads.CounterType = PerformanceCounterType.NumberOfItems32; CCDC.Add(numRunningThreads); // // Number of Active Tasks in the TaskPreProcessor Queue // CounterCreationData numActiveTasks = new CounterCreationData(); numActiveTasks.CounterName = PERF_CNT_NUM_TASKS; numActiveTasks.CounterHelp = PERF_CNT_NUM_TASKS_DESC; numActiveTasks.CounterType = PerformanceCounterType.NumberOfItems32; CCDC.Add(numActiveTasks); // // Number of Completed Tasks in the TaskPreProcessor Queue // CounterCreationData numCompletedTasks = new CounterCreationData(); numCompletedTasks.CounterName = PERF_CNT_NUM_COMPLETED_TASKS; numCompletedTasks.CounterHelp = PERF_CNT_NUM_COMPLETED_TASKS_DESC; numCompletedTasks.CounterType = PerformanceCounterType.NumberOfItems32; CCDC.Add(numCompletedTasks); // // Number of Failed Tasks in the TaskPreProcessor Queue // CounterCreationData numFailedTasks = new CounterCreationData(); numFailedTasks.CounterName = PERF_CNT_NUM_FAILED_TASKS; numFailedTasks.CounterHelp = PERF_CNT_NUM_FAILED_TASKS_DESC; numFailedTasks.CounterType = PerformanceCounterType.NumberOfItems32; CCDC.Add(numFailedTasks); // // Number of active script engines performing a single task // CounterCreationData numActiveScriptEngines = new CounterCreationData(); numActiveScriptEngines.CounterName = PERF_CNT_NUM_SCRIPT_ENGINES; numActiveScriptEngines.CounterHelp = PERF_CNT_NUM_SCRIPT_ENGINES_DESC; numActiveScriptEngines.CounterType = PerformanceCounterType.NumberOfItems32; CCDC.Add(numActiveScriptEngines); // // Number of Active Capabilities // CounterCreationData numActiveCapabilities = new CounterCreationData(); numActiveCapabilities.CounterName = PERF_CNT_NUM_CAPABILITIES; numActiveCapabilities.CounterHelp = PERF_CNT_NUM_CAPABILITIES_DESC; numActiveCapabilities.CounterType = PerformanceCounterType.NumberOfItems32; CCDC.Add(numActiveCapabilities); // // Requests completed per second // CounterCreationData requestsCompletedPerSecnond = new CounterCreationData(); requestsCompletedPerSecnond.CounterName = PERF_CNT_RQSTS_CMPLT_PER_SCND; requestsCompletedPerSecnond.CounterHelp = PERF_CNT_RQSTS_CMPLT_PER_SCND_DESC; requestsCompletedPerSecnond.CounterType = PerformanceCounterType.RateOfCountsPerSecond32; CCDC.Add(requestsCompletedPerSecnond); // // Items process per second // CounterCreationData itemsPerSecond = new CounterCreationData(); itemsPerSecond.CounterName = PERF_CNT_ITEMS_PER_SCND; itemsPerSecond.CounterHelp = PERF_CNT_ITEMS_PER_SCND_DESC; itemsPerSecond.CounterType = PerformanceCounterType.RateOfCountsPerSecond32; CCDC.Add(itemsPerSecond); // // Average request completion time // CounterCreationData averageRequestCompletionTime = new CounterCreationData(); averageRequestCompletionTime.CounterName = PERF_CNT_AVG_RQST_CMPLT_TIME; averageRequestCompletionTime.CounterHelp = PERF_CNT_AVG_RQST_CMPLT_TIME_DESC; averageRequestCompletionTime.CounterType = PerformanceCounterType.AverageTimer32; CCDC.Add(averageRequestCompletionTime); CounterCreationData averageRequestCompletionTimeBase = new CounterCreationData(); averageRequestCompletionTimeBase.CounterName = PERF_CNT_AVG_RQST_CMPLT_TIME_BASE; averageRequestCompletionTimeBase.CounterHelp = PERF_CNT_AVG_RQST_CMPLT_TIME__BASE_DESC; averageRequestCompletionTimeBase.CounterType = PerformanceCounterType.AverageBase; CCDC.Add(averageRequestCompletionTimeBase); // // Create the category. // PerformanceCounterCategory.Create(PERF_CNT_CATEGORY, PERF_CNT_CATEGORY_DESC, CCDC); } } // //********************************************************************** /// <summary> /// Create and initialize the standard set of performance counters /// </summary> //********************************************************************** // private void CreatePerformanceCounters() { // // Create and initialize // m_totalRequestsMade = new PerformanceCounter(); m_totalRequestsMade.CategoryName = PERF_CNT_CATEGORY; m_totalRequestsMade.CounterName = PERF_CNT_TOTAL_RQSTS_MADE; m_totalRequestsMade.ReadOnly = false; m_totalRequestsMade.MachineName = "."; m_totalRequestsMade.RawValue = 0; m_requestsPerSecond = new PerformanceCounter(); m_requestsPerSecond.CategoryName = PERF_CNT_CATEGORY; m_requestsPerSecond.CounterName = PERF_CNT_RQSTS_PER_SCND; m_requestsPerSecond.ReadOnly = false; m_requestsPerSecond.MachineName = "."; m_requestsPerSecond.RawValue = 0; m_totalRequestsCompleted = new PerformanceCounter(); m_totalRequestsCompleted.CategoryName = PERF_CNT_CATEGORY; m_totalRequestsCompleted.CounterName = PERF_CNT_TOTAL_RQSTS_CMPLTD; m_totalRequestsCompleted.ReadOnly = false; m_totalRequestsCompleted.MachineName = "."; m_totalRequestsCompleted.RawValue = 0; m_requestsCompletedPerSecond = new PerformanceCounter(); m_requestsCompletedPerSecond.CategoryName = PERF_CNT_CATEGORY; m_requestsCompletedPerSecond.CounterName = PERF_CNT_RQSTS_CMPLT_PER_SCND; m_requestsCompletedPerSecond.ReadOnly = false; m_requestsCompletedPerSecond.MachineName = "."; m_requestsCompletedPerSecond.RawValue = 0; m_itemsPerSecond = new PerformanceCounter(); m_itemsPerSecond.CategoryName = PERF_CNT_CATEGORY; m_itemsPerSecond.CounterName = PERF_CNT_ITEMS_PER_SCND; m_itemsPerSecond.ReadOnly = false; m_itemsPerSecond.MachineName = "."; m_itemsPerSecond.RawValue = 0; m_numRunningThreads = new PerformanceCounter(); m_numRunningThreads.CategoryName = PERF_CNT_CATEGORY; m_numRunningThreads.CounterName = PERF_CNT_NUM_THREADS; m_numRunningThreads.ReadOnly = false; m_numRunningThreads.MachineName = "."; m_numRunningThreads.RawValue = 0; m_numActiveTasks = new PerformanceCounter(); m_numActiveTasks.CategoryName = PERF_CNT_CATEGORY; m_numActiveTasks.CounterName = PERF_CNT_NUM_TASKS; m_numActiveTasks.ReadOnly = false; m_numActiveTasks.MachineName = "."; m_numActiveTasks.RawValue = 0; m_numCompletedTasks = new PerformanceCounter(); m_numCompletedTasks.CategoryName = PERF_CNT_CATEGORY; m_numCompletedTasks.CounterName = PERF_CNT_NUM_COMPLETED_TASKS; m_numCompletedTasks.ReadOnly = false; m_numCompletedTasks.MachineName = "."; m_numCompletedTasks.RawValue = 0; m_numFailedTasks = new PerformanceCounter(); m_numFailedTasks.CategoryName = PERF_CNT_CATEGORY; m_numFailedTasks.CounterName = PERF_CNT_NUM_FAILED_TASKS; m_numFailedTasks.ReadOnly = false; m_numFailedTasks.MachineName = "."; m_numFailedTasks.RawValue = 0; m_numActiveScriptEngines = new PerformanceCounter(); m_numActiveScriptEngines.CategoryName = PERF_CNT_CATEGORY; m_numActiveScriptEngines.CounterName = PERF_CNT_NUM_SCRIPT_ENGINES; m_numActiveScriptEngines.ReadOnly = false; m_numActiveScriptEngines.MachineName = "."; m_numActiveScriptEngines.RawValue = 0; m_numActiveCapabilities = new PerformanceCounter(); m_numActiveCapabilities.CategoryName = PERF_CNT_CATEGORY; m_numActiveCapabilities.CounterName = PERF_CNT_NUM_CAPABILITIES; m_numActiveCapabilities.ReadOnly = false; m_numActiveCapabilities.MachineName = "."; m_numActiveCapabilities.RawValue = 0; m_averageRequestCompletionTime = new PerformanceCounter(); m_averageRequestCompletionTime.CategoryName = PERF_CNT_CATEGORY; m_averageRequestCompletionTime.CounterName = PERF_CNT_AVG_RQST_CMPLT_TIME; m_averageRequestCompletionTime.ReadOnly = false; m_averageRequestCompletionTime.MachineName = "."; m_averageRequestCompletionTime.RawValue = 0; m_averageRequestCompletionTimeBase = new PerformanceCounter(); m_averageRequestCompletionTimeBase.CategoryName = PERF_CNT_CATEGORY; m_averageRequestCompletionTimeBase.CounterName = PERF_CNT_AVG_RQST_CMPLT_TIME_BASE; m_averageRequestCompletionTimeBase.ReadOnly = false; m_averageRequestCompletionTimeBase.MachineName = "."; m_averageRequestCompletionTimeBase.RawValue = 0; } // //********************************************************************** /// <summary> /// Remove the performance counter instances /// A call to RemoveServicePerformanceCounters is made /// to allow the removal of service-specific performance counters /// </summary> //********************************************************************** // private void RemovePerformanceCounters() { m_totalRequestsMade.RemoveInstance(); m_requestsPerSecond.RemoveInstance(); m_totalRequestsCompleted.RemoveInstance(); m_requestsCompletedPerSecond.RemoveInstance(); m_itemsPerSecond.RemoveInstance(); m_averageRequestCompletionTime.RemoveInstance(); m_averageRequestCompletionTimeBase.RemoveInstance(); m_numRunningThreads.RemoveInstance(); m_numActiveTasks.RemoveInstance(); m_numCompletedTasks.RemoveInstance(); m_numFailedTasks.RemoveInstance(); m_numActiveScriptEngines.RemoveInstance(); m_numActiveCapabilities.RemoveInstance(); } #endregion #region Perfomance Counting // //********************************************************************** /// <summary> /// Call when a new request has been made /// </summary> //********************************************************************** // public DateTime IncRequestMade() { lock(pcLock) { // // Update all counters // m_totalRequestsMade.Increment(); m_requestsPerSecond.Increment(); return DateTime.Now; } } // //********************************************************************** /// <summary> /// Call whenever a request is completed /// </summary> //********************************************************************** // public void IncRequestsCompleted() { lock(pcLock) { // // Update all counters // if (startTime == 0) QueryPerformanceCounter(ref startTime); // // Get End Time // QueryPerformanceCounter(ref endTime); //m_totalRequestsCompleted.Increment(); m_requestsCompletedPerSecond.Increment(); m_averageRequestCompletionTime.IncrementBy(endTime - startTime); m_averageRequestCompletionTimeBase.Increment(); startTime = endTime; } } // //********************************************************************** /// <summary> /// Call when a single item has been processed /// </summary> //********************************************************************** // public void IncrementItemsProcessed() { lock(pcLock) { m_itemsPerSecond.Increment(); } } // //********************************************************************** /// <summary> /// Call when multiple items have been processed /// (instead of calling IncrementItemsProcessed multiple times) /// </summary> /// <param name="incrementBy"></param> //********************************************************************** // public void IncrementItemsProcessed(int incrementBy) { lock(pcLock) { m_itemsPerSecond.IncrementBy(incrementBy); } } // //********************************************************************** /// <summary> /// Call whenever a thread is created /// </summary> //********************************************************************** // public void IncThreadCount() { lock(pcLock) { m_numRunningThreads.Increment(); } } // //********************************************************************** /// <summary> /// Call everytime a thread is killed/removed /// </summary> //********************************************************************** // public void DecThreadCount() { lock(pcLock) { m_numRunningThreads.Decrement(); } } // //********************************************************************** /// <summary> /// Call whenever a task is added to the TaskPreProcessor Queue /// </summary> //********************************************************************** // public void IncTaskCount() { lock(pcLock) { m_numActiveTasks.Increment(); } } // //********************************************************************** /// <summary> /// Call whenever a task has been completed /// </summary> //********************************************************************** // public void IncTaskCompletedCount() { lock(pcLock) { m_numCompletedTasks.Increment(); } } // //********************************************************************** /// <summary> /// Call whenever a task fails /// </summary> //********************************************************************** // public void IncTaskFailedCount() { lock(pcLock) { m_numFailedTasks.Increment(); } } // //********************************************************************** /// <summary> /// Call whenever a task is removed from the TaskPreProcessor Queue /// </summary> //********************************************************************** // public void DecTaskCount() { lock(pcLock) { m_numActiveTasks.Decrement(); } } // //********************************************************************** /// <summary> /// Call whenever a script engine is started to perform a task /// </summary> //********************************************************************** // public void IncScriptEngineCount() { lock(pcLock) { m_numActiveScriptEngines.Increment(); } } // //********************************************************************** /// <summary> /// Call whenever a script engine is shutdown after performing a task /// </summary> //********************************************************************** // public void DecScriptEngineCount() { lock(pcLock) { m_numActiveScriptEngines.Decrement(); } } // //********************************************************************** /// <summary> /// Call whenever a capability can be performed by the inference engine /// </summary> //********************************************************************** // public void IncCapabilityCount() { lock(pcLock) { m_numActiveCapabilities.Increment(); } } // //********************************************************************** /// <summary> /// Call whenever a capability can not be performed by the inference engine /// </summary> //********************************************************************** // public void DecCapabilityCount() { lock(pcLock) { m_numActiveCapabilities.Decrement(); } } #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; using System.Globalization; using System.IO; using System.Text.Encodings.Web; using System.Text.Unicode; using Xunit; namespace Microsoft.Framework.WebEncoders { public class JavaScriptStringEncoderTests { [Fact] public void TestSurrogate() { Assert.Equal("\\uD83D\\uDCA9", System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode("\U0001f4a9")); using (var writer = new StringWriter()) { System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(writer, "\U0001f4a9"); Assert.Equal("\\uD83D\\uDCA9", writer.GetStringBuilder().ToString()); } } [Fact] public void Ctor_WithTextEncoderSettings() { // Arrange var filter = new TextEncoderSettings(); filter.AllowCharacters('a', 'b'); filter.AllowCharacters('\0', '&', '\uFFFF', 'd'); JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(filter); // Act & assert Assert.Equal("a", encoder.JavaScriptStringEncode("a")); Assert.Equal("b", encoder.JavaScriptStringEncode("b")); Assert.Equal(@"\u0063", encoder.JavaScriptStringEncode("c")); Assert.Equal("d", encoder.JavaScriptStringEncode("d")); Assert.Equal(@"\u0000", encoder.JavaScriptStringEncode("\0")); // we still always encode control chars Assert.Equal(@"\u0026", encoder.JavaScriptStringEncode("&")); // we still always encode HTML-special chars Assert.Equal(@"\uFFFF", encoder.JavaScriptStringEncode("\uFFFF")); // we still always encode non-chars and other forbidden chars } [Fact] public void Ctor_WithUnicodeRanges() { // Arrange JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.Latin1Supplement, UnicodeRanges.MiscellaneousSymbols); // Act & assert Assert.Equal(@"\u0061", encoder.JavaScriptStringEncode("a")); Assert.Equal("\u00E9", encoder.JavaScriptStringEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */)); Assert.Equal("\u2601", encoder.JavaScriptStringEncode("\u2601" /* CLOUD */)); } [Fact] public void Ctor_WithNoParameters_DefaultsToBasicLatin() { // Arrange JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(); // Act & assert Assert.Equal("a", encoder.JavaScriptStringEncode("a")); Assert.Equal(@"\u00E9", encoder.JavaScriptStringEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */)); Assert.Equal(@"\u2601", encoder.JavaScriptStringEncode("\u2601" /* CLOUD */)); } [Fact] public void Default_EquivalentToBasicLatin() { // Arrange JavaScriptStringEncoder controlEncoder = new JavaScriptStringEncoder(UnicodeRanges.BasicLatin); JavaScriptStringEncoder testEncoder = JavaScriptStringEncoder.Default; // Act & assert for (int i = 0; i <= char.MaxValue; i++) { if (!IsSurrogateCodePoint(i)) { string input = new string((char)i, 1); Assert.Equal(controlEncoder.JavaScriptStringEncode(input), testEncoder.JavaScriptStringEncode(input)); } } } [Fact] public void JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple_Escaping() { // The following two calls could be simply InlineData to the Theory below // Unfortunately, the xUnit logger fails to escape the inputs when logging the test results, // and so the suite fails despite all tests passing. // TODO: I will try to fix it in xUnit, but for now this is a workaround to enable these tests. JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple("\b", @"\b"); JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple("\f", @"\f"); } [Theory] [InlineData("<", @"\u003C")] [InlineData(">", @"\u003E")] [InlineData("&", @"\u0026")] [InlineData("'", @"\u0027")] [InlineData("\"", @"\u0022")] [InlineData("+", @"\u002B")] [InlineData("\\", @"\\")] [InlineData("/", @"\/")] [InlineData("\n", @"\n")] [InlineData("\t", @"\t")] [InlineData("\r", @"\r")] public void JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple(string input, string expected) { // Arrange JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.All); // Act string retVal = encoder.JavaScriptStringEncode(input); // Assert Assert.Equal(expected, retVal); } [Fact] public void JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Extended() { // Arrange JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.All); // Act & assert - BMP chars for (int i = 0; i <= 0xFFFF; i++) { string input = new string((char)i, 1); string expected; if (IsSurrogateCodePoint(i)) { expected = "\uFFFD"; // unpaired surrogate -> Unicode replacement char } else { if (input == "\b") { expected = @"\b"; } else if (input == "\t") { expected = @"\t"; } else if (input == "\n") { expected = @"\n"; } else if (input == "\f") { expected = @"\f"; } else if (input == "\r") { expected = @"\r"; } else if (input == "\\") { expected = @"\\"; } else if (input == "/") { expected = @"\/"; } else if (input == "`") { expected = @"\u0060"; } else { bool mustEncode = false; switch (i) { case '<': case '>': case '&': case '\"': case '\'': case '+': mustEncode = true; break; } if (i <= 0x001F || (0x007F <= i && i <= 0x9F)) { mustEncode = true; // control char } else if (!UnicodeHelpers.IsCharacterDefined((char)i)) { mustEncode = true; // undefined (or otherwise disallowed) char } if (mustEncode) { expected = string.Format(CultureInfo.InvariantCulture, @"\u{0:X4}", i); } else { expected = input; // no encoding } } } string retVal = encoder.JavaScriptStringEncode(input); Assert.Equal(expected, retVal); } // Act & assert - astral chars for (int i = 0x10000; i <= 0x10FFFF; i++) { string input = char.ConvertFromUtf32(i); string expected = string.Format(CultureInfo.InvariantCulture, @"\u{0:X4}\u{1:X4}", (uint)input[0], (uint)input[1]); string retVal = encoder.JavaScriptStringEncode(input); Assert.Equal(expected, retVal); } } [Fact] public void JavaScriptStringEncode_BadSurrogates_ReturnsUnicodeReplacementChar() { // Arrange JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.All); // allow all codepoints // "a<unpaired leading>b<unpaired trailing>c<trailing before leading>d<unpaired trailing><valid>e<high at end of string>" const string input = "a\uD800b\uDFFFc\uDFFF\uD800d\uDFFF\uD800\uDFFFe\uD800"; const string expected = "a\uFFFDb\uFFFDc\uFFFD\uFFFDd\uFFFD\\uD800\\uDFFFe\uFFFD"; // 'D800' 'DFFF' was preserved since it's valid // Act string retVal = encoder.JavaScriptStringEncode(input); // Assert Assert.Equal(expected, retVal); } [Fact] public void JavaScriptStringEncode_EmptyStringInput_ReturnsEmptyString() { // Arrange JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(); // Act & assert Assert.Equal("", encoder.JavaScriptStringEncode("")); } [Fact] public void JavaScriptStringEncode_InputDoesNotRequireEncoding_ReturnsOriginalStringInstance() { // Arrange JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(); string input = "Hello, there!"; // Act & assert Assert.Same(input, encoder.JavaScriptStringEncode(input)); } [Fact] public void JavaScriptStringEncode_NullInput_Throws() { // Arrange JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(); Assert.Throws<ArgumentNullException>(() => { encoder.JavaScriptStringEncode(null); }); } [Fact] public void JavaScriptStringEncode_WithCharsRequiringEncodingAtBeginning() { Assert.Equal(@"\u0026Hello, there!", new JavaScriptStringEncoder().JavaScriptStringEncode("&Hello, there!")); } [Fact] public void JavaScriptStringEncode_WithCharsRequiringEncodingAtEnd() { Assert.Equal(@"Hello, there!\u0026", new JavaScriptStringEncoder().JavaScriptStringEncode("Hello, there!&")); } [Fact] public void JavaScriptStringEncode_WithCharsRequiringEncodingInMiddle() { Assert.Equal(@"Hello, \u0026there!", new JavaScriptStringEncoder().JavaScriptStringEncode("Hello, &there!")); } [Fact] public void JavaScriptStringEncode_WithCharsRequiringEncodingInterspersed() { Assert.Equal(@"Hello, \u003Cthere\u003E!", new JavaScriptStringEncoder().JavaScriptStringEncode("Hello, <there>!")); } [Fact] public void JavaScriptStringEncode_CharArray() { // Arrange JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(); var output = new StringWriter(); // Act encoder.JavaScriptStringEncode("Hello+world!".ToCharArray(), 3, 5, output); // Assert Assert.Equal(@"lo\u002Bwo", output.ToString()); } [Fact] public void JavaScriptStringEncode_StringSubstring() { // Arrange JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(); var output = new StringWriter(); // Act encoder.JavaScriptStringEncode("Hello+world!", 3, 5, output); // Assert Assert.Equal(@"lo\u002Bwo", output.ToString()); } [Theory] [InlineData("\"", @"\u0022")] [InlineData("'", @"\u0027")] public void JavaScriptStringEncode_Quotes(string input, string expected) { // Per the design document, we provide additional defense-in-depth // against breaking out of HTML attributes by having the encoders // never emit the ' or " characters. This means that we want to // \u-escape these characters instead of using \' and \". // Arrange JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.All); // Act string retVal = encoder.JavaScriptStringEncode(input); // Assert Assert.Equal(expected, retVal); } [Fact] public void JavaScriptStringEncode_DoesNotOutputHtmlSensitiveCharacters() { // Per the design document, we provide additional defense-in-depth // by never emitting HTML-sensitive characters unescaped. // Arrange JavaScriptStringEncoder javaScriptStringEncoder = new JavaScriptStringEncoder(UnicodeRanges.All); HtmlEncoder htmlEncoder = new HtmlEncoder(UnicodeRanges.All); // Act & assert for (int i = 0; i <= 0x10FFFF; i++) { if (IsSurrogateCodePoint(i)) { continue; // surrogates don't matter here } string javaScriptStringEncoded = javaScriptStringEncoder.JavaScriptStringEncode(char.ConvertFromUtf32(i)); string thenHtmlEncoded = htmlEncoder.HtmlEncode(javaScriptStringEncoded); Assert.Equal(javaScriptStringEncoded, thenHtmlEncoded); // should have contained no HTML-sensitive characters } } private static bool IsSurrogateCodePoint(int codePoint) { return (0xD800 <= codePoint && codePoint <= 0xDFFF); } } }
#region File Description //----------------------------------------------------------------------------- // Game1.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using Microsoft.Xna.Framework.Media; namespace FirstPersonCameraWindows { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { Matrix view; Matrix proj; Model box; Texture2D boxTexture; // Set the avatar position and rotation variables. static Vector3 avatarPosition = new Vector3(0, 0, -50); static Vector3 cameraPosition = avatarPosition; float avatarYaw; // Set the direction the camera points without rotation. Vector3 cameraReference = new Vector3(0, 0, 1); // Set rates in world units per 1/60th second (the default fixed-step interval). float rotationSpeed = 1f / 60f; float forwardSpeed = 50f / 60f; // Set field of view of the camera in radians (pi/4 is 45 degrees). static float viewAngle = MathHelper.PiOver4; // Set distance from the camera of the near and far clipping planes. static float nearClip = 1.0f; static float farClip = 2000.0f; GraphicsDeviceManager graphics; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { box = Content.Load<Model>("box"); boxTexture = Content.Load<Texture2D>("boxtexture"); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); if (Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit(); UpdateAvatarPosition(); UpdateCamera(); base.Update(gameTime); } /// <summary> /// Updates the position and direction of the avatar. /// </summary> void UpdateAvatarPosition() { KeyboardState keyboardState = Keyboard.GetState(); GamePadState currentState = GamePad.GetState(PlayerIndex.One); if (keyboardState.IsKeyDown(Keys.Left) || (currentState.DPad.Left == ButtonState.Pressed)) { // Rotate left. avatarYaw += rotationSpeed; } if (keyboardState.IsKeyDown(Keys.Right) || (currentState.DPad.Right == ButtonState.Pressed)) { // Rotate right. avatarYaw -= rotationSpeed; } if (keyboardState.IsKeyDown(Keys.Up) || (currentState.DPad.Up == ButtonState.Pressed)) { Matrix forwardMovement = Matrix.CreateRotationY(avatarYaw); Vector3 v = new Vector3(0, 0, forwardSpeed); v = Vector3.Transform(v, forwardMovement); avatarPosition.Z += v.Z; avatarPosition.X += v.X; } if (keyboardState.IsKeyDown(Keys.Down) || (currentState.DPad.Down == ButtonState.Pressed)) { Matrix forwardMovement = Matrix.CreateRotationY(avatarYaw); Vector3 v = new Vector3(0, 0, -forwardSpeed); v = Vector3.Transform(v, forwardMovement); avatarPosition.Z += v.Z; avatarPosition.X += v.X; } } /// <summary> /// Updates the position and direction of the camera relative to the avatar. /// </summary> void UpdateCamera() { // Calculate the camera's current position. Matrix rotationMatrix = Matrix.CreateRotationY(avatarYaw); // Create a vector pointing the direction the camera is facing. Vector3 transformedReference = Vector3.Transform(cameraReference, rotationMatrix); // Calculate the position the camera is looking at. Vector3 cameraLookat = cameraPosition + transformedReference; // Set up the view matrix and projection matrix. view = Matrix.CreateLookAt(cameraPosition, cameraLookat, new Vector3(0.0f, 1.0f, 0.0f)); proj = Matrix.CreatePerspectiveFieldOfView(viewAngle, graphics.GraphicsDevice.Viewport.AspectRatio, nearClip, farClip); } /// <summary> /// Draws the box model; a reference point for the avatar. /// </summary> void DrawModel(Model model, Matrix world, Texture2D texture) { foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect be in mesh.Effects) { be.Projection = proj; be.View = view; be.World = world; be.Texture = texture; be.TextureEnabled = true; } mesh.Draw(); } } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear(Color.SteelBlue); DrawModel(box, Matrix.Identity, boxTexture); base.Draw(gameTime); } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** using System; using System.Drawing; using System.Windows.Forms; using NUnit.Core; using NUnit.Util; namespace NUnit.UiKit { public class StatusBar : System.Windows.Forms.StatusBar, TestObserver { private StatusBarPanel statusPanel = new StatusBarPanel(); private StatusBarPanel testCountPanel = new StatusBarPanel(); private StatusBarPanel testsRunPanel = new StatusBarPanel(); private StatusBarPanel errorsPanel = new StatusBarPanel(); private StatusBarPanel failuresPanel = new StatusBarPanel(); private StatusBarPanel timePanel = new StatusBarPanel(); private int testCount = 0; private int testsRun = 0; private int errors = 0; private int failures = 0; private double time = 0.0; private bool displayProgress = false; public bool DisplayTestProgress { get { return displayProgress; } set { displayProgress = value; } } public StatusBar() { Panels.Add( statusPanel ); Panels.Add( testCountPanel ); Panels.Add( testsRunPanel ); Panels.Add( errorsPanel ); Panels.Add( failuresPanel ); Panels.Add( timePanel ); statusPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring; statusPanel.BorderStyle = StatusBarPanelBorderStyle.None; statusPanel.Text = "Status"; testCountPanel.AutoSize = StatusBarPanelAutoSize.Contents; testsRunPanel.AutoSize = StatusBarPanelAutoSize.Contents; errorsPanel.AutoSize = StatusBarPanelAutoSize.Contents; failuresPanel.AutoSize = StatusBarPanelAutoSize.Contents; timePanel.AutoSize = StatusBarPanelAutoSize.Contents; ShowPanels = true; InitPanels(); } // Kluge to keep VS from generating code that sets the Panels for // the statusbar. Really, our status bar should be a user control // to avoid this and shouldn't allow the panels to be set except // according to specific protocols. [System.ComponentModel.DesignerSerializationVisibility( System.ComponentModel.DesignerSerializationVisibility.Hidden )] public new System.Windows.Forms.StatusBar.StatusBarPanelCollection Panels { get { return base.Panels; } } public override string Text { get { return statusPanel.Text; } set { statusPanel.Text = value; } } public void Initialize( int testCount ) { Initialize( testCount, testCount > 0 ? "Ready" : "" ); } public void Initialize( int testCount, string text ) { this.statusPanel.Text = text; this.testCount = testCount; this.testsRun = 0; this.errors = 0; this.failures = 0; this.time = 0.0; InitPanels(); } private void InitPanels() { this.testCountPanel.MinWidth = 50; DisplayTestCount(); this.testsRunPanel.MinWidth = 50; this.testsRunPanel.Text = ""; this.errorsPanel.MinWidth = 50; this.errorsPanel.Text = ""; this.failuresPanel.MinWidth = 50; this.failuresPanel.Text = ""; this.timePanel.MinWidth = 50; this.timePanel.Text = ""; } private void DisplayTestCount() { testCountPanel.Text = "Test Cases : " + testCount.ToString(); } private void DisplayTestsRun() { testsRunPanel.Text = "Tests Run : " + testsRun.ToString(); } private void DisplayErrors() { errorsPanel.Text = "Errors : " + errors.ToString(); } private void DisplayFailures() { failuresPanel.Text = "Failures : " + failures.ToString(); } private void DisplayTime() { timePanel.Text = "Time : " + time.ToString(); } private void DisplayResult(TestResult result) { ResultSummarizer summarizer = new ResultSummarizer(result); //this.testCount = summarizer.ResultCount; this.testsRun = summarizer.TestsRun; this.errors = summarizer.Errors; this.failures = summarizer.Failures; this.time = summarizer.Time; DisplayTestCount(); DisplayTestsRun(); DisplayErrors(); DisplayFailures(); DisplayTime(); } public void OnTestLoaded( object sender, TestEventArgs e ) { Initialize( e.TestCount ); } public void OnTestReloaded( object sender, TestEventArgs e ) { Initialize( e.TestCount, "Reloaded" ); } public void OnTestUnloaded( object sender, TestEventArgs e ) { Initialize( 0, "Unloaded" ); } private void OnRunStarting( object sender, TestEventArgs e ) { Initialize( e.TestCount, "Running :" + e.Name ); DisplayTestCount(); DisplayTestsRun(); DisplayErrors(); DisplayFailures(); DisplayTime(); } private void OnRunFinished(object sender, TestEventArgs e ) { if ( e.Exception != null ) statusPanel.Text = "Failed"; else { statusPanel.Text = "Completed"; DisplayResult( e.Result ); } } public void OnTestStarting( object sender, TestEventArgs e ) { string fullText = "Running : " + e.TestName.FullName; string shortText = "Running : " + e.TestName.Name; Graphics g = Graphics.FromHwnd( Handle ); SizeF sizeNeeded = g.MeasureString( fullText, Font ); if ( statusPanel.Width >= (int)sizeNeeded.Width ) { statusPanel.Text = fullText; statusPanel.ToolTipText = ""; } else { sizeNeeded = g.MeasureString( shortText, Font ); statusPanel.Text = statusPanel.Width >= (int)sizeNeeded.Width ? shortText : e.TestName.Name; statusPanel.ToolTipText = e.TestName.FullName; } } private void OnTestFinished( object sender, TestEventArgs e ) { if ( DisplayTestProgress && e.Result.Executed ) { ++testsRun; DisplayTestsRun(); switch ( e.Result.ResultState ) { case ResultState.Error: case ResultState.Cancelled: ++errors; DisplayErrors(); break; case ResultState.Failure: ++failures; DisplayFailures(); break; } } } // protected override void OnFontChanged(EventArgs e) // { // base.OnFontChanged(e); // // this.Height = (int)(this.Font.Height * 1.6); // } #region TestObserver Members public void Subscribe(ITestEvents events) { events.TestLoaded += new TestEventHandler( OnTestLoaded ); events.TestReloaded += new TestEventHandler( OnTestReloaded ); events.TestUnloaded += new TestEventHandler( OnTestUnloaded ); events.TestStarting += new TestEventHandler( OnTestStarting ); events.TestFinished += new TestEventHandler( OnTestFinished ); events.RunStarting += new TestEventHandler( OnRunStarting ); events.RunFinished += new TestEventHandler( OnRunFinished ); } #endregion } }
using Xunit; namespace Jint.Tests.Ecma { public class Test_15_4_4_18 : EcmaTest { [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachMustExistAsAFunction() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-0-1.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthMustBe1() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-0-2.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToUndefined() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-1.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToTheMathObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-10.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToDateObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-11.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToRegexpObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-12.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToTheJsonObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-13.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToErrorObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-14.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToTheArgumentsObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-15.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToNull() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-2.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToBooleanPrimitive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-3.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToBooleanObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-4.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToNumberPrimitive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-5.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToNumberObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-6.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToStringPrimitive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-7.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToStringObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-8.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToFunctionObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-1-9.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthIsOwnDataPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-1.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToArrayLikeObjectLengthIsAnInheritedAccessorProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-10.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToArrayLikeObjectLengthIsAnOwnAccessorPropertyWithoutAGetFunction() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-11.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthIsOwnAccessorPropertyWithoutAGetFunctionThatOverridesAnInheritedAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-12.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToTheArrayLikeObjectThatLengthIsInheritedAccessorPropertyWithoutAGetFunction() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-13.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToTheArrayLikeObjectThatLengthPropertyDoesnTExist() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-14.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthIsPropertyOfTheGlobalObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-15.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-17.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToStringObjectWhichImplementsItsOwnPropertyGetMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-18.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToFunctionObjectWhichImplementsItsOwnPropertyGetMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-19.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthIsOwnDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-2.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthIsAnOwnDataPropertyThatOverridesAnInheritedDataPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-3.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthIsOwnDataPropertyThatOverridesAnInheritedDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-4.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToArrayLikeObjectLengthIsAnOwnDataPropertyThatOverridesAnInheritedAccessorProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-5.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToArrayLikeObjectLengthIsAnInheritedDataProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-6.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToArrayLikeObjectLengthIsAnOwnAccessorProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-7.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToArrayLikeObjectLengthIsAnOwnAccessorPropertyThatOverridesAnInheritedDataProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-8.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAppliedToArrayLikeObjectLengthIsAnOwnAccessorPropertyThatOverridesAnInheritedAccessorProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-2-9.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsUndefined() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-1.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsANumberValueIsNan() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-10.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthIsAStringContainingAPositiveNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-11.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthIsAStringContainingANegativeNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-12.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthIsAStringContainingADecimalNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-13.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthIsAStringContainingInfinity() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-14.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthIsAStringContainingAnExponentialNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-15.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthIsAStringContainingAHexNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-16.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthIsAStringContainingANumberWithLeadingZeros() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-17.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsAStringThatCanTConvertToANumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-18.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsAnObjectWhichHasAnOwnTostringMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-19.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsABooleanValueIsTrue() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-2.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsAnObjectWhichHasAnOwnValueofMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-20.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachLengthIsAnObjectThatHasAnOwnValueofMethodThatReturnsAnObjectAndTostringMethodThatReturnsAString() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-21.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThrowsTypeerrorExceptionWhenLengthIsAnObjectWithTostringAndValueofMethodsThatDonTReturnPrimitiveValues() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-22.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachUsesInheritedValueofMethodWhenLengthIsAnObjectWithAnOwnTostringAndInheritedValueofMethods() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-23.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsAPositiveNonIntegerEnsureTruncationOccursInTheProperDirection() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-24.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsANegativeNonIntegerEnsureTruncationOccursInTheProperDirection() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-25.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsBoundaryValue232() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-28.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsBoundaryValue2321() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-29.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsANumberValueIs0() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-3.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsANumberValueIs02() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-4.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsANumberValueIs03() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-5.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsANumberValueIsPositive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-6.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsANumberValueIsNegative() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-7.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsANumberValueIsInfinity() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-8.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachValueOfLengthIsANumberValueIsInfinity2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-9.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThrowsTypeerrorIfCallbackfnIsUndefined() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-4-1.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachTheExceptionIsNotThrownIfExceptionWasThrownByStep2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-4-10.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachTheExceptionIsNotThrownIfExceptionWasThrownByStep3() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-4-11.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachCallbackfnIsAFunction() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-4-12.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachCallingWithNoCallbackfnIsTheSameAsPassingUndefinedForCallbackfn() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-4-15.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThrowsReferenceerrorIfCallbackfnIsUnreferenced() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-4-2.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThrowsTypeerrorIfCallbackfnIsNull() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-4-3.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThrowsTypeerrorIfCallbackfnIsBoolean() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-4-4.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThrowsTypeerrorIfCallbackfnIsNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-4-5.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThrowsTypeerrorIfCallbackfnIsString() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-4-6.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThrowsTypeerrorIfCallbackfnIsObjectWithoutCallInternalMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-4-7.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachSideEffectsProducedByStep2AreVisibleWhenAnExceptionOccurs() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-4-8.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachSideEffectsProducedByStep3AreVisibleWhenAnExceptionOccurs() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-4-9.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisargNotPassedToStrictCallbackfn() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-1-s.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisargIsPassed() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-1.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachArrayObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-10.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachStringObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-11.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachBooleanObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-12.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachNumberObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-13.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachTheMathObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-14.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDateObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-15.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachRegexpObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-16.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachTheJsonObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-17.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachErrorObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-18.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachTheArgumentsObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-19.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisargIsObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-2.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachTheGlobalObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-21.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachBooleanPrimitiveCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-22.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachNumberPrimitiveCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-23.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachStringPrimitiveCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-24.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisargNotPassed() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-25.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisargIsArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-3.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisargIsObjectFromObjectTemplatePrototype() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-4.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisargIsObjectFromObjectTemplate() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-5.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisargIsFunction() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-6.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachBuiltInFunctionsCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-7.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachFunctionObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-9.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTConsiderNewElementsAddedToArrayAfterTheCall() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-1.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTVisitDeletedElementsInArrayAfterTheCall() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-2.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTVisitDeletedElementsWhenArrayLengthIsDecreased() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-3.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTConsiderNewlyAddedElementsInSparseArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-4.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachVisitsDeletedElementInArrayAfterTheCallWhenSameIndexIsAlsoPresentInPrototype() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-5.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachConsidersNewValueOfElementsInArrayAfterTheCall() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-7.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachNoObservableEffectsOccurIfLenIs0() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-8.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachModificationsToLengthDonTChangeNumberOfIterations() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-9.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachCallbackfnNotCalledForIndexesNeverBeenAssignedValues() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-1.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDeletingPropertyOfPrototypeCausesPrototypeIndexPropertyNotToBeVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-10.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDeletingPropertyOfPrototypeCausesPrototypeIndexPropertyNotToBeVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-11.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDeletingOwnPropertyWithPrototypePropertyCausesPrototypeIndexPropertyToBeVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-12.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDeletingOwnPropertyWithPrototypePropertyCausesPrototypeIndexPropertyToBeVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-13.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDecreasingLengthOfArrayCausesIndexPropertyNotToBeVisited() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-14.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDecreasingLengthOfArrayWithPrototypePropertyCausesPrototypeIndexPropertyToBeVisited() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-15.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDecreasingLengthOfArrayDoesNotDeleteNonConfigurableProperties() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-16.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachAddedPropertiesInStep2AreVisibleHere() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-2.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDeletedPropertiesInStep2AreVisibleHere() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-3.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachPropertiesAddedIntoOwnObjectAfterCurrentPositionAreVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-4.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachPropertiesAddedIntoOwnObjectAfterCurrentPositionAreVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-5.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachPropertiesCanBeAddedToPrototypeAfterCurrentPositionAreVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-6.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachPropertiesCanBeAddedToPrototypeAfterCurrentPositionAreVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-7.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDeletingOwnPropertyCausesIndexPropertyNotToBeVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-8.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDeletingOwnPropertyCausesIndexPropertyNotToBeVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-b-9.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnDataPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-1.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-10.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedDataPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-11.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-12.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-13.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-14.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsInheritedAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-15.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsInheritedAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-16.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-17.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-18.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionThatOverridesAnInheritedAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-19.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-2.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionThatOverridesAnInheritedAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-20.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsInheritedAccessorPropertyWithoutAGetFunctionOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-21.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsInheritedAccessorPropertyWithoutAGetFunctionOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-22.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisObjectIsAnGlobalObjectWhichContainsIndexProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-23.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisObjectIsTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethodNumberOfArgumentsIsLessThanNumberOfParameters() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-25.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisObjectIsTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethodNumberOfArgumentsEqualsNumberOfParameters() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-26.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisObjectIsTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethodNumberOfArgumentsIsGreaterThanNumberOfParameters() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-27.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementChangedByGetterOnPreviousIterationsIsObservedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-28.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementChangedByGetterOnPreviousIterationsIsObservedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-29.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-3.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachUnnhandledExceptionsHappenedInGetterTerminateIterationOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-30.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachUnnhandledExceptionsHappenedInGetterTerminateIterationOnAnArrayLikeObject2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-31.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedDataPropertyOnAnArray2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-4.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-5.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-6.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsInheritedDataPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-7.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsInheritedDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-8.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementToBeRetrievedIsOwnAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-i-9.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachCallbackfnCalledWithCorrectParameters() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-1.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachCallbackfnIsCalledWith1FormalParameter() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-10.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachCallbackfnIsCalledWith2FormalParameter() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-11.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachCallbackfnIsCalledWith3FormalParameter() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-12.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachCallbackfnThatUsesArguments() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-13.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisOfCallbackfnIsABooleanObjectWhenTIsNotAnObjectTIsABoolean() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-16.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisOfCallbackfnIsANumberObjectWhenTIsNotAnObjectTIsANumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-17.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachThisOfCallbackfnIsAnStringObjectWhenTIsNotAnObjectTIsAString() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-18.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachNonIndexedPropertiesAreNotCalled() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-19.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachCallbackfnTakes3Arguments() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-2.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachCallbackfnCalledWithCorrectParametersThisargIsCorrect() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-20.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachCallbackfnCalledWithCorrectParametersKvalueIsCorrect() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-21.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachCallbackfnCalledWithCorrectParametersTheIndexKIsCorrect() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-22.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachCallbackfnCalledWithCorrectParametersThisObjectOIsCorrect() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-23.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachKValuesArePassedInAscendingNumericOrder() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-4.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachKValuesAreAccessedDuringEachIterationAndNotPriorToStartingTheLoopOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-5.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachArgumentsToCallbackfnAreSelfConsistent() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-6.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachUnhandledExceptionsHappenedInCallbackfnTerminateIteration() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-7.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachElementChangedByCallbackfnOnPreviousIterationsIsObserved() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-8.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachCallbackfnIsCalledWith0FormalParameter() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-7-c-ii-9.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTCallCallbackfnIfLengthIs0EmptyArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-8-1.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachSubclassedArrayWhenLengthIsReduced() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-8-10.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTMutateTheArrayOnWhichItIsCalledOn() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-8-11.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTVisitExpandos() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-8-12.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachUndefinedWillBeReturnedWhenLenIs0() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-8-13.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTCallCallbackfnIfLengthIs0SubclassedArrayLengthOverriddenToNullTypeConversion() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-8-2.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTCallCallbackfnIfLengthIs0SubclassedArrayLengthOverriddenToFalseTypeConversion() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-8-3.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTCallCallbackfnIfLengthIs0SubclassedArrayLengthOverriddenTo0TypeConversion() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-8-4.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTCallCallbackfnIfLengthIs0SubclassedArrayLengthOverriddenTo0TypeConversion2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-8-5.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTCallCallbackfnIfLengthIs0SubclassedArrayLengthOverriddenWithObjWithValueof() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-8-6.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTCallCallbackfnIfLengthIs0SubclassedArrayLengthOverriddenWithObjWOValueofTostring() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-8-7.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTCallCallbackfnIfLengthIs0SubclassedArrayLengthOverriddenWith() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-8-8.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayPrototypeForeachDoesnTCallCallbackfnIfLengthIs0SubclassedArrayLengthOverriddenWith0() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-8-9.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayForeachCanBeFrozenWhileInProgress() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/S15.4.4.18_A1.js", false); } [Fact] [Trait("Category", "15.4.4.18")] public void ArrayForeachCanBeFrozenWhileInProgress2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.18/S15.4.4.18_A2.js", false); } } }
using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis; using Tsarev.Analyzer.TestHelpers; using Xunit; namespace Tsarev.Analyzer.Web.Test { public class AsyncControllerAnalyzerTest : DiagnosticVerifier { //No diagnostics expected to show up [Fact] public void TestEmpty() { var test = @""; VerifyCSharpDiagnostic(test); } [Fact] public void TestControllerByName() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public System.Web.Mvc.ActionResult Method() { return null; } } } }"; VerifyCSharpDiagnostic(test, ExpectAsyncWarning(6, 46, "FooController", "Method")); } [Fact] public void TestExpression() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public System.Web.Mvc.ActionResult Method() { return SomeMethod() ?? View(); } private ActionResult SomeMethod() => null; } } }"; VerifyCSharpDiagnostic(test, ExpectAsyncWarning(6, 46, "FooController", "Method")); } [Fact] public void TestControllerDescedant() { var test = @" namespace ConsoleApplication1 { class UpperClass { class Foo : Controller { public System.Web.Mvc.ActionResult Method() { return null; } } } }"; VerifyCSharpDiagnostic(test, ExpectAsyncWarning(6, 46, "Foo", "Method")); } [Fact] public void TestControllerByNameCorrect() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public Task<ActionResult> Method() { return null; } } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestControllerByNameValueTaskCorrect() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public ValueTask<ActionResult> Method() { return null; } } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestControllerPrivateCorrect() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { private ActionResult Method() { return null; } } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestNoCrashGnericInAnalyzer() { var test = @" using System.Configuration; namespace ConsoleApplication1 { class FooController { public IHttpActionResult GetUsers() { return Ok<IEnumerable<User>>(users); } } }"; VerifyCSharpDiagnostic(test, ExpectAsyncWarning(7, 34, "FooController", "GetUsers")); } [Fact] public void TestNoCrashNotSimpleInAnalyzer() { var test = @" using System.Configuration; namespace ConsoleApplication1 { class FooController { public IHttpActionResult GetUsers() { return ErrorMessage.GetHashCode(); } } }"; VerifyCSharpDiagnostic(test, ExpectAsyncWarning(7, 34, "FooController", "GetUsers")); } [Fact] public void TestControllerTrivialViewCorrect() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public ActionResult Method() { return View(); } } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestControllerTrivialPatialViewCorrect() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public ActionResult Method() { return PartialView(""Test"", 4); } } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestControllerInInterface() { var test = @" public interface IModelDocumentationProvider { string GetDocumentation(MemberInfo member); string GetDocumentation(Type type); }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestEmptyTrivialConst() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public string Method() { return ""some""; } } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestEmptyTrivialVoid() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public void Method() { } } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestControllerTrivialWithArgumentCorrect() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public ActionResult Method() { return View(""ViewName""); } } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestTrivialWithViewBagAssigment() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public ActionResult Method() { ViewBag.Title = ""something""; return View(""ViewName""); } } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestNonTrivialWithViewBagAssigmentAndCall() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public ActionResult Method() { ViewBag.Title = ""something""; LoadEntireWorld(); return View(""ViewName""); } } } }"; VerifyCSharpDiagnostic(test, ExpectAsyncWarning(6, 31, "FooController", "Method")); } [Fact] public void TestIgnoreAbstractMethod() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public abstract ActionResult Method(); } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestIgnorePrivateMethod() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { private string GetUserName() { return User.Identity.Name; } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestAnalyzeGenericClass() { var test = @" namespace ConsoleApplication1 { public abstract class SomeController<TViewModel> : Controller where TViewModel : class { public abstract ActionResult Index(); } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestControllerTrivialArrowCorrect() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public ActionResult Method() => View(); } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestControllerTrivialArrowWithArgumentCorrect() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public ActionResult Method() => View(""ViewName""); } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestControllerTrivialArrayCorrect() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public IEnumerable<int> Get() { return new int[] { 1, 2,}; } } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestControllerDisposeCorrect() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public void Dispose() { return SomeMethod(); } private string SomeMethod() {} } } }"; VerifyCSharpDiagnostic(test); } [Fact] public void TestControllerNonTrivialWithCall() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public ActionResult Method() { return View(SomeMethod()); } private string SomeMethod() {} } } }"; VerifyCSharpDiagnostic(test, ExpectAsyncWarning(6, 31, "FooController", "Method")); } [Fact] public void TestControllerNonTrivialWithCallArrow() { var test = @" namespace ConsoleApplication1 { class UpperClass { class FooController { public ActionResult Method() => View(SomeMethod()); private string SomeMethod() {} } } }"; VerifyCSharpDiagnostic(test, ExpectAsyncWarning(6, 31, "FooController", "Method")); } [Fact] public void TestControllerNonTrivialWithException() { var test = @" class FooController { public DeliveryInfo[] Method(long messageId) { using (var client = new MTSCommunicatorM2MXMLAPI()) { System.Net.ServicePointManager.Expect100Continue = false; string passwordHash = CalculateMD5Hash(password); var result = client.GetMessageStatus(messageId, login, passwordHash); return result; } } } }"; VerifyCSharpDiagnostic(test, ExpectAsyncWarning(3, 31, "FooController", "Method")); } [Fact(Skip = "need to understand that local variables actually constant")] public void TestControllerTrivialWithPartialView() { var test = @" class FooController { public ActionResult SelectView(bool isFirstView) { return isFirstView ? PartialView(""First"") : PartialView(""Second""); } }"; VerifyCSharpDiagnostic(test); } [Fact(Skip = "need to understand that local variables actually constant")] public void TestControllerTrivialWithFile() { var test = @" class FooController { public ActionResult DownLoadFile() { var data = new [] {1, 2, 3}; return File(data, ""application/vnd.ms-excel"", ""test.txt""); } }"; VerifyCSharpDiagnostic(test); } [Fact(Skip = "need to understand that local variables actually constant")] public void TestControllerTrivialWithTempData() { var test = @" class FooController { public ActionResult GetFromTempData() { return View(""ViewName"", TempData[1]); } }"; VerifyCSharpDiagnostic(test); } private DiagnosticResult ExpectAsyncWarning(int line, int column, string controller, string method) => new DiagnosticResult { Id = nameof(AsyncControllerAnalyzer), Message = $"Controller '{controller}' contains method '{method}' that executes synchronously. Consider converting to method that returns Task<T>", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", line, column) } }; protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() => new AsyncControllerAnalyzer(); } }
// 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; namespace System.IO { /// <summary> /// Provides a string parser that may be used instead of String.Split /// to avoid unnecessary string and array allocations. /// </summary> internal struct StringParser { /// <summary>The string being parsed.</summary> private readonly string _buffer; /// <summary>The separator character used to separate subcomponents of the larger string.</summary> private readonly char _separator; /// <summary>true if empty subcomponents should be skipped; false to treat them as valid entries.</summary> private readonly bool _skipEmpty; /// <summary>The starting index from which to parse the current entry.</summary> private int _startIndex; /// <summary>The ending index that represents the next index after the last character that's part of the current entry.</summary> private int _endIndex; /// <summary>Initialize the StringParser.</summary> /// <param name="buffer">The string to parse.</param> /// <param name="separator">The separator character used to separate subcomponents of <paramref name="buffer"/>.</param> /// <param name="skipEmpty">true if empty subcomponents should be skipped; false to treat them as valid entries. Defaults to false.</param> public StringParser(string buffer, char separator, bool skipEmpty = false) { if (buffer == null) { throw new ArgumentNullException("buffer"); } _buffer = buffer; _separator = separator; _skipEmpty = skipEmpty; _startIndex = -1; _endIndex = -1; } /// <summary>Moves to the next component of the string.</summary> /// <returns>true if there is a next component to be parsed; otherwise, false.</returns> public bool MoveNext() { if (_buffer == null) { throw new InvalidOperationException(); } while (true) { if (_endIndex >= _buffer.Length) { _startIndex = _endIndex; return false; } int nextSeparator = _buffer.IndexOf(_separator, _endIndex + 1); _startIndex = _endIndex + 1; _endIndex = nextSeparator >= 0 ? nextSeparator : _buffer.Length; if (!_skipEmpty || _endIndex > _startIndex + 1) { return true; } } } /// <summary> /// Moves to the next component of the string. If there isn't one, it throws an exception. /// </summary> public void MoveNextOrFail() { if (!MoveNext()) { ThrowForInvalidData(); } } /// <summary> /// Moves to the next component of the string and returns it as a string. /// </summary> /// <returns></returns> public string MoveAndExtractNext() { MoveNextOrFail(); return _buffer.Substring(_startIndex, _endIndex - _startIndex); } /// <summary> /// Gets the current subcomponent of the string as a string. /// </summary> public string ExtractCurrent() { if (_buffer == null || _startIndex == -1) { throw new InvalidOperationException(); } return _buffer.Substring(_startIndex, _endIndex - _startIndex); } /// <summary>Moves to the next component and parses it as an Int32.</summary> public unsafe int ParseNextInt32() { MoveNextOrFail(); bool negative = false; int result = 0; fixed (char* bufferPtr = _buffer) { char* p = bufferPtr + _startIndex; char* end = bufferPtr + _endIndex; if (p == end) { ThrowForInvalidData(); } if (*p == '-') { negative = true; p++; if (p == end) { ThrowForInvalidData(); } } while (p != end) { int d = *p - '0'; if (d < 0 || d > 9) { ThrowForInvalidData(); } result = checked((result * 10) + d); p++; } } if (negative) { result *= -1; } Debug.Assert(result == int.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result"); return result; } /// <summary>Moves to the next component and parses it as an Int64.</summary> public unsafe long ParseNextInt64() { MoveNextOrFail(); bool negative = false; long result = 0; fixed (char* bufferPtr = _buffer) { char* p = bufferPtr + _startIndex; char* end = bufferPtr + _endIndex; if (p == end) { ThrowForInvalidData(); } if (*p == '-') { negative = true; p++; if (p == end) { ThrowForInvalidData(); } } while (p != end) { int d = *p - '0'; if (d < 0 || d > 9) { ThrowForInvalidData(); } result = checked((result * 10) + d); p++; } } if (negative) { result *= -1; } Debug.Assert(result == long.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result"); return result; } /// <summary>Moves to the next component and parses it as a UInt32.</summary> public unsafe uint ParseNextUInt32() { MoveNextOrFail(); if (_startIndex == _endIndex) { ThrowForInvalidData(); } uint result = 0; fixed (char* bufferPtr = _buffer) { char* p = bufferPtr + _startIndex; char* end = bufferPtr + _endIndex; while (p != end) { int d = *p - '0'; if (d < 0 || d > 9) { ThrowForInvalidData(); } result = (uint)checked((result * 10) + d); p++; } } Debug.Assert(result == uint.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result"); return result; } /// <summary>Moves to the next component and parses it as a UInt64.</summary> public unsafe ulong ParseNextUInt64() { MoveNextOrFail(); ulong result = 0; fixed (char* bufferPtr = _buffer) { char* p = bufferPtr + _startIndex; char* end = bufferPtr + _endIndex; while (p != end) { int d = *p - '0'; if (d < 0 || d > 9) { ThrowForInvalidData(); } result = checked((result * 10ul) + (ulong)d); p++; } } Debug.Assert(result == ulong.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result"); return result; } /// <summary>Moves to the next component and parses it as a Char.</summary> public char ParseNextChar() { MoveNextOrFail(); if (_endIndex - _startIndex != 1) { ThrowForInvalidData(); } char result = _buffer[_startIndex]; Debug.Assert(result == char.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result"); return result; } internal delegate T ParseRawFunc<T>(string buffer, ref int startIndex, ref int endIndex); /// <summary> /// Moves to the next component and hands the raw buffer and indexing data to a selector function /// that can validate and return the appropriate data from the component. /// </summary> internal T ParseRaw<T>(ParseRawFunc<T> selector) { MoveNextOrFail(); return selector(_buffer, ref _startIndex, ref _endIndex); } /// <summary>Throws unconditionally for invalid data.</summary> private static void ThrowForInvalidData() { throw new InvalidDataException(); } } }
#region License // // Copyright (c) 2018, Fluent Migrator Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Linq; using FluentMigrator.Runner.Generators.Oracle; using NUnit.Framework; using Shouldly; namespace FluentMigrator.Tests.Unit.Generators.Oracle { [TestFixture] public abstract class OracleBaseColumnTests<TGenerator> : BaseColumnTests where TGenerator : OracleGenerator, new() { protected TGenerator Generator; [SetUp] public void Setup() { Generator = new TGenerator(); } [Test] public override void CanCreateNullableColumnWithCustomDomainTypeAndCustomSchema() { var expression = GeneratorTestHelper.GetCreateColumnExpressionWithNullableCustomType(); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD TestColumn1 MyDomainType"); } [Test] public override void CanCreateNullableColumnWithCustomDomainTypeAndDefaultSchema() { var expression = GeneratorTestHelper.GetCreateColumnExpressionWithNullableCustomType(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestTable1 ADD TestColumn1 MyDomainType"); } [Test] public override void CanAlterColumnWithCustomSchema() { var expression = GeneratorTestHelper.GetAlterColumnExpression(); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestSchema.TestTable1 MODIFY TestColumn1 NVARCHAR2(20) NOT NULL"); } [Test] public override void CanAlterColumnWithDefaultSchema() { var expression = GeneratorTestHelper.GetAlterColumnExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestTable1 MODIFY TestColumn1 NVARCHAR2(20) NOT NULL"); } [Test] public abstract override void CanCreateAutoIncrementColumnWithCustomSchema(); [Test] public abstract override void CanCreateAutoIncrementColumnWithDefaultSchema(); [Test] public override void CanCreateColumnWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateColumnExpression(); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD TestColumn1 NVARCHAR2(5) NOT NULL"); } [Test] public override void CanCreateColumnWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateColumnExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestTable1 ADD TestColumn1 NVARCHAR2(5) NOT NULL"); } [Test] public override void CanCreateColumnWithSystemMethodAndCustomSchema() { var expressions = GeneratorTestHelper.GetCreateColumnWithSystemMethodExpression("TestSchema"); var result = string.Join(Environment.NewLine, expressions.Select(x => (string)Generator.Generate((dynamic)x))); result.ShouldBe( @"ALTER TABLE TestSchema.TestTable1 ADD TestColumn1 TIMESTAMP(4)" + Environment.NewLine + "UPDATE TestSchema.TestTable1 SET TestColumn1 = LOCALTIMESTAMP WHERE 1 = 1"); } [Test] public override void CanCreateColumnWithSystemMethodAndDefaultSchema() { var expressions = GeneratorTestHelper.GetCreateColumnWithSystemMethodExpression(); var result = string.Join(Environment.NewLine, expressions.Select(x => (string)Generator.Generate((dynamic)x))); result.ShouldBe( @"ALTER TABLE TestTable1 ADD TestColumn1 TIMESTAMP(4)" + Environment.NewLine + "UPDATE TestTable1 SET TestColumn1 = LOCALTIMESTAMP WHERE 1 = 1"); } [Test] public override void CanCreateDecimalColumnWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateDecimalColumnExpression(); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD TestColumn1 NUMBER(19,2) NOT NULL"); } [Test] public override void CanCreateDecimalColumnWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateDecimalColumnExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestTable1 ADD TestColumn1 NUMBER(19,2) NOT NULL"); } [Test] public override void CanDropColumnWithCustomSchema() { var expression = GeneratorTestHelper.GetDeleteColumnExpression(); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestSchema.TestTable1 DROP COLUMN TestColumn1"); } [Test] public override void CanDropColumnWithDefaultSchema() { var expression = GeneratorTestHelper.GetDeleteColumnExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestTable1 DROP COLUMN TestColumn1"); } [Test] public override void CanDropMultipleColumnsWithCustomSchema() { var expression = GeneratorTestHelper.GetDeleteColumnExpression(new[] { "TestColumn1", "TestColumn2" }); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe( "ALTER TABLE TestSchema.TestTable1 DROP COLUMN TestColumn1" + Environment.NewLine + ";" + Environment.NewLine + "ALTER TABLE TestSchema.TestTable1 DROP COLUMN TestColumn2"); } [Test] public override void CanDropMultipleColumnsWithDefaultSchema() { var expression = GeneratorTestHelper.GetDeleteColumnExpression(new[] { "TestColumn1", "TestColumn2" }); var result = Generator.Generate(expression); result.ShouldBe( "ALTER TABLE TestTable1 DROP COLUMN TestColumn1" + Environment.NewLine + ";" + Environment.NewLine + "ALTER TABLE TestTable1 DROP COLUMN TestColumn2"); } [Test] public override void CanRenameColumnWithCustomSchema() { var expression = GeneratorTestHelper.GetRenameColumnExpression(); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestSchema.TestTable1 RENAME COLUMN TestColumn1 TO TestColumn2"); } [Test] public override void CanRenameColumnWithDefaultSchema() { var expression = GeneratorTestHelper.GetRenameColumnExpression(); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestTable1 RENAME COLUMN TestColumn1 TO TestColumn2"); } [Test] public void CanCreateColumnWithDefaultValue() { var expression = GeneratorTestHelper.GetCreateColumnExpression(); expression.Column.DefaultValue = 1; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestTable1 ADD TestColumn1 NVARCHAR2(5) DEFAULT 1 NOT NULL"); } [Test] public void CanCreateColumnWithDefaultStringValue() { var expression = GeneratorTestHelper.GetCreateColumnExpression(); expression.Column.DefaultValue = "1"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestTable1 ADD TestColumn1 NVARCHAR2(5) DEFAULT '1' NOT NULL"); } [Test] public void CanCreateColumnWithDefaultSystemMethodNewGuid() { var expression = GeneratorTestHelper.GetCreateColumnExpression(); expression.Column.DefaultValue = SystemMethods.NewGuid; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestTable1 ADD TestColumn1 NVARCHAR2(5) DEFAULT sys_guid() NOT NULL"); } [Test] public void CanCreateColumnWithDefaultSystemMethodCurrentDateTime() { var expression = GeneratorTestHelper.GetCreateColumnExpression(); expression.Column.DefaultValue = SystemMethods.CurrentDateTime; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestTable1 ADD TestColumn1 NVARCHAR2(5) DEFAULT LOCALTIMESTAMP NOT NULL"); } [Test] public void CanCreateColumnWithDefaultSystemMethodCurrentUser() { var expression = GeneratorTestHelper.GetCreateColumnExpression(); expression.Column.DefaultValue = SystemMethods.CurrentUser; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE TestTable1 ADD TestColumn1 NVARCHAR2(5) DEFAULT USER NOT NULL"); } } }
using static DiffMatchPatch.Operation; namespace DiffMatchPatch; public static class PatchList { internal static string NullPadding(short paddingLength = 4) => new(Enumerable.Range(1, paddingLength).Select(i => (char)i).ToArray()); /// <summary> /// Add some padding on text start and end so that edges can match something. /// Intended to be called only from within patch_apply. /// </summary> /// <param name="patches"></param> /// <param name="patchMargin"></param> /// <returns>The padding string added to each side.</returns> internal static IEnumerable<Patch> AddPadding(this IEnumerable<Patch> patches, string padding) { var paddingLength = padding.Length; var enumerator = patches.GetEnumerator(); if (!enumerator.MoveNext()) yield break; Patch current = enumerator.Current.Bump(paddingLength); Patch next = current; bool isfirst = true; while (true) { var hasnext = enumerator.MoveNext(); if (hasnext) next = enumerator.Current.Bump(paddingLength); yield return (isfirst, hasnext) switch { (true, false) => current.AddPadding(padding), // list has only one patch (true, true) => current.AddPaddingInFront(padding), (false, true) => current, (false, false) => current.AddPaddingAtEnd(padding) }; isfirst = false; if (!hasnext) yield break; current = next; } } /// <summary> /// Take a list of patches and return a textual representation. /// </summary> /// <param name="patches"></param> /// <returns></returns> public static string ToText(this IEnumerable<Patch> patches) => patches.Aggregate(new StringBuilder(), (sb, patch) => sb.Append(patch)).ToString(); static readonly Regex PatchHeader = new("^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@$"); /// <summary> /// Parse a textual representation of patches and return a List of Patch /// objects.</summary> /// <param name="text"></param> /// <returns></returns> public static ImmutableList<Patch> Parse(string text) => ParseImpl(text).ToImmutableList(); static IEnumerable<Patch> ParseImpl(string text) { if (text.Length == 0) { yield break; } var lines = text.SplitBy('\n').ToArray(); var index = 0; while (index < lines.Length) { var line = lines[index]; var m = PatchHeader.Match(line); if (!m.Success) { throw new ArgumentException("Invalid patch string: " + line); } (var start1, var length1) = m.GetStartAndLength(1, 2); (var start2, var length2) = m.GetStartAndLength(3, 4); index++; IEnumerable<Diff> CreateDiffs() { while (index < lines.Length) { line = lines[index]; if (!string.IsNullOrEmpty(line)) { var sign = line[0]; if (sign == '@') // Start of next patch. break; yield return sign switch { '+' => Diff.Insert(line[1..].Replace("+", "%2b").UrlDecoded()), '-' => Diff.Delete(line[1..].Replace("+", "%2b").UrlDecoded()), _ => Diff.Equal(line[1..].Replace("+", "%2b").UrlDecoded()) }; } index++; } } yield return new Patch ( start1, length1, start2, length2, CreateDiffs().ToImmutableList() ); } } static (int start, int length) GetStartAndLength(this Match m, int startIndex, int lengthIndex) { var lengthStr = m.Groups[lengthIndex].Value; var value = Convert.ToInt32(m.Groups[startIndex].Value); return lengthStr switch { "0" => (value, 0), "" => (value - 1, 1), _ => (value - 1, Convert.ToInt32(lengthStr)) }; } /// <summary> /// Merge a set of patches onto the text. Return a patched text, as well /// as an array of true/false values indicating which patches were applied.</summary> /// <param name="patches"></param> /// <param name="text">Old text</param> /// <returns>Two element Object array, containing the new text and an array of /// bool values.</returns> public static (string newText, bool[] results) Apply(this IEnumerable<Patch> patches, string text) => Apply(patches, text, MatchSettings.Default, PatchSettings.Default); public static (string newText, bool[] results) Apply(this IEnumerable<Patch> patches, string text, MatchSettings matchSettings) => Apply(patches, text, matchSettings, PatchSettings.Default); /// <summary> /// Merge a set of patches onto the text. Return a patched text, as well /// as an array of true/false values indicating which patches were applied.</summary> /// <param name="patches"></param> /// <param name="text">Old text</param> /// <param name="matchSettings"></param> /// <param name="settings"></param> /// <returns>Two element Object array, containing the new text and an array of /// bool values.</returns> public static (string newText, bool[] results) Apply(this IEnumerable<Patch> input, string text, MatchSettings matchSettings, PatchSettings settings) { if (!input.Any()) { return (text, new bool[0]); } var nullPadding = NullPadding(settings.PatchMargin); text = nullPadding + text + nullPadding; var patches = input.AddPadding(nullPadding).SplitMax().ToList(); var x = 0; // delta keeps track of the offset between the expected and actual // location of the previous patch. If there are patches expected at // positions 10 and 20, but the first patch was found at 12, delta is 2 // and the second patch has an effective expected position of 22. var delta = 0; var results = new bool[patches.Count]; foreach (var aPatch in patches) { var expectedLoc = aPatch.Start2 + delta; var text1 = aPatch.Diffs.Text1(); int startLoc; var endLoc = -1; if (text1.Length > Constants.MatchMaxBits) { // patch_splitMax will only provide an oversized pattern // in the case of a monster delete. startLoc = text.FindBestMatchIndex(text1.Substring(0, Constants.MatchMaxBits), expectedLoc, matchSettings); if (startLoc != -1) { endLoc = text.FindBestMatchIndex( text1[^Constants.MatchMaxBits..], expectedLoc + text1.Length - Constants.MatchMaxBits, matchSettings ); if (endLoc == -1 || startLoc >= endLoc) { // Can't find valid trailing context. Drop this patch. startLoc = -1; } } } else { startLoc = text.FindBestMatchIndex(text1, expectedLoc, matchSettings); } if (startLoc == -1) { // No match found. :( results[x] = false; // Subtract the delta for this failed patch from subsequent patches. delta -= aPatch.Length2 - aPatch.Length1; } else { // Found a match. :) results[x] = true; delta = startLoc - expectedLoc; int actualEndLoc; if (endLoc == -1) { actualEndLoc = Math.Min(startLoc + text1.Length, text.Length); } else { actualEndLoc = Math.Min(endLoc + Constants.MatchMaxBits, text.Length); } var text2 = text[startLoc..actualEndLoc]; if (text1 == text2) { // Perfect match, just shove the Replacement text in. text = text.Substring(0, startLoc) + aPatch.Diffs.Text2() + text[(startLoc + text1.Length)..]; } else { // Imperfect match. Run a diff to get a framework of equivalent // indices. var diffs = Diff.Compute(text1, text2, 0f, false); if (text1.Length > Constants.MatchMaxBits && diffs.Levenshtein() / (float)text1.Length > settings.PatchDeleteThreshold) { // The end points match, but the content is unacceptably bad. results[x] = false; } else { diffs = diffs.CleanupSemanticLossless().ToImmutableList(); var index1 = 0; foreach (var aDiff in aPatch.Diffs) { if (aDiff.Operation != Equal) { var index2 = diffs.FindEquivalentLocation2(index1); if (aDiff.Operation == Insert) { // Insertion text = text.Insert(startLoc + index2, aDiff.Text); } else if (aDiff.Operation == Delete) { // Deletion text = text.Remove(startLoc + index2, diffs.FindEquivalentLocation2(index1 + aDiff.Text.Length) - index2); } } if (aDiff.Operation != Delete) { index1 += aDiff.Text.Length; } } } } } x++; } // Strip the padding off. text = text.Substring(nullPadding.Length, text.Length - 2 * nullPadding.Length); return (text, results); } /// <summary> /// Look through the patches and break up any which are longer than the /// maximum limit of the match algorithm. /// Intended to be called only from within patch_apply. /// </summary> /// <param name="patches"></param> /// <param name="patchMargin"></param> internal static IEnumerable<Patch> SplitMax(this IEnumerable<Patch> patches, short patchMargin = 4) { var patchSize = Constants.MatchMaxBits; foreach (var patch in patches) { if (patch.Length1 <= patchSize) { yield return patch; continue; } var bigpatch = patch; // Remove the big old patch. (var start1, _, var start2, _, var diffs) = bigpatch; var precontext = string.Empty; while (diffs.Any()) { // Create one of several smaller patches. (int s1, int l1, int s2, int l2, List<Diff> thediffs) = (start1 - precontext.Length, precontext.Length, start2 - precontext.Length, precontext.Length, new List<Diff>()); var empty = true; if (precontext.Length != 0) { thediffs.Add(Diff.Equal(precontext)); } while (diffs.Any() && l1 < patchSize - patchMargin) { var first = diffs[0]; var diffType = diffs[0].Operation; var diffText = diffs[0].Text; if (first.Operation == Insert) { // Insertions are harmless. l2 += diffText.Length; start2 += diffText.Length; thediffs.Add(Diff.Insert(diffText)); diffs = diffs.RemoveAt(0); empty = false; } else if (first.IsLargeDelete(2 * patchSize) && thediffs.Count == 1 && thediffs[0].Operation == Equal) { // This is a large deletion. Let it pass in one chunk. l1 += diffText.Length; start1 += diffText.Length; thediffs.Add(Diff.Delete(diffText)); diffs = diffs.RemoveAt(0); empty = false; } else { // Deletion or equality. Only take as much as we can stomach. var cutoff = diffText.Substring(0, Math.Min(diffText.Length, patchSize - l1 - patchMargin)); l1 += cutoff.Length; start1 += cutoff.Length; if (diffType == Equal) { l2 += cutoff.Length; start2 += cutoff.Length; } else { empty = false; } thediffs.Add(Diff.Create(diffType, cutoff)); if (cutoff == first.Text) { diffs = diffs.RemoveAt(0); } else { diffs = diffs.RemoveAt(0).Insert(0, first with { Text = first.Text[cutoff.Length..] }); } } } // Compute the head context for the next patch. precontext = thediffs.Text2(); // if (thediffs.Text2() != precontext) throw new E precontext = precontext[Math.Max(0, precontext.Length - patchMargin)..]; // Append the end context for this patch. var text1 = diffs.Text1(); var postcontext = text1.Length > patchMargin ? text1.Substring(0, patchMargin) : text1; if (postcontext.Length != 0) { l1 += postcontext.Length; l2 += postcontext.Length; var lastDiff = thediffs.Last(); if (thediffs.Any() && lastDiff.Operation == Equal) { thediffs[^1] = lastDiff.Append(postcontext); } else { thediffs.Add(Diff.Equal(postcontext)); } } if (!empty) { yield return new Patch(s1, l1, s2, l2, thediffs.ToImmutableList()); } } } } }
/* * 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.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Resource; using Apache.Ignite.Core.Tests.Cache; using NUnit.Framework; /// <summary> /// <see cref="IMessaging"/> tests. /// </summary> public sealed class MessagingTest { /** */ private IIgnite _grid1; /** */ private IIgnite _grid2; /** */ private IIgnite _grid3; /** */ private static int _messageId; /** Objects to test against. */ private static readonly object[] Objects = { // Primitives. null, "string topic", Guid.NewGuid(), DateTime.Now, byte.MinValue, short.MaxValue, // Enums. CacheMode.Local, GCCollectionMode.Forced, // Objects. new CacheTestKey(25), new IgniteGuid(Guid.NewGuid(), 123), }; /// <summary> /// Executes before each test. /// </summary> [SetUp] public void SetUp() { _grid1 = Ignition.Start(GetConfiguration("grid-1")); _grid2 = Ignition.Start(GetConfiguration("grid-2")); _grid3 = Ignition.Start(GetConfiguration("grid-3")); Assert.AreEqual(3, _grid1.GetCluster().GetNodes().Count); } /// <summary> /// Executes after each test. /// </summary> [TearDown] public void TearDown() { try { TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3); MessagingTestHelper.AssertFailures(); } finally { // Stop all grids between tests to drop any hanging messages Ignition.StopAll(true); } } /// <summary> /// Tests that any data type can be used as a message. /// </summary> [Test] public void TestMessageDataTypes() { var topic = "dataTypes"; object lastMsg = null; var evt = new AutoResetEvent(false); var messaging1 = _grid1.GetMessaging(); var messaging2 = _grid2.GetMessaging(); var listener = new MessageListener<object>((nodeId, msg) => { lastMsg = msg; evt.Set(); return true; }); messaging1.LocalListen(listener, topic); foreach (var msg in Objects.Where(x => x != null)) { messaging2.Send(msg, topic); evt.WaitOne(500); Assert.AreEqual(msg, lastMsg); } messaging1.StopLocalListen(listener, topic); } /// <summary> /// Tests LocalListen. /// </summary> [Test] public void TestLocalListen() { TestLocalListen(NextId()); foreach (var topic in Objects) { TestLocalListen(topic); } } /// <summary> /// Tests LocalListen. /// </summary> [SuppressMessage("ReSharper", "AccessToModifiedClosure")] private void TestLocalListen(object topic) { var messaging = _grid1.GetMessaging(); var listener = MessagingTestHelper.GetListener(); messaging.LocalListen(listener, topic); // Test sending CheckSend(topic); CheckSend(topic, _grid2); CheckSend(topic, _grid3); // Test different topic CheckNoMessage(NextId()); CheckNoMessage(NextId(), _grid2); // Test multiple subscriptions for the same filter messaging.LocalListen(listener, topic); messaging.LocalListen(listener, topic); CheckSend(topic, repeatMultiplier: 3); // expect all messages repeated 3 times messaging.StopLocalListen(listener, topic); CheckSend(topic, repeatMultiplier: 2); // expect all messages repeated 2 times messaging.StopLocalListen(listener, topic); CheckSend(topic); // back to 1 listener // Test message type mismatch var ex = Assert.Throws<IgniteException>(() => messaging.Send(1.1, topic)); Assert.AreEqual("Unable to cast object of type 'System.Double' to type 'System.String'.", ex.Message); // Test end listen MessagingTestHelper.ListenResult = false; CheckSend(topic, single: true); // we'll receive one more and then unsubscribe because of delegate result. CheckNoMessage(topic); // Start again MessagingTestHelper.ListenResult = true; messaging.LocalListen(listener, topic); CheckSend(topic); // Stop messaging.StopLocalListen(listener, topic); CheckNoMessage(topic); } /// <summary> /// Tests LocalListen with projection. /// </summary> [Test] public void TestLocalListenProjection() { TestLocalListenProjection(NextId()); TestLocalListenProjection("prj"); foreach (var topic in Objects) { TestLocalListenProjection(topic); } } /// <summary> /// Tests LocalListen with projection. /// </summary> private void TestLocalListenProjection(object topic) { var grid3GotMessage = false; var grid3Listener = new MessageListener<string>((id, x) => { grid3GotMessage = true; return true; }); _grid3.GetMessaging().LocalListen(grid3Listener, topic); var clusterMessaging = _grid1.GetCluster().ForNodes(_grid1.GetCluster().GetLocalNode(), _grid2.GetCluster().GetLocalNode()).GetMessaging(); var clusterListener = MessagingTestHelper.GetListener(); clusterMessaging.LocalListen(clusterListener, topic); CheckSend(msg: clusterMessaging, topic: topic); Assert.IsFalse(grid3GotMessage, "Grid3 should not get messages"); CheckSend(grid: _grid2, msg: clusterMessaging, topic: topic); Assert.IsFalse(grid3GotMessage, "Grid3 should not get messages"); clusterMessaging.StopLocalListen(clusterListener, topic); _grid3.GetMessaging().StopLocalListen(grid3Listener, topic); } /// <summary> /// Tests LocalListen in multithreaded mode. /// </summary> [Test] [SuppressMessage("ReSharper", "AccessToModifiedClosure")] [Category(TestUtils.CategoryIntensive)] public void TestLocalListenMultithreaded() { const int threadCnt = 20; const int runSeconds = 20; var messaging = _grid1.GetMessaging(); var senders = TaskRunner.Run(() => TestUtils.RunMultiThreaded(() => { messaging.Send(NextMessage()); Thread.Sleep(50); }, threadCnt, runSeconds)); var sharedReceived = 0; var sharedListener = new MessageListener<string>((id, x) => { Interlocked.Increment(ref sharedReceived); Thread.MemoryBarrier(); return true; }); TestUtils.RunMultiThreaded(() => { // Check that listen/stop work concurrently messaging.LocalListen(sharedListener); for (int i = 0; i < 100; i++) { messaging.LocalListen(sharedListener); messaging.StopLocalListen(sharedListener); } var localReceived = 0; var stopLocal = 0; var localListener = new MessageListener<string>((id, x) => { Interlocked.Increment(ref localReceived); Thread.MemoryBarrier(); return Thread.VolatileRead(ref stopLocal) == 0; }); messaging.LocalListen(localListener); Thread.Sleep(100); Thread.VolatileWrite(ref stopLocal, 1); Thread.Sleep(1000); var result = Thread.VolatileRead(ref localReceived); Thread.Sleep(100); // Check that unsubscription worked properly Assert.AreEqual(result, Thread.VolatileRead(ref localReceived)); messaging.StopLocalListen(sharedListener); }, threadCnt, runSeconds); senders.Wait(); Thread.Sleep(100); var sharedResult = Thread.VolatileRead(ref sharedReceived); messaging.Send(NextMessage()); Thread.Sleep(MessagingTestHelper.SleepTimeout); // Check that unsubscription worked properly Assert.AreEqual(sharedResult, Thread.VolatileRead(ref sharedReceived)); } /// <summary> /// Tests RemoteListen. /// </summary> [Test] public void TestRemoteListen([Values(true, false)] bool async) { TestRemoteListen(NextId(), async); foreach (var topic in Objects) { TestRemoteListen(topic, async); } } /// <summary> /// Tests RemoteListen. /// </summary> private void TestRemoteListen(object topic, bool async = false) { var messaging =_grid1.GetMessaging(); var listener = MessagingTestHelper.GetListener(); var listenId = async ? messaging.RemoteListenAsync(listener, topic).Result : messaging.RemoteListen(listener, topic); // Test sending CheckSend(topic, msg: messaging, remoteListen: true); // Test different topic CheckNoMessage(NextId()); // Test multiple subscriptions for the same filter var listenId2 = async ? messaging.RemoteListenAsync(listener, topic).Result : messaging.RemoteListen(listener, topic); CheckSend(topic, msg: messaging, remoteListen: true, repeatMultiplier: 2); // expect twice the messages if (async) messaging.StopRemoteListenAsync(listenId2).Wait(); else messaging.StopRemoteListen(listenId2); CheckSend(topic, msg: messaging, remoteListen: true); // back to normal after unsubscription // Test message type mismatch var ex = Assert.Throws<IgniteException>(() => messaging.Send(1.1, topic)); Assert.AreEqual("Unable to cast object of type 'System.Double' to type 'System.String'.", ex.Message); // Test end listen if (async) messaging.StopRemoteListenAsync(listenId).Wait(); else messaging.StopRemoteListen(listenId); CheckNoMessage(topic); } /// <summary> /// Tests RemoteListen with a projection. /// </summary> [Test] public void TestRemoteListenProjection() { TestRemoteListenProjection(NextId()); foreach (var topic in Objects) { TestRemoteListenProjection(topic); } } /// <summary> /// Tests RemoteListen with a projection. /// </summary> private void TestRemoteListenProjection(object topic) { var clusterMessaging = _grid1.GetCluster().ForNodes(_grid1.GetCluster().GetLocalNode(), _grid2.GetCluster().GetLocalNode()).GetMessaging(); var clusterListener = MessagingTestHelper.GetListener(); var listenId = clusterMessaging.RemoteListen(clusterListener, topic); CheckSend(msg: clusterMessaging, topic: topic, remoteListen: true); clusterMessaging.StopRemoteListen(listenId); CheckNoMessage(topic); } /// <summary> /// Tests LocalListen in multithreaded mode. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestRemoteListenMultithreaded() { const int threadCnt = 20; const int runSeconds = 20; var messaging = _grid1.GetMessaging(); var senders = TaskRunner.Run(() => TestUtils.RunMultiThreaded(() => { MessagingTestHelper.ClearReceived(int.MaxValue); messaging.Send(NextMessage()); Thread.Sleep(50); }, threadCnt, runSeconds)); var sharedListener = MessagingTestHelper.GetListener(); for (int i = 0; i < 100; i++) messaging.RemoteListen(sharedListener); // add some listeners to be stopped by filter result TestUtils.RunMultiThreaded(() => { // Check that listen/stop work concurrently messaging.StopRemoteListen(messaging.RemoteListen(sharedListener)); }, threadCnt, runSeconds / 2); MessagingTestHelper.ListenResult = false; messaging.Send(NextMessage()); // send a message to make filters return false Thread.Sleep(MessagingTestHelper.SleepTimeout); // wait for all to unsubscribe MessagingTestHelper.ListenResult = true; senders.Wait(); // wait for senders to stop MessagingTestHelper.ClearReceived(int.MaxValue); var lastMsg = NextMessage(); messaging.Send(lastMsg); Thread.Sleep(MessagingTestHelper.SleepTimeout); // Check that unsubscription worked properly var sharedResult = MessagingTestHelper.ReceivedMessages.ToArray(); if (sharedResult.Length != 0) { Assert.Fail("Unexpected messages ({0}): {1}; last sent message: {2}", sharedResult.Length, string.Join(",", sharedResult), lastMsg); } } /// <summary> /// Sends messages in various ways and verefies correct receival. /// </summary> /// <param name="topic">Topic.</param> /// <param name="grid">The grid to use.</param> /// <param name="msg">Messaging to use.</param> /// <param name="remoteListen">Whether to expect remote listeners.</param> /// <param name="single">When true, only check one message.</param> /// <param name="repeatMultiplier">Expected message count multiplier.</param> private void CheckSend(object topic = null, IIgnite grid = null, IMessaging msg = null, bool remoteListen = false, bool single = false, int repeatMultiplier = 1) { IClusterGroup cluster; if (msg != null) cluster = msg.ClusterGroup; else { grid = grid ?? _grid1; msg = grid.GetMessaging(); cluster = grid.GetCluster().ForLocal(); } // Messages will repeat due to multiple nodes listening var expectedRepeat = repeatMultiplier * (remoteListen ? cluster.GetNodes().Count : 1); var messages = Enumerable.Range(1, 10).Select(x => NextMessage()).OrderBy(x => x).ToList(); // Single message MessagingTestHelper.ClearReceived(expectedRepeat); msg.Send(messages[0], topic); MessagingTestHelper.VerifyReceive(cluster, messages.Take(1), m => m.ToList(), expectedRepeat); if (single) return; // Multiple messages (receive order is undefined) MessagingTestHelper.ClearReceived(messages.Count * expectedRepeat); msg.SendAll(messages, topic); MessagingTestHelper.VerifyReceive(cluster, messages, m => m.OrderBy(x => x), expectedRepeat); // Multiple messages, ordered MessagingTestHelper.ClearReceived(messages.Count * expectedRepeat); messages.ForEach(x => msg.SendOrdered(x, topic, MessagingTestHelper.MessageTimeout)); if (remoteListen) // in remote scenario messages get mixed up due to different timing on different nodes MessagingTestHelper.VerifyReceive(cluster, messages, m => m.OrderBy(x => x), expectedRepeat); else MessagingTestHelper.VerifyReceive(cluster, messages, m => m.Reverse(), expectedRepeat); } /// <summary> /// Checks that no message has arrived. /// </summary> private void CheckNoMessage(object topic, IIgnite grid = null) { // this will result in an exception in case of a message MessagingTestHelper.ClearReceived(0); (grid ?? _grid1).GetMessaging().SendAll(NextMessage(), topic); Thread.Sleep(MessagingTestHelper.SleepTimeout); MessagingTestHelper.AssertFailures(); } /// <summary> /// Gets the Ignite configuration. /// </summary> private static IgniteConfiguration GetConfiguration(string name) { return new IgniteConfiguration(TestUtils.GetTestConfiguration()) { IgniteInstanceName = name }; } /// <summary> /// Generates next message with sequential ID and current test name. /// </summary> private static string NextMessage() { var id = NextId(); return id + "_" + TestContext.CurrentContext.Test.Name; } /// <summary> /// Generates next sequential ID. /// </summary> private static int NextId() { return Interlocked.Increment(ref _messageId); } } /// <summary> /// Messaging test helper class. /// </summary> [Serializable] public static class MessagingTestHelper { /** */ public static readonly ConcurrentStack<string> ReceivedMessages = new ConcurrentStack<string>(); /** */ private static readonly ConcurrentStack<string> Failures = new ConcurrentStack<string>(); /** */ private static readonly CountdownEvent ReceivedEvent = new CountdownEvent(0); /** */ private static readonly ConcurrentStack<Guid> LastNodeIds = new ConcurrentStack<Guid>(); /** */ public static volatile bool ListenResult = true; /** */ public static readonly TimeSpan MessageTimeout = TimeSpan.FromMilliseconds(5000); /** */ public static readonly TimeSpan SleepTimeout = TimeSpan.FromMilliseconds(50); /// <summary> /// Clears received message information. /// </summary> /// <param name="expectedCount">The expected count of messages to be received.</param> public static void ClearReceived(int expectedCount) { ReceivedMessages.Clear(); ReceivedEvent.Reset(expectedCount); LastNodeIds.Clear(); } /// <summary> /// Verifies received messages against expected messages. /// </summary> /// <param name="cluster">Cluster.</param> /// <param name="expectedMessages">Expected messages.</param> /// <param name="resultFunc">Result transform function.</param> /// <param name="expectedRepeat">Expected repeat count.</param> public static void VerifyReceive(IClusterGroup cluster, IEnumerable<string> expectedMessages, Func<IEnumerable<string>, IEnumerable<string>> resultFunc, int expectedRepeat) { // check if expected message count has been received; Wait returns false if there were none. Assert.IsTrue(ReceivedEvent.Wait(MessageTimeout), string.Format("expectedMessages: {0}, expectedRepeat: {1}, remaining: {2}", expectedMessages, expectedRepeat, ReceivedEvent.CurrentCount)); expectedMessages = expectedMessages.SelectMany(x => Enumerable.Repeat(x, expectedRepeat)); Assert.AreEqual(expectedMessages, resultFunc(ReceivedMessages)); // check that all messages came from local node. var localNodeId = cluster.Ignite.GetCluster().GetLocalNode().Id; Assert.AreEqual(localNodeId, LastNodeIds.Distinct().Single()); AssertFailures(); } /// <summary> /// Gets the message listener. /// </summary> /// <returns>New instance of message listener.</returns> public static IMessageListener<string> GetListener() { return new RemoteListener(); } /// <summary> /// Combines accumulated failures and throws an assertion, if there are any. /// Clears accumulated failures. /// </summary> public static void AssertFailures() { if (Failures.Any()) Assert.Fail(Failures.Reverse().Aggregate((x, y) => string.Format("{0}\n{1}", x, y))); Failures.Clear(); } /// <summary> /// Remote listener. /// </summary> private class RemoteListener : IMessageListener<string> { /** <inheritdoc /> */ public bool Invoke(Guid nodeId, string message) { try { LastNodeIds.Push(nodeId); ReceivedMessages.Push(message); ReceivedEvent.Signal(); return ListenResult; } catch (Exception ex) { // When executed on remote nodes, these exceptions will not go to sender, // so we have to accumulate them. Failures.Push(string.Format("Exception in Listen (msg: {0}, id: {1}): {2}", message, nodeId, ex)); throw; } } } } /// <summary> /// Test message filter. /// </summary> [Serializable] public class MessageListener<T> : IMessageListener<T> { /** */ private readonly Func<Guid, T, bool> _invoke; #pragma warning disable 649 /** Grid. */ [InstanceResource] private IIgnite _grid; #pragma warning restore 649 /// <summary> /// Initializes a new instance of the <see cref="MessageListener{T}"/> class. /// </summary> /// <param name="invoke">The invoke delegate.</param> public MessageListener(Func<Guid, T, bool> invoke) { _invoke = invoke; } /** <inheritdoc /> */ public bool Invoke(Guid nodeId, T message) { Assert.IsNotNull(_grid); return _invoke(nodeId, message); } } }
using System; using System.Collections.Generic; using Pixie.Markup; namespace Pixie.Transforms { /// <summary> /// A transformation that turns log entries into diagnostics. /// </summary> public sealed class DiagnosticExtractor { /// <summary> /// Creates a diagnostic extractor. /// </summary> /// <param name="defaultOrigin"> /// The default origin to use, for when a log entry /// does not specify an origin. /// </param> /// <param name="defaultKind"> /// The kind of diagnostic to provide. /// </param> /// <param name="defaultThemeColor"> /// The diagnostic theme color. /// </param> /// <param name="defaultTitle"> /// The diagnostic title. /// </param> public DiagnosticExtractor( MarkupNode defaultOrigin, string defaultKind, Color defaultThemeColor, MarkupNode defaultTitle) { this.DefaultOrigin = defaultOrigin; this.DefaultKind = defaultKind; this.DefaultThemeColor = defaultThemeColor; this.DefaultTitle = defaultTitle; } /// <summary> /// Gets the default origin to use, for when a log entry /// does not specify an origin. /// </summary> /// <returns>The default origin.</returns> public MarkupNode DefaultOrigin { get; private set; } /// <summary> /// Gets the default kind of diagnostic to produce. /// </summary> /// <returns>The default kind of diagnostic.</returns> public string DefaultKind { get; private set; } /// <summary> /// Gets the default theme color for diagnostics. /// </summary> /// <returns>The default theme color for diagnostics.</returns> public Color DefaultThemeColor { get; private set; } /// <summary> /// Gets the default title for diagnostics. /// </summary> /// <returns>The default title for diagnostics.</returns> public MarkupNode DefaultTitle { get; private set; } /// <summary> /// Transforms a markup tree to include a diagnostic. /// </summary> /// <param name="tree">The tree to transform.</param> /// <returns>A transformed tree.</returns> public MarkupNode Transform(MarkupNode tree) { var visitor = new DiagnosticExtractingVisitor(this); return visitor.Transform(tree); } private static Dictionary<Severity, string> defaultKinds = new Dictionary<Severity, string>() { { Severity.Info, "info" }, { Severity.Message, "message" }, { Severity.Warning, "warning" }, { Severity.Error, "error" } }; private static Dictionary<Severity, Color> defaultColors = new Dictionary<Severity, Color>() { { Severity.Info, Colors.Green }, { Severity.Message, Colors.Green }, { Severity.Warning, Colors.Yellow }, { Severity.Error, Colors.Red } }; /// <summary> /// Transforms a log entry to include a diagnostic. /// </summary> /// <param name="entry">The log entry to transform.</param> /// <param name="defaultOrigin"> /// The default origin of a diagnostic. This is typically the /// name of the application.</param> /// <returns>A transformed log entry.</returns> public static LogEntry Transform(LogEntry entry, MarkupNode defaultOrigin) { var extractor = new DiagnosticExtractor( defaultOrigin, defaultKinds[entry.Severity], defaultColors[entry.Severity], new Text("")); return new LogEntry(entry.Severity, extractor.Transform(entry.Contents)); } } /// <summary> /// A node visitor that helps turn log entries into diagnostics. /// </summary> internal sealed class DiagnosticExtractingVisitor : MarkupVisitor { public DiagnosticExtractingVisitor(DiagnosticExtractor extractor) { this.extractor = extractor; } public DiagnosticExtractor extractor; private MarkupNode title; private MarkupNode origin; private bool foundText; private bool foundExistingDiagnostic; private bool FoundEverything => foundExistingDiagnostic || (title != null && origin != null); /// <inheritdoc/> protected override bool IsOfInterest(MarkupNode node) { return !FoundEverything && (node is Title || node is Text || node is HighlightedSource || node is Diagnostic); } /// <inheritdoc/> protected override MarkupNode VisitInteresting(MarkupNode node) { if (!foundText) { if (node is Title) { title = ((Title)node).Contents; foundText = true; return new Text(""); } else if (node is Text) { foundText = true; return node; } else if (node is Diagnostic) { // A top-level diagnostic is just what we're looking for. foundExistingDiagnostic = true; return node; } } if (origin == null && node is HighlightedSource) { var src = (HighlightedSource)node; origin = new SourceReference(src.HighlightedSpan); return node; } return VisitUninteresting(node); } /// <summary> /// Transforms a node to include a diagnostic. /// </summary> /// <param name="node">The node to transform.</param> /// <returns>A transformed node.</returns> public MarkupNode Transform(MarkupNode node) { var visited = Visit(node); if (foundExistingDiagnostic) { return visited; } else { return new Diagnostic( origin ?? extractor.DefaultOrigin, extractor.DefaultKind, extractor.DefaultThemeColor, title ?? extractor.DefaultTitle, visited); } } } }
// =========================================================== // Copyright (c) 2014-2015, Enrico Da Ros/kendar.org // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // =========================================================== using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Reflection; using Dapper; using ECQRS.Commons; using ECQRS.Commons.Repositories; using System.Collections; using System.Linq.Expressions; using LinqToSqlServer; namespace ECQRS.SqlServer.Repositories { public class DapperRepository<T> : IRepository<T> where T : IEntity, new() { private readonly IRepositoryConfiguration _config; protected static readonly string[] _fieldsNames; protected static readonly string[] _fields; protected static readonly string[] _values; protected static readonly string[] _fieldsValues; protected static readonly string _table; protected readonly string _connString; public string Table { get { return _table; } } public static string[] Fields { get { return _fields; } } static DapperRepository() { _table = typeof(T).Name; var fields = typeof(T) .GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(p => p.CanRead && p.CanWrite && p.Name != "Id") .Select(p => p.Name) .ToArray(); _fieldsNames = fields.ToArray(); _fields = fields.Select(f => "[" + f + "]").ToArray(); _values = fields.Select(f => "@" + f).ToArray(); var fieldsValues = new List<string>(); for (int i = 0; i < _fields.Length; i++) { fieldsValues.Add(string.Format("{0} = {1}", _fields[i], _values[i])); } _fieldsValues = fieldsValues.ToArray(); } public DapperRepository(IRepositoryConfiguration config) { _config = config; //Initialize(_table, new SqlConnection(config.ConnectionString), false); _connString = config.ConnectionString; DapperRepository.InitializeParsAndKeys<T>(_connString); } public T Get(Guid id) { using (var db = new SqlConnection(_connString)) { return db.Query<T>( string.Format("SELECT * FROM [{0}] WHERE [Id] = @id", _table), new { id }).SingleOrDefault(); } } public IQueryable<T> Where(string filter = null, Dictionary<string, object> param = null) { using (var db = new SqlConnection(_connString)) { if (string.IsNullOrWhiteSpace(filter)) { return db.Query<T>(string.Format("SELECT * FROM [{0}]", _table)).AsQueryable(); } return db.Query<T>(string.Format("SELECT * FROM [{0}] WHERE {1}", _table, filter), param).AsQueryable(); } } public void Update(T item) { UpdateWhere(item,i=>i.Id ==item.Id); } public Guid Save(T item) { var autoGen = DapperRepository._autoGenPk.ContainsKey(typeof(T)) && DapperRepository._autoGenPk[typeof(T)]; using (var db = new SqlConnection(_connString)) { var fields = string.Join(",", _fields); if (autoGen) fields += ",[Id]"; var values = string.Join(",", _values); if (autoGen) values += ",@Id"; var sqlQuery = string.Format( "INSERT INTO [{0}] ({1}) output INSERTED.Id VALUES({2}) ", //"OUTPUT inserted.Id VALUES(1)", _table, fields, values); return db.ExecuteScalar<Guid>(sqlQuery, item); } } public void Delete(Guid id) { DeleteWhere(a => a.Id == id); } private static Dictionary<string, object> ToPropertyDictionary(object obj) { var dictionary = new Dictionary<string, object>(); foreach (var propertyInfo in obj.GetType().GetProperties()) if (propertyInfo.CanRead && propertyInfo.GetIndexParameters().Length == 0) dictionary[propertyInfo.Name] = propertyInfo.GetValue(obj, null); return dictionary; } public IQueryable<T> Where(Expression<Func<T, bool>> expr) { var db = new SqlConnection(_connString); IQueryable<T> pq = new SqlServerQueryable<T>(_table, db, false); return pq.Where(expr); } public void UpdateWhere(object values, Expression<Func<T, bool>> expr) { using (var db = new SqlConnection(_connString)) { var realParams = new Dictionary<string, object>(); var target = ToPropertyDictionary(values); foreach(var item in target){ realParams.Add(item.Key, item.Value); } IQueryable<T> pq = new SqlServerQueryable<T>(null, null, true); pq.Where(expr).ToArray(); var result= ((SqlServerQueryable<T>)pq).Result; foreach(var item in result.Parameters){ realParams.Add(item.Key, item.Value); } var fieldsValues = string.Join(",", target.Select(kvp => "["+kvp.Key + "]=@" + kvp.Key)); var sqlQuery = string.Format( "UPDATE [{0}] SET {1} {2}", _table, fieldsValues, result.Sql); if (result.Sql.Contains("[Id]=[Id]")) { throw new Exception("AAAARG"); } db.Execute(sqlQuery, realParams); } } public void DeleteWhere(Expression<Func<T, bool>> expr) { using (var db = new SqlConnection(_connString)) { var fieldsValues = new Dictionary<string,object>(); IQueryable<T> pq = new SqlServerQueryable<T>(null, null, true); pq.Where(expr).ToArray(); var result= ((SqlServerQueryable<T>)pq).Result; foreach(var item in result.Parameters){ fieldsValues.Add(item.Key,item.Value); } if (result.Sql.Contains("[Id]=[Id]")) { throw new Exception("AAAARG"); } db.Query<T>( string.Format("DELETE FROM [{0}] {1}", _table,result.Sql), fieldsValues).SingleOrDefault(); } } public IEnumerable<T> GetAll() { using (var db = new SqlConnection(_connString)) { return db.Query<T>(string.Format("SELECT * FROM [{0}]", _table)); } } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A shopping center or mall. /// </summary> public class ShoppingCenter_Core : TypeCore, ILocalBusiness { public ShoppingCenter_Core() { this._TypeId = 240; this._Id = "ShoppingCenter"; this._Schema_Org_Url = "http://schema.org/ShoppingCenter"; string label = ""; GetLabel(out label, "ShoppingCenter", typeof(ShoppingCenter_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{155}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateType; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Microsoft.VisualStudio.Text.Differencing; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { public abstract class AbstractUserDiagnosticTest : AbstractCodeActionOrUserDiagnosticTest { internal abstract Task<IEnumerable<Tuple<Diagnostic, CodeFixCollection>>> GetDiagnosticAndFixesAsync( TestWorkspace workspace, string fixAllActionEquivalenceKey, object fixProviderData); internal abstract Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync(TestWorkspace workspace, object fixProviderData); protected override async Task<IList<CodeAction>> GetCodeActionsWorkerAsync( TestWorkspace workspace, string fixAllActionEquivalenceKey, object fixProviderData) { var diagnostics = await GetDiagnosticAndFixAsync(workspace, fixAllActionEquivalenceKey, fixProviderData); return diagnostics?.Item2?.Fixes.Select(f => f.Action).ToList(); } internal async Task<Tuple<Diagnostic, CodeFixCollection>> GetDiagnosticAndFixAsync( TestWorkspace workspace, string fixAllActionEquivalenceKey = null, object fixProviderData = null) { return (await GetDiagnosticAndFixesAsync(workspace, fixAllActionEquivalenceKey, fixProviderData)).FirstOrDefault(); } protected Document GetDocumentAndSelectSpan(TestWorkspace workspace, out TextSpan span) { var hostDocument = workspace.Documents.Single(d => d.SelectedSpans.Any()); span = hostDocument.SelectedSpans.Single(); return workspace.CurrentSolution.GetDocument(hostDocument.Id); } protected bool TryGetDocumentAndSelectSpan(TestWorkspace workspace, out Document document, out TextSpan span) { var hostDocument = workspace.Documents.FirstOrDefault(d => d.SelectedSpans.Any()); if (hostDocument == null) { document = null; span = default(TextSpan); return false; } span = hostDocument.SelectedSpans.Single(); document = workspace.CurrentSolution.GetDocument(hostDocument.Id); return true; } protected Document GetDocumentAndAnnotatedSpan(TestWorkspace workspace, out string annotation, out TextSpan span) { var hostDocument = workspace.Documents.Single(d => d.AnnotatedSpans.Any()); var annotatedSpan = hostDocument.AnnotatedSpans.Single(); annotation = annotatedSpan.Key; span = annotatedSpan.Value.Single(); return workspace.CurrentSolution.GetDocument(hostDocument.Id); } protected FixAllScope? GetFixAllScope(string annotation) { if (annotation == null) { return null; } switch (annotation) { case "FixAllInDocument": return FixAllScope.Document; case "FixAllInProject": return FixAllScope.Project; case "FixAllInSolution": return FixAllScope.Solution; case "FixAllInSelection": return FixAllScope.Custom; } throw new InvalidProgramException("Incorrect FixAll annotation in test"); } internal async Task<IEnumerable<Tuple<Diagnostic, CodeFixCollection>>> GetDiagnosticAndFixesAsync( IEnumerable<Diagnostic> diagnostics, DiagnosticAnalyzer provider, CodeFixProvider fixer, TestDiagnosticAnalyzerDriver testDriver, Document document, TextSpan span, string annotation, string fixAllActionId) { if (diagnostics.IsEmpty()) { return SpecializedCollections.EmptyEnumerable<Tuple<Diagnostic, CodeFixCollection>>(); } FixAllScope? scope = GetFixAllScope(annotation); return await GetDiagnosticAndFixesAsync(diagnostics, provider, fixer, testDriver, document, span, scope, fixAllActionId); } private async Task<IEnumerable<Tuple<Diagnostic, CodeFixCollection>>> GetDiagnosticAndFixesAsync( IEnumerable<Diagnostic> diagnostics, DiagnosticAnalyzer provider, CodeFixProvider fixer, TestDiagnosticAnalyzerDriver testDriver, Document document, TextSpan span, FixAllScope? scope, string fixAllActionId) { Assert.NotEmpty(diagnostics); var result = new List<Tuple<Diagnostic, CodeFixCollection>>(); if (scope == null) { // Simple code fix. foreach (var diagnostic in diagnostics) { var fixes = new List<CodeFix>(); var context = new CodeFixContext(document, diagnostic, (a, d) => fixes.Add(new CodeFix(document.Project, a, d)), CancellationToken.None); await fixer.RegisterCodeFixesAsync(context); if (fixes.Any()) { var codeFix = new CodeFixCollection( fixer, diagnostic.Location.SourceSpan, fixes.ToImmutableArray(), fixAllState: null, supportedScopes: ImmutableArray<FixAllScope>.Empty, firstDiagnostic: null); result.Add(Tuple.Create(diagnostic, codeFix)); } } } else { // Fix all fix. var fixAllProvider = fixer.GetFixAllProvider(); Assert.NotNull(fixAllProvider); var fixAllState = GetFixAllState(fixAllProvider, diagnostics, provider, fixer, testDriver, document, scope.Value, fixAllActionId); var fixAllContext = fixAllState.CreateFixAllContext(new ProgressTracker(), CancellationToken.None); var fixAllFix = await fixAllProvider.GetFixAsync(fixAllContext); if (fixAllFix != null) { // Same fix applies to each diagnostic in scope. foreach (var diagnostic in diagnostics) { var diagnosticSpan = diagnostic.Location.IsInSource ? diagnostic.Location.SourceSpan : default(TextSpan); var codeFix = new CodeFixCollection( fixAllProvider, diagnosticSpan, ImmutableArray.Create(new CodeFix(document.Project, fixAllFix, diagnostic)), fixAllState: null, supportedScopes: ImmutableArray<FixAllScope>.Empty, firstDiagnostic: null); result.Add(Tuple.Create(diagnostic, codeFix)); } } } return result; } private static FixAllState GetFixAllState( FixAllProvider fixAllProvider, IEnumerable<Diagnostic> diagnostics, DiagnosticAnalyzer provider, CodeFixProvider fixer, TestDiagnosticAnalyzerDriver testDriver, Document document, FixAllScope scope, string fixAllActionId) { Assert.NotEmpty(diagnostics); if (scope == FixAllScope.Custom) { // Bulk fixing diagnostics in selected scope. var diagnosticsToFix = ImmutableDictionary.CreateRange(SpecializedCollections.SingletonEnumerable(KeyValuePair.Create(document, diagnostics.ToImmutableArray()))); return FixAllState.Create(fixAllProvider, diagnosticsToFix, fixer, fixAllActionId); } var diagnostic = diagnostics.First(); Func<Document, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getDocumentDiagnosticsAsync = async (d, diagIds, c) => { var root = await d.GetSyntaxRootAsync(); var diags = await testDriver.GetDocumentDiagnosticsAsync(provider, d, root.FullSpan); diags = diags.Where(diag => diagIds.Contains(diag.Id)); return diags; }; Func<Project, bool, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getProjectDiagnosticsAsync = async (p, includeAllDocumentDiagnostics, diagIds, c) => { var diags = includeAllDocumentDiagnostics ? await testDriver.GetAllDiagnosticsAsync(provider, p) : await testDriver.GetProjectDiagnosticsAsync(provider, p); diags = diags.Where(diag => diagIds.Contains(diag.Id)); return diags; }; var diagnosticIds = ImmutableHashSet.Create(diagnostic.Id); var fixAllDiagnosticProvider = new FixAllState.FixAllDiagnosticProvider(diagnosticIds, getDocumentDiagnosticsAsync, getProjectDiagnosticsAsync); return diagnostic.Location.IsInSource ? new FixAllState(fixAllProvider, document, fixer, scope, fixAllActionId, diagnosticIds, fixAllDiagnosticProvider) : new FixAllState(fixAllProvider, document.Project, fixer, scope, fixAllActionId, diagnosticIds, fixAllDiagnosticProvider); } protected async Task TestEquivalenceKeyAsync(string initialMarkup, string equivalenceKey) { using (var workspace = await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions: null, compilationOptions: null)) { var diagnosticAndFix = await GetDiagnosticAndFixAsync(workspace); Assert.Equal(equivalenceKey, diagnosticAndFix.Item2.Fixes.ElementAt(index: 0).Action.EquivalenceKey); } } protected async Task TestActionCountInAllFixesAsync( string initialMarkup, int count, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, object fixProviderData = null) { using (var workspace = await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions, compilationOptions)) { var diagnosticAndFix = await GetDiagnosticAndFixesAsync(workspace, fixAllActionEquivalenceKey: null, fixProviderData: fixProviderData); var diagnosticCount = diagnosticAndFix.Select(x => x.Item2.Fixes.Count()).Sum(); Assert.Equal(count, diagnosticCount); } } protected async Task TestSpansAsync( string initialMarkup, string expectedMarkup, int index = 0, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, IDictionary<OptionKey, object> featureOptions = null, string diagnosticId = null, string fixAllActionEquivalenceId = null, object fixProviderData = null) { MarkupTestFile.GetSpans(expectedMarkup, out var unused, out IList<TextSpan> spansList); var expectedTextSpans = spansList.ToSet(); using (var workspace = await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions, compilationOptions)) { if (featureOptions != null) { workspace.ApplyOptions(featureOptions); } ISet<TextSpan> actualTextSpans; if (diagnosticId == null) { var diagnosticsAndFixes = await GetDiagnosticAndFixesAsync(workspace, fixAllActionEquivalenceId, fixProviderData); var diagnostics = diagnosticsAndFixes.Select(t => t.Item1); actualTextSpans = diagnostics.Select(d => d.Location.SourceSpan).ToSet(); } else { var diagnostics = await GetDiagnosticsAsync(workspace, fixProviderData); actualTextSpans = diagnostics.Where(d => d.Id == diagnosticId).Select(d => d.Location.SourceSpan).ToSet(); } Assert.True(expectedTextSpans.SetEquals(actualTextSpans)); } } internal async Task TestWithMockedGenerateTypeDialog( string initial, string languageName, string typeName, string expected = null, bool isLine = true, bool isMissing = false, Accessibility accessibility = Accessibility.NotApplicable, TypeKind typeKind = TypeKind.Class, string projectName = null, bool isNewFile = false, string existingFilename = null, IList<string> newFileFolderContainers = null, string fullFilePath = null, string newFileName = null, string assertClassName = null, bool checkIfUsingsIncluded = false, bool checkIfUsingsNotIncluded = false, string expectedTextWithUsings = null, string defaultNamespace = "", bool areFoldersValidIdentifiers = true, GenerateTypeDialogOptions assertGenerateTypeDialogOptions = null, IList<TypeKindOptions> assertTypeKindPresent = null, IList<TypeKindOptions> assertTypeKindAbsent = null, bool isCancelled = false) { using (var testState = await GenerateTypeTestState.CreateAsync(initial, isLine, projectName, typeName, existingFilename, languageName)) { // Initialize the viewModel values testState.TestGenerateTypeOptionsService.SetGenerateTypeOptions( accessibility: accessibility, typeKind: typeKind, typeName: testState.TypeName, project: testState.ProjectToBeModified, isNewFile: isNewFile, newFileName: newFileName, folders: newFileFolderContainers, fullFilePath: fullFilePath, existingDocument: testState.ExistingDocument, areFoldersValidIdentifiers: areFoldersValidIdentifiers, isCancelled: isCancelled); testState.TestProjectManagementService.SetDefaultNamespace( defaultNamespace: defaultNamespace); var diagnosticsAndFixes = await GetDiagnosticAndFixesAsync(testState.Workspace, fixAllActionEquivalenceKey: null, fixProviderData: null); var generateTypeDiagFixes = diagnosticsAndFixes.SingleOrDefault(df => GenerateTypeTestState.FixIds.Contains(df.Item1.Id)); if (isMissing) { Assert.Null(generateTypeDiagFixes); return; } var fixes = generateTypeDiagFixes.Item2.Fixes; Assert.NotNull(fixes); var fixActions = MassageActions(fixes.Select(f => f.Action).ToList()); Assert.NotNull(fixActions); // Since the dialog option is always fed as the last CodeAction var index = fixActions.Count() - 1; var action = fixActions.ElementAt(index); Assert.Equal(action.Title, FeaturesResources.Generate_new_type); var operations = await action.GetOperationsAsync(CancellationToken.None); Tuple<Solution, Solution> oldSolutionAndNewSolution = null; if (!isNewFile) { oldSolutionAndNewSolution = await TestOperationsAsync( testState.Workspace, expected, operations, conflictSpans: null, renameSpans: null, warningSpans: null, compareTokens: false, expectedChangedDocumentId: testState.ExistingDocument.Id); } else { oldSolutionAndNewSolution = await TestAddDocument( testState.Workspace, expected, operations, projectName != null, testState.ProjectToBeModified.Id, newFileFolderContainers, newFileName, compareTokens: false); } if (checkIfUsingsIncluded) { Assert.NotNull(expectedTextWithUsings); await TestOperationsAsync(testState.Workspace, expectedTextWithUsings, operations, conflictSpans: null, renameSpans: null, warningSpans: null, compareTokens: false, expectedChangedDocumentId: testState.InvocationDocument.Id); } if (checkIfUsingsNotIncluded) { var oldSolution = oldSolutionAndNewSolution.Item1; var newSolution = oldSolutionAndNewSolution.Item2; var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution); Assert.False(changedDocumentIds.Contains(testState.InvocationDocument.Id)); } // Added into a different project than the triggering project if (projectName != null) { var appliedChanges = ApplyOperationsAndGetSolution(testState.Workspace, operations); var newSolution = appliedChanges.Item2; var triggeredProject = newSolution.GetProject(testState.TriggeredProject.Id); // Make sure the Project reference is present Assert.True(triggeredProject.ProjectReferences.Any(pr => pr.ProjectId == testState.ProjectToBeModified.Id)); } // Assert Option Calculation if (assertClassName != null) { Assert.True(assertClassName == testState.TestGenerateTypeOptionsService.ClassName); } if (assertGenerateTypeDialogOptions != null || assertTypeKindPresent != null || assertTypeKindAbsent != null) { var generateTypeDialogOptions = testState.TestGenerateTypeOptionsService.GenerateTypeDialogOptions; if (assertGenerateTypeDialogOptions != null) { Assert.True(assertGenerateTypeDialogOptions.IsPublicOnlyAccessibility == generateTypeDialogOptions.IsPublicOnlyAccessibility); Assert.True(assertGenerateTypeDialogOptions.TypeKindOptions == generateTypeDialogOptions.TypeKindOptions); Assert.True(assertGenerateTypeDialogOptions.IsAttribute == generateTypeDialogOptions.IsAttribute); } if (assertTypeKindPresent != null) { foreach (var typeKindPresentEach in assertTypeKindPresent) { Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) != 0); } } if (assertTypeKindAbsent != null) { foreach (var typeKindPresentEach in assertTypeKindAbsent) { Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) == 0); } } } } } } }
/* * 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.Impl { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Datastream; using Apache.Ignite.Core.DataStructures; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.Metadata; using Apache.Ignite.Core.Impl.Cache; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Datastream; using Apache.Ignite.Core.Impl.DataStructures; using Apache.Ignite.Core.Impl.Handle; using Apache.Ignite.Core.Impl.Transactions; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Services; using Apache.Ignite.Core.Transactions; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Native Ignite wrapper. /// </summary> internal class Ignite : IIgnite, IClusterGroupEx, ICluster { /** */ private readonly IgniteConfiguration _cfg; /** Grid name. */ private readonly string _name; /** Unmanaged node. */ private readonly IUnmanagedTarget _proc; /** Marshaller. */ private readonly Marshaller _marsh; /** Initial projection. */ private readonly ClusterGroupImpl _prj; /** Binary. */ private readonly Binary.Binary _binary; /** Cached proxy. */ private readonly IgniteProxy _proxy; /** Lifecycle beans. */ private readonly IList<LifecycleBeanHolder> _lifecycleBeans; /** Local node. */ private IClusterNode _locNode; /** Transactions facade. */ private readonly Lazy<TransactionsImpl> _transactions; /** Callbacks */ private readonly UnmanagedCallbacks _cbs; /** Node info cache. */ private readonly ConcurrentDictionary<Guid, ClusterNodeImpl> _nodes = new ConcurrentDictionary<Guid, ClusterNodeImpl>(); /** Client reconnect task completion source. */ private volatile TaskCompletionSource<bool> _clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>(); /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="name">Grid name.</param> /// <param name="proc">Interop processor.</param> /// <param name="marsh">Marshaller.</param> /// <param name="lifecycleBeans">Lifecycle beans.</param> /// <param name="cbs">Callbacks.</param> public Ignite(IgniteConfiguration cfg, string name, IUnmanagedTarget proc, Marshaller marsh, IList<LifecycleBeanHolder> lifecycleBeans, UnmanagedCallbacks cbs) { Debug.Assert(cfg != null); Debug.Assert(proc != null); Debug.Assert(marsh != null); Debug.Assert(lifecycleBeans != null); Debug.Assert(cbs != null); _cfg = cfg; _name = name; _proc = proc; _marsh = marsh; _lifecycleBeans = lifecycleBeans; _cbs = cbs; marsh.Ignite = this; _prj = new ClusterGroupImpl(proc, UU.ProcessorProjection(proc), marsh, this, null); _binary = new Binary.Binary(marsh); _proxy = new IgniteProxy(this); cbs.Initialize(this); // Grid is not completely started here, can't initialize interop transactions right away. _transactions = new Lazy<TransactionsImpl>( () => new TransactionsImpl(UU.ProcessorTransactions(proc), marsh, GetLocalNode().Id)); // Set reconnected task to completed state for convenience. _clientReconnectTaskCompletionSource.SetResult(false); SetCompactFooter(); } /// <summary> /// Sets the compact footer setting. /// </summary> private void SetCompactFooter() { if (!string.IsNullOrEmpty(_cfg.SpringConfigUrl)) { // If there is a Spring config, use setting from Spring, // since we ignore .NET config in legacy mode. var cfg0 = GetConfiguration().BinaryConfiguration; if (cfg0 != null) _marsh.CompactFooter = cfg0.CompactFooter; } } /// <summary> /// On-start routine. /// </summary> internal void OnStart() { foreach (var lifecycleBean in _lifecycleBeans) lifecycleBean.OnStart(this); } /// <summary> /// Gets Ignite proxy. /// </summary> /// <returns>Proxy.</returns> public IgniteProxy Proxy { get { return _proxy; } } /** <inheritdoc /> */ public string Name { get { return _name; } } /** <inheritdoc /> */ public ICluster GetCluster() { return this; } /** <inheritdoc /> */ IIgnite IClusterGroup.Ignite { get { return this; } } /** <inheritdoc /> */ public IClusterGroup ForLocal() { return _prj.ForNodes(GetLocalNode()); } /** <inheritdoc /> */ public ICompute GetCompute() { return _prj.ForServers().GetCompute(); } /** <inheritdoc /> */ public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes) { return ((IClusterGroup) _prj).ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodes(params IClusterNode[] nodes) { return _prj.ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(IEnumerable<Guid> ids) { return ((IClusterGroup) _prj).ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(ICollection<Guid> ids) { return _prj.ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(params Guid[] ids) { return _prj.ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForPredicate(Func<IClusterNode, bool> p) { IgniteArgumentCheck.NotNull(p, "p"); return _prj.ForPredicate(p); } /** <inheritdoc /> */ public IClusterGroup ForAttribute(string name, string val) { return _prj.ForAttribute(name, val); } /** <inheritdoc /> */ public IClusterGroup ForCacheNodes(string name) { return _prj.ForCacheNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForDataNodes(string name) { return _prj.ForDataNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForClientNodes(string name) { return _prj.ForClientNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForRemotes() { return _prj.ForRemotes(); } /** <inheritdoc /> */ public IClusterGroup ForHost(IClusterNode node) { IgniteArgumentCheck.NotNull(node, "node"); return _prj.ForHost(node); } /** <inheritdoc /> */ public IClusterGroup ForRandom() { return _prj.ForRandom(); } /** <inheritdoc /> */ public IClusterGroup ForOldest() { return _prj.ForOldest(); } /** <inheritdoc /> */ public IClusterGroup ForYoungest() { return _prj.ForYoungest(); } /** <inheritdoc /> */ public IClusterGroup ForDotNet() { return _prj.ForDotNet(); } /** <inheritdoc /> */ public IClusterGroup ForServers() { return _prj.ForServers(); } /** <inheritdoc /> */ public ICollection<IClusterNode> GetNodes() { return _prj.GetNodes(); } /** <inheritdoc /> */ public IClusterNode GetNode(Guid id) { return _prj.GetNode(id); } /** <inheritdoc /> */ public IClusterNode GetNode() { return _prj.GetNode(); } /** <inheritdoc /> */ public IClusterMetrics GetMetrics() { return _prj.GetMetrics(); } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly", Justification = "There is no finalizer.")] [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_proxy", Justification = "Proxy does not need to be disposed.")] public void Dispose() { Ignition.Stop(Name, true); } /// <summary> /// Internal stop routine. /// </summary> /// <param name="cancel">Cancel flag.</param> internal unsafe void Stop(bool cancel) { UU.IgnitionStop(_proc.Context, Name, cancel); _cbs.Cleanup(); } /// <summary> /// Called before node has stopped. /// </summary> internal void BeforeNodeStop() { var handler = Stopping; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /// <summary> /// Called after node has stopped. /// </summary> internal void AfterNodeStop() { foreach (var bean in _lifecycleBeans) bean.OnLifecycleEvent(LifecycleEventType.AfterNodeStop); var handler = Stopped; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /** <inheritdoc /> */ public ICache<TK, TV> GetCache<TK, TV>(string name) { return Cache<TK, TV>(UU.ProcessorCache(_proc, name)); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(string name) { return Cache<TK, TV>(UU.ProcessorGetOrCreateCache(_proc, name)); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration) { return GetOrCreateCache<TK, TV>(configuration, null); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { IgniteArgumentCheck.NotNull(configuration, "configuration"); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = Marshaller.StartMarshal(stream); configuration.Write(writer); if (nearConfiguration != null) { writer.WriteBoolean(true); nearConfiguration.Write(writer); } else writer.WriteBoolean(false); stream.SynchronizeOutput(); return Cache<TK, TV>(UU.ProcessorGetOrCreateCache(_proc, stream.MemoryPointer)); } } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(string name) { return Cache<TK, TV>(UU.ProcessorCreateCache(_proc, name)); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration) { return CreateCache<TK, TV>(configuration, null); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { IgniteArgumentCheck.NotNull(configuration, "configuration"); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = Marshaller.StartMarshal(stream); configuration.Write(writer); if (nearConfiguration != null) { writer.WriteBoolean(true); nearConfiguration.Write(writer); } else writer.WriteBoolean(false); stream.SynchronizeOutput(); return Cache<TK, TV>(UU.ProcessorCreateCache(_proc, stream.MemoryPointer)); } } /** <inheritdoc /> */ public void DestroyCache(string name) { UU.ProcessorDestroyCache(_proc, name); } /// <summary> /// Gets cache from specified native cache object. /// </summary> /// <param name="nativeCache">Native cache.</param> /// <param name="keepBinary">Keep binary flag.</param> /// <returns> /// New instance of cache wrapping specified native cache. /// </returns> public ICache<TK, TV> Cache<TK, TV>(IUnmanagedTarget nativeCache, bool keepBinary = false) { return new CacheImpl<TK, TV>(this, nativeCache, _marsh, false, keepBinary, false, false); } /** <inheritdoc /> */ public IClusterNode GetLocalNode() { return _locNode ?? (_locNode = GetNodes().FirstOrDefault(x => x.IsLocal)); } /** <inheritdoc /> */ public bool PingNode(Guid nodeId) { return _prj.PingNode(nodeId); } /** <inheritdoc /> */ public long TopologyVersion { get { return _prj.TopologyVersion; } } /** <inheritdoc /> */ public ICollection<IClusterNode> GetTopology(long ver) { return _prj.Topology(ver); } /** <inheritdoc /> */ public void ResetMetrics() { UU.ProjectionResetMetrics(_prj.Target); } /** <inheritdoc /> */ public Task<bool> ClientReconnectTask { get { return _clientReconnectTaskCompletionSource.Task; } } /** <inheritdoc /> */ public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName) { return new DataStreamerImpl<TK, TV>(UU.ProcessorDataStreamer(_proc, cacheName, false), _marsh, cacheName, false); } /** <inheritdoc /> */ public IBinary GetBinary() { return _binary; } /** <inheritdoc /> */ public ICacheAffinity GetAffinity(string cacheName) { return new CacheAffinityImpl(UU.ProcessorAffinity(_proc, cacheName), _marsh, false, this); } /** <inheritdoc /> */ public ITransactions GetTransactions() { return _transactions.Value; } /** <inheritdoc /> */ public IMessaging GetMessaging() { return _prj.GetMessaging(); } /** <inheritdoc /> */ public IEvents GetEvents() { return _prj.GetEvents(); } /** <inheritdoc /> */ public IServices GetServices() { return _prj.ForServers().GetServices(); } /** <inheritdoc /> */ public IAtomicLong GetAtomicLong(string name, long initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var nativeLong = UU.ProcessorAtomicLong(_proc, name, initialValue, create); if (nativeLong == null) return null; return new AtomicLong(nativeLong, Marshaller, name); } /** <inheritdoc /> */ public IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var nativeSeq = UU.ProcessorAtomicSequence(_proc, name, initialValue, create); if (nativeSeq == null) return null; return new AtomicSequence(nativeSeq, Marshaller, name); } /** <inheritdoc /> */ public IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var refTarget = GetAtomicReferenceUnmanaged(name, initialValue, create); return refTarget == null ? null : new AtomicReference<T>(refTarget, Marshaller, name); } /// <summary> /// Gets the unmanaged atomic reference. /// </summary> /// <param name="name">The name.</param> /// <param name="initialValue">The initial value.</param> /// <param name="create">Create flag.</param> /// <returns>Unmanaged atomic reference, or null.</returns> private IUnmanagedTarget GetAtomicReferenceUnmanaged<T>(string name, T initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); // Do not allocate memory when default is not used. if (!create) return UU.ProcessorAtomicReference(_proc, name, 0, false); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = Marshaller.StartMarshal(stream); writer.Write(initialValue); var memPtr = stream.SynchronizeOutput(); return UU.ProcessorAtomicReference(_proc, name, memPtr, true); } } /** <inheritdoc /> */ public IgniteConfiguration GetConfiguration() { using (var stream = IgniteManager.Memory.Allocate(1024).GetStream()) { UU.ProcessorGetIgniteConfiguration(_proc, stream.MemoryPointer); stream.SynchronizeInput(); return new IgniteConfiguration(_marsh.StartUnmarshal(stream)); } } /** <inheritdoc /> */ public ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, UU.ProcessorCreateNearCache); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, UU.ProcessorGetOrCreateNearCache); } /** <inheritdoc /> */ public ICollection<string> GetCacheNames() { using (var stream = IgniteManager.Memory.Allocate(1024).GetStream()) { UU.ProcessorGetCacheNames(_proc, stream.MemoryPointer); stream.SynchronizeInput(); var reader = _marsh.StartUnmarshal(stream); var res = new string[stream.ReadInt()]; for (int i = 0; i < res.Length; i++) res[i] = reader.ReadString(); return res; } } /** <inheritdoc /> */ public event EventHandler Stopping; /** <inheritdoc /> */ public event EventHandler Stopped; /** <inheritdoc /> */ public event EventHandler ClientDisconnected; /** <inheritdoc /> */ public event EventHandler<ClientReconnectEventArgs> ClientReconnected; /// <summary> /// Gets or creates near cache. /// </summary> private ICache<TK, TV> GetOrCreateNearCache0<TK, TV>(string name, NearCacheConfiguration configuration, Func<IUnmanagedTarget, string, long, IUnmanagedTarget> func) { IgniteArgumentCheck.NotNull(configuration, "configuration"); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = Marshaller.StartMarshal(stream); configuration.Write(writer); stream.SynchronizeOutput(); return Cache<TK, TV>(func(_proc, name, stream.MemoryPointer)); } } /// <summary> /// Gets internal projection. /// </summary> /// <returns>Projection.</returns> internal ClusterGroupImpl ClusterGroup { get { return _prj; } } /// <summary> /// Marshaller. /// </summary> internal Marshaller Marshaller { get { return _marsh; } } /// <summary> /// Configuration. /// </summary> internal IgniteConfiguration Configuration { get { return _cfg; } } /// <summary> /// Put metadata to Grid. /// </summary> /// <param name="metas">Metadata.</param> internal void PutBinaryTypes(ICollection<BinaryType> metas) { _prj.PutBinaryTypes(metas); } /** <inheritDoc /> */ public IBinaryType GetBinaryType(int typeId) { return _prj.GetBinaryType(typeId); } /// <summary> /// Handle registry. /// </summary> public HandleRegistry HandleRegistry { get { return _cbs.HandleRegistry; } } /// <summary> /// Updates the node information from stream. /// </summary> /// <param name="memPtr">Stream ptr.</param> public void UpdateNodeInfo(long memPtr) { var stream = IgniteManager.Memory.Get(memPtr).GetStream(); IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); var node = new ClusterNodeImpl(reader); node.Init(this); _nodes[node.Id] = node; } /// <summary> /// Gets the node from cache. /// </summary> /// <param name="id">Node id.</param> /// <returns>Cached node.</returns> public ClusterNodeImpl GetNode(Guid? id) { return id == null ? null : _nodes[id.Value]; } /// <summary> /// Gets the interop processor. /// </summary> internal IUnmanagedTarget InteropProcessor { get { return _proc; } } /// <summary> /// Called when local client node has been disconnected from the cluster. /// </summary> internal void OnClientDisconnected() { _clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>(); var handler = ClientDisconnected; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /// <summary> /// Called when local client node has been reconnected to the cluster. /// </summary> /// <param name="clusterRestarted">Cluster restarted flag.</param> internal void OnClientReconnected(bool clusterRestarted) { _clientReconnectTaskCompletionSource.TrySetResult(clusterRestarted); var handler = ClientReconnected; if (handler != null) handler.Invoke(this, new ClientReconnectEventArgs(clusterRestarted)); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Reflection; using System.Text; using System.Xml; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Internal.Fakeables; using NLog.Layouts; using NLog.Targets; /// <summary> /// XML event description compatible with log4j, Chainsaw and NLogViewer. /// </summary> [LayoutRenderer("log4jxmlevent")] [ThreadSafe] [MutableUnsafe] public class Log4JXmlEventLayoutRenderer : LayoutRenderer, IUsesStackTrace, IIncludeContext { private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1); private static readonly string dummyNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid(); private static readonly string dummyNamespaceRemover = " xmlns:log4j=\"" + dummyNamespace + "\""; private static readonly string dummyNLogNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid(); private static readonly string dummyNLogNamespaceRemover = " xmlns:nlog=\"" + dummyNLogNamespace + "\""; private readonly NdcLayoutRenderer _ndcLayoutRenderer = new NdcLayoutRenderer() { Separator = " " }; #if !SILVERLIGHT private readonly NdlcLayoutRenderer _ndlcLayoutRenderer = new NdlcLayoutRenderer() { Separator = " " }; #endif /// <summary> /// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class. /// </summary> public Log4JXmlEventLayoutRenderer() : this(LogFactory.CurrentAppDomain) { } /// <summary> /// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class. /// </summary> public Log4JXmlEventLayoutRenderer(IAppDomain appDomain) { IncludeNLogData = true; // TODO NLog ver. 5 - Disable this by default, as mostly duplicate data is added #if SILVERLIGHT AppInfo = "Silverlight Application"; #elif NETSTANDARD1_3 AppInfo = "NetCore Application"; #elif __IOS__ AppInfo = "MonoTouch Application"; #else AppInfo = string.Format( CultureInfo.InvariantCulture, "{0}({1})", appDomain.FriendlyName, LogFactory.DefaultAppEnvironment.CurrentProcessId); #endif Parameters = new List<NLogViewerParameterInfo>(); try { _machineName = EnvironmentHelper.GetMachineName(); if (string.IsNullOrEmpty(_machineName)) { InternalLogger.Info("MachineName is not available."); } } catch (Exception exception) { InternalLogger.Error(exception, "Error getting machine name."); if (exception.MustBeRethrown()) { throw; } _machineName = string.Empty; } } /// <summary> /// Initializes the layout renderer. /// </summary> protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); _xmlWriterSettings = new XmlWriterSettings { Indent = IndentXml, ConformanceLevel = ConformanceLevel.Fragment, IndentChars = " ", }; } /// <summary> /// Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema. /// </summary> /// <docgen category='Payload Options' order='10' /> [DefaultValue(true)] public bool IncludeNLogData { get; set; } /// <summary> /// Gets or sets a value indicating whether the XML should use spaces for indentation. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IndentXml { get; set; } /// <summary> /// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain. /// </summary> /// <docgen category='Payload Options' order='10' /> public string AppInfo { get; set; } /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeCallSite { get; set; } /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeSourceInfo { get; set; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeMdc { get; set; } #if !SILVERLIGHT /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsLogicalContext"/> dictionary. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeScopeProperties { get => IncludeMdlc; set => IncludeMdlc = value; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsLogicalContext"/> dictionary. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeMdlc { get; set; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsLogicalContext"/> stack. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNdlc { get; set; } /// <summary> /// Gets or sets the NDLC item separator. /// </summary> /// <docgen category='Payload Options' order='10' /> [DefaultValue(" ")] public string NdlcItemSeparator { get => _ndlcLayoutRenderer.Separator; set => _ndlcLayoutRenderer.Separator = value; } #endif /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='JSON Output' order='10' /> public bool IncludeEventProperties { get => IncludeAllProperties; set => IncludeAllProperties = value; } /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeAllProperties { get; set; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsContext"/> stack. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNdc { get; set; } /// <summary> /// Gets or sets the NDC item separator. /// </summary> /// <docgen category='Payload Options' order='10' /> [DefaultValue(" ")] public string NdcItemSeparator { get => _ndcLayoutRenderer.Separator; set => _ndcLayoutRenderer.Separator = value; } /// <summary> /// Gets or sets the log4j:event logger-xml-attribute (Default ${logger}) /// </summary> /// <docgen category='Payload Options' order='10' /> public Layout LoggerName { get; set; } private readonly string _machineName; private XmlWriterSettings _xmlWriterSettings; /// <summary> /// Gets the level of stack trace information required by the implementing class. /// </summary> StackTraceUsage IUsesStackTrace.StackTraceUsage { get { if (IncludeSourceInfo) { return StackTraceUsage.Max; } if (IncludeCallSite) { return StackTraceUsage.WithoutSource; } return StackTraceUsage.None; } } internal IList<NLogViewerParameterInfo> Parameters { get; set; } internal void AppendToStringBuilder(StringBuilder sb, LogEventInfo logEvent) { Append(sb, logEvent); } /// <summary> /// Renders the XML logging event and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { StringBuilder sb = new StringBuilder(); using (XmlWriter xtw = XmlWriter.Create(sb, _xmlWriterSettings)) { xtw.WriteStartElement("log4j", "event", dummyNamespace); xtw.WriteAttributeSafeString("xmlns", "nlog", null, dummyNLogNamespace); xtw.WriteAttributeSafeString("logger", LoggerName != null ? LoggerName.Render(logEvent) : logEvent.LoggerName); xtw.WriteAttributeSafeString("level", logEvent.Level.Name.ToUpperInvariant()); xtw.WriteAttributeSafeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture)); xtw.WriteAttributeSafeString("thread", AsyncHelpers.GetManagedThreadId().ToString(CultureInfo.InvariantCulture)); xtw.WriteElementSafeString("log4j", "message", dummyNamespace, logEvent.FormattedMessage); if (logEvent.Exception != null) { // TODO Why twice the exception details? xtw.WriteElementSafeString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString()); } AppendNdc(xtw, logEvent); AppendException(logEvent, xtw); AppendCallSite(logEvent, xtw); AppendProperties(xtw); AppendMdlc(xtw); if (IncludeAllProperties) { AppendProperties("log4j", xtw, logEvent); } AppendParameters(logEvent, xtw); xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", "log4japp"); xtw.WriteAttributeSafeString("value", AppInfo); xtw.WriteEndElement(); xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", "log4jmachinename"); xtw.WriteAttributeSafeString("value", _machineName); xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.Flush(); // get rid of 'nlog' and 'log4j' namespace declarations sb.Replace(dummyNamespaceRemover, string.Empty); sb.Replace(dummyNLogNamespaceRemover, string.Empty); sb.CopyTo(builder); // StringBuilder.Replace is not good when reusing the StringBuilder } } private void AppendMdlc(XmlWriter xtw) { #if !SILVERLIGHT if (IncludeMdlc) { foreach (string key in MappedDiagnosticsLogicalContext.GetNames()) { string propertyValue = XmlHelper.XmlConvertToString(MappedDiagnosticsLogicalContext.GetObject(key)); if (propertyValue == null) continue; xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", key); xtw.WriteAttributeSafeString("value", propertyValue); xtw.WriteEndElement(); } } #endif } private void AppendNdc(XmlWriter xtw, LogEventInfo logEvent) { string ndcContent = null; if (IncludeNdc) { ndcContent = _ndcLayoutRenderer.Render(logEvent); } #if !SILVERLIGHT if (IncludeNdlc) { if (ndcContent != null) { //extra separator ndcContent += NdcItemSeparator; } ndcContent += _ndlcLayoutRenderer.Render(logEvent); } #endif if (ndcContent != null) { //NDLC and NDC should be in the same element xtw.WriteElementSafeString("log4j", "NDC", dummyNamespace, ndcContent); } } private static void AppendException(LogEventInfo logEvent, XmlWriter xtw) { if (logEvent.Exception != null) { // TODO Why twice the exception details? xtw.WriteStartElement("log4j", "throwable", dummyNamespace); xtw.WriteSafeCData(logEvent.Exception.ToString()); xtw.WriteEndElement(); } } private void AppendParameters(LogEventInfo logEvent, XmlWriter xtw) { for (int i = 0; i < Parameters?.Count; ++i) { var parameter = Parameters[i]; if (string.IsNullOrEmpty(parameter?.Name)) continue; var parameterValue = parameter.Layout?.Render(logEvent) ?? string.Empty; if (!parameter.IncludeEmptyValue && string.IsNullOrEmpty(parameterValue)) continue; xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", parameter.Name); xtw.WriteAttributeSafeString("value", parameterValue); xtw.WriteEndElement(); } } private void AppendProperties(XmlWriter xtw) { xtw.WriteStartElement("log4j", "properties", dummyNamespace); if (IncludeMdc) { foreach (string key in MappedDiagnosticsContext.GetNames()) { string propertyValue = XmlHelper.XmlConvertToString(MappedDiagnosticsContext.GetObject(key)); if (propertyValue == null) continue; xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", key); xtw.WriteAttributeSafeString("value", propertyValue); xtw.WriteEndElement(); } } } private void AppendCallSite(LogEventInfo logEvent, XmlWriter xtw) { if ((IncludeCallSite || IncludeSourceInfo) && logEvent.CallSiteInformation != null) { MethodBase methodBase = logEvent.CallSiteInformation.GetCallerStackFrameMethod(0); string callerClassName = logEvent.CallSiteInformation.GetCallerClassName(methodBase, true, true, true); string callerMemberName = logEvent.CallSiteInformation.GetCallerMemberName(methodBase, true, true, true); xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace); if (!string.IsNullOrEmpty(callerClassName)) { xtw.WriteAttributeSafeString("class", callerClassName); } xtw.WriteAttributeSafeString("method", callerMemberName); #if !SILVERLIGHT if (IncludeSourceInfo) { xtw.WriteAttributeSafeString("file", logEvent.CallSiteInformation.GetCallerFilePath(0)); xtw.WriteAttributeSafeString("line", logEvent.CallSiteInformation.GetCallerLineNumber(0).ToString(CultureInfo.InvariantCulture)); } #endif xtw.WriteEndElement(); if (IncludeNLogData) { xtw.WriteElementSafeString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture)); xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace); var type = methodBase?.DeclaringType; if (type != null) { xtw.WriteAttributeSafeString("assembly", type.GetAssembly().FullName); } xtw.WriteEndElement(); xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace); AppendProperties("nlog", xtw, logEvent); xtw.WriteEndElement(); } } } private void AppendProperties(string prefix, XmlWriter xtw, LogEventInfo logEvent) { if (logEvent.HasProperties) { foreach (var contextProperty in logEvent.Properties) { string propertyKey = XmlHelper.XmlConvertToString(contextProperty.Key); if (string.IsNullOrEmpty(propertyKey)) continue; string propertyValue = XmlHelper.XmlConvertToString(contextProperty.Value); if (propertyValue == null) continue; xtw.WriteStartElement(prefix, "data", dummyNamespace); xtw.WriteAttributeSafeString("name", propertyKey); xtw.WriteAttributeSafeString("value", propertyValue); xtw.WriteEndElement(); } } } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // 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. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Gl { /// <summary> /// [GL] Value of GL_PROGRAM_ATTRIB_COMPONENTS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_gpu_program4")] public const int PROGRAM_ATTRIB_COMPONENTS_NV = 0x8906; /// <summary> /// [GL] Value of GL_PROGRAM_RESULT_COMPONENTS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_gpu_program4")] public const int PROGRAM_RESULT_COMPONENTS_NV = 0x8907; /// <summary> /// [GL] Value of GL_MAX_PROGRAM_ATTRIB_COMPONENTS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_gpu_program4")] public const int MAX_PROGRAM_ATTRIB_COMPONENTS_NV = 0x8908; /// <summary> /// [GL] Value of GL_MAX_PROGRAM_RESULT_COMPONENTS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_gpu_program4")] public const int MAX_PROGRAM_RESULT_COMPONENTS_NV = 0x8909; /// <summary> /// [GL] Value of GL_MAX_PROGRAM_GENERIC_ATTRIBS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_gpu_program4")] public const int MAX_PROGRAM_GENERIC_ATTRIBS_NV = 0x8DA5; /// <summary> /// [GL] Value of GL_MAX_PROGRAM_GENERIC_RESULTS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_gpu_program4")] public const int MAX_PROGRAM_GENERIC_RESULTS_NV = 0x8DA6; /// <summary> /// [GL] glProgramLocalParameterI4iNV: Binding for glProgramLocalParameterI4iNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="x"> /// A <see cref="T:int"/>. /// </param> /// <param name="y"> /// A <see cref="T:int"/>. /// </param> /// <param name="z"> /// A <see cref="T:int"/>. /// </param> /// <param name="w"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void ProgramLocalParameterI4NV(int target, uint index, int x, int y, int z, int w) { Debug.Assert(Delegates.pglProgramLocalParameterI4iNV != null, "pglProgramLocalParameterI4iNV not implemented"); Delegates.pglProgramLocalParameterI4iNV(target, index, x, y, z, w); LogCommand("glProgramLocalParameterI4iNV", null, target, index, x, y, z, w ); DebugCheckErrors(null); } /// <summary> /// [GL] glProgramLocalParameterI4ivNV: Binding for glProgramLocalParameterI4ivNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="params"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void ProgramLocalParameterI4NV(int target, uint index, int[] @params) { Debug.Assert(@params.Length >= 4); unsafe { fixed (int* p_params = @params) { Debug.Assert(Delegates.pglProgramLocalParameterI4ivNV != null, "pglProgramLocalParameterI4ivNV not implemented"); Delegates.pglProgramLocalParameterI4ivNV(target, index, p_params); LogCommand("glProgramLocalParameterI4ivNV", null, target, index, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glProgramLocalParametersI4ivNV: Binding for glProgramLocalParametersI4ivNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="params"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void ProgramLocalParametersI4NV(int target, uint index, int[] @params) { Debug.Assert(@params.Length > 0 && (@params.Length % 4) == 0, "empty or not multiple of 4"); unsafe { fixed (int* p_params = @params) { Debug.Assert(Delegates.pglProgramLocalParametersI4ivNV != null, "pglProgramLocalParametersI4ivNV not implemented"); Delegates.pglProgramLocalParametersI4ivNV(target, index, @params.Length / 4, p_params); LogCommand("glProgramLocalParametersI4ivNV", null, target, index, @params.Length / 4, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glProgramLocalParameterI4uiNV: Binding for glProgramLocalParameterI4uiNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="x"> /// A <see cref="T:uint"/>. /// </param> /// <param name="y"> /// A <see cref="T:uint"/>. /// </param> /// <param name="z"> /// A <see cref="T:uint"/>. /// </param> /// <param name="w"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void ProgramLocalParameterI4uiNV(int target, uint index, uint x, uint y, uint z, uint w) { Debug.Assert(Delegates.pglProgramLocalParameterI4uiNV != null, "pglProgramLocalParameterI4uiNV not implemented"); Delegates.pglProgramLocalParameterI4uiNV(target, index, x, y, z, w); LogCommand("glProgramLocalParameterI4uiNV", null, target, index, x, y, z, w ); DebugCheckErrors(null); } /// <summary> /// [GL] glProgramLocalParameterI4uivNV: Binding for glProgramLocalParameterI4uivNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="params"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void ProgramLocalParameterI4uiNV(int target, uint index, uint[] @params) { Debug.Assert(@params.Length >= 4); unsafe { fixed (uint* p_params = @params) { Debug.Assert(Delegates.pglProgramLocalParameterI4uivNV != null, "pglProgramLocalParameterI4uivNV not implemented"); Delegates.pglProgramLocalParameterI4uivNV(target, index, p_params); LogCommand("glProgramLocalParameterI4uivNV", null, target, index, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glProgramLocalParametersI4uivNV: Binding for glProgramLocalParametersI4uivNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="params"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void ProgramLocalParametersI4uiNV(int target, uint index, uint[] @params) { Debug.Assert(@params.Length > 0 && (@params.Length % 4) == 0, "empty or not multiple of 4"); unsafe { fixed (uint* p_params = @params) { Debug.Assert(Delegates.pglProgramLocalParametersI4uivNV != null, "pglProgramLocalParametersI4uivNV not implemented"); Delegates.pglProgramLocalParametersI4uivNV(target, index, @params.Length / 4, p_params); LogCommand("glProgramLocalParametersI4uivNV", null, target, index, @params.Length / 4, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glProgramEnvParameterI4iNV: Binding for glProgramEnvParameterI4iNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="x"> /// A <see cref="T:int"/>. /// </param> /// <param name="y"> /// A <see cref="T:int"/>. /// </param> /// <param name="z"> /// A <see cref="T:int"/>. /// </param> /// <param name="w"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void ProgramEnvParameterI4NV(int target, uint index, int x, int y, int z, int w) { Debug.Assert(Delegates.pglProgramEnvParameterI4iNV != null, "pglProgramEnvParameterI4iNV not implemented"); Delegates.pglProgramEnvParameterI4iNV(target, index, x, y, z, w); LogCommand("glProgramEnvParameterI4iNV", null, target, index, x, y, z, w ); DebugCheckErrors(null); } /// <summary> /// [GL] glProgramEnvParameterI4ivNV: Binding for glProgramEnvParameterI4ivNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="params"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void ProgramEnvParameterI4NV(int target, uint index, int[] @params) { Debug.Assert(@params.Length >= 4); unsafe { fixed (int* p_params = @params) { Debug.Assert(Delegates.pglProgramEnvParameterI4ivNV != null, "pglProgramEnvParameterI4ivNV not implemented"); Delegates.pglProgramEnvParameterI4ivNV(target, index, p_params); LogCommand("glProgramEnvParameterI4ivNV", null, target, index, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glProgramEnvParametersI4ivNV: Binding for glProgramEnvParametersI4ivNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="params"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void ProgramEnvParametersI4NV(int target, uint index, int[] @params) { Debug.Assert(@params.Length > 0 && (@params.Length % 4) == 0, "empty or not multiple of 4"); unsafe { fixed (int* p_params = @params) { Debug.Assert(Delegates.pglProgramEnvParametersI4ivNV != null, "pglProgramEnvParametersI4ivNV not implemented"); Delegates.pglProgramEnvParametersI4ivNV(target, index, @params.Length / 4, p_params); LogCommand("glProgramEnvParametersI4ivNV", null, target, index, @params.Length / 4, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glProgramEnvParameterI4uiNV: Binding for glProgramEnvParameterI4uiNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="x"> /// A <see cref="T:uint"/>. /// </param> /// <param name="y"> /// A <see cref="T:uint"/>. /// </param> /// <param name="z"> /// A <see cref="T:uint"/>. /// </param> /// <param name="w"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void ProgramEnvParameterI4uiNV(int target, uint index, uint x, uint y, uint z, uint w) { Debug.Assert(Delegates.pglProgramEnvParameterI4uiNV != null, "pglProgramEnvParameterI4uiNV not implemented"); Delegates.pglProgramEnvParameterI4uiNV(target, index, x, y, z, w); LogCommand("glProgramEnvParameterI4uiNV", null, target, index, x, y, z, w ); DebugCheckErrors(null); } /// <summary> /// [GL] glProgramEnvParameterI4uivNV: Binding for glProgramEnvParameterI4uivNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="params"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void ProgramEnvParameterI4uiNV(int target, uint index, uint[] @params) { Debug.Assert(@params.Length >= 4); unsafe { fixed (uint* p_params = @params) { Debug.Assert(Delegates.pglProgramEnvParameterI4uivNV != null, "pglProgramEnvParameterI4uivNV not implemented"); Delegates.pglProgramEnvParameterI4uivNV(target, index, p_params); LogCommand("glProgramEnvParameterI4uivNV", null, target, index, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glProgramEnvParametersI4uivNV: Binding for glProgramEnvParametersI4uivNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="params"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void ProgramEnvParametersI4uiNV(int target, uint index, uint[] @params) { Debug.Assert(@params.Length > 0 && (@params.Length % 4) == 0, "empty or not multiple of 4"); unsafe { fixed (uint* p_params = @params) { Debug.Assert(Delegates.pglProgramEnvParametersI4uivNV != null, "pglProgramEnvParametersI4uivNV not implemented"); Delegates.pglProgramEnvParametersI4uivNV(target, index, @params.Length / 4, p_params); LogCommand("glProgramEnvParametersI4uivNV", null, target, index, @params.Length / 4, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetProgramLocalParameterIivNV: Binding for glGetProgramLocalParameterIivNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="params"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void GetProgramLocalParameterINV(int target, uint index, [Out] int[] @params) { Debug.Assert(@params.Length >= 4); unsafe { fixed (int* p_params = @params) { Debug.Assert(Delegates.pglGetProgramLocalParameterIivNV != null, "pglGetProgramLocalParameterIivNV not implemented"); Delegates.pglGetProgramLocalParameterIivNV(target, index, p_params); LogCommand("glGetProgramLocalParameterIivNV", null, target, index, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetProgramLocalParameterIuivNV: Binding for glGetProgramLocalParameterIuivNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="params"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void GetProgramLocalParameterINV(int target, uint index, [Out] uint[] @params) { Debug.Assert(@params.Length >= 4); unsafe { fixed (uint* p_params = @params) { Debug.Assert(Delegates.pglGetProgramLocalParameterIuivNV != null, "pglGetProgramLocalParameterIuivNV not implemented"); Delegates.pglGetProgramLocalParameterIuivNV(target, index, p_params); LogCommand("glGetProgramLocalParameterIuivNV", null, target, index, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetProgramEnvParameterIivNV: Binding for glGetProgramEnvParameterIivNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="params"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void GetProgramEnvParameterINV(int target, uint index, [Out] int[] @params) { Debug.Assert(@params.Length >= 4); unsafe { fixed (int* p_params = @params) { Debug.Assert(Delegates.pglGetProgramEnvParameterIivNV != null, "pglGetProgramEnvParameterIivNV not implemented"); Delegates.pglGetProgramEnvParameterIivNV(target, index, p_params); LogCommand("glGetProgramEnvParameterIivNV", null, target, index, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetProgramEnvParameterIuivNV: Binding for glGetProgramEnvParameterIuivNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="params"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_NV_gpu_program4")] public static void GetProgramEnvParameterINV(int target, uint index, [Out] uint[] @params) { Debug.Assert(@params.Length >= 4); unsafe { fixed (uint* p_params = @params) { Debug.Assert(Delegates.pglGetProgramEnvParameterIuivNV != null, "pglGetProgramEnvParameterIuivNV not implemented"); Delegates.pglGetProgramEnvParameterIuivNV(target, index, p_params); LogCommand("glGetProgramEnvParameterIuivNV", null, target, index, @params ); } } DebugCheckErrors(null); } internal static unsafe partial class Delegates { [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramLocalParameterI4iNV(int target, uint index, int x, int y, int z, int w); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glProgramLocalParameterI4iNV pglProgramLocalParameterI4iNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramLocalParameterI4ivNV(int target, uint index, int* @params); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glProgramLocalParameterI4ivNV pglProgramLocalParameterI4ivNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramLocalParametersI4ivNV(int target, uint index, int count, int* @params); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glProgramLocalParametersI4ivNV pglProgramLocalParametersI4ivNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramLocalParameterI4uiNV(int target, uint index, uint x, uint y, uint z, uint w); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glProgramLocalParameterI4uiNV pglProgramLocalParameterI4uiNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramLocalParameterI4uivNV(int target, uint index, uint* @params); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glProgramLocalParameterI4uivNV pglProgramLocalParameterI4uivNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramLocalParametersI4uivNV(int target, uint index, int count, uint* @params); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glProgramLocalParametersI4uivNV pglProgramLocalParametersI4uivNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramEnvParameterI4iNV(int target, uint index, int x, int y, int z, int w); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glProgramEnvParameterI4iNV pglProgramEnvParameterI4iNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramEnvParameterI4ivNV(int target, uint index, int* @params); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glProgramEnvParameterI4ivNV pglProgramEnvParameterI4ivNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramEnvParametersI4ivNV(int target, uint index, int count, int* @params); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glProgramEnvParametersI4ivNV pglProgramEnvParametersI4ivNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramEnvParameterI4uiNV(int target, uint index, uint x, uint y, uint z, uint w); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glProgramEnvParameterI4uiNV pglProgramEnvParameterI4uiNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramEnvParameterI4uivNV(int target, uint index, uint* @params); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glProgramEnvParameterI4uivNV pglProgramEnvParameterI4uivNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramEnvParametersI4uivNV(int target, uint index, int count, uint* @params); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glProgramEnvParametersI4uivNV pglProgramEnvParametersI4uivNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetProgramLocalParameterIivNV(int target, uint index, int* @params); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glGetProgramLocalParameterIivNV pglGetProgramLocalParameterIivNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetProgramLocalParameterIuivNV(int target, uint index, uint* @params); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glGetProgramLocalParameterIuivNV pglGetProgramLocalParameterIuivNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetProgramEnvParameterIivNV(int target, uint index, int* @params); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glGetProgramEnvParameterIivNV pglGetProgramEnvParameterIivNV; [RequiredByFeature("GL_NV_gpu_program4")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetProgramEnvParameterIuivNV(int target, uint index, uint* @params); [RequiredByFeature("GL_NV_gpu_program4")] [ThreadStatic] internal static glGetProgramEnvParameterIuivNV pglGetProgramEnvParameterIuivNV; } } }
using Lucene.Net.Documents; using Lucene.Net.Support; using NUnit.Framework; using System; using System.Collections.Generic; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using IBits = Lucene.Net.Util.IBits; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; [TestFixture] public class TestDocIdSet : LuceneTestCase { [Test] public virtual void TestFilteredDocIdSet() { const int maxdoc = 10; DocIdSet innerSet = new DocIdSetAnonymousClass(this, maxdoc); DocIdSet filteredSet = new FilteredDocIdSetAnonymousClass(this, innerSet); DocIdSetIterator iter = filteredSet.GetIterator(); List<int?> list = new List<int?>(); int doc = iter.Advance(3); if (doc != DocIdSetIterator.NO_MORE_DOCS) { list.Add(Convert.ToInt32(doc)); while ((doc = iter.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { list.Add(Convert.ToInt32(doc)); } } int[] docs = new int[list.Count]; int c = 0; IEnumerator<int?> intIter = list.GetEnumerator(); while (intIter.MoveNext()) { docs[c++] = (int)intIter.Current; } int[] answer = new int[] { 4, 6, 8 }; bool same = Arrays.Equals(answer, docs); if (!same) { Console.WriteLine("answer: " + Arrays.ToString(answer)); Console.WriteLine("gotten: " + Arrays.ToString(docs)); Assert.Fail(); } } private class DocIdSetAnonymousClass : DocIdSet { private readonly TestDocIdSet outerInstance; private readonly int maxdoc; public DocIdSetAnonymousClass(TestDocIdSet outerInstance, int maxdoc) { this.outerInstance = outerInstance; this.maxdoc = maxdoc; } public override DocIdSetIterator GetIterator() { return new DocIdSetIteratorAnonymousClass(this); } private class DocIdSetIteratorAnonymousClass : DocIdSetIterator { private readonly DocIdSetAnonymousClass outerInstance; public DocIdSetIteratorAnonymousClass(DocIdSetAnonymousClass outerInstance) { this.outerInstance = outerInstance; docid = -1; } internal int docid; public override int DocID => docid; public override int NextDoc() { docid++; return docid < outerInstance.maxdoc ? docid : (docid = NO_MORE_DOCS); } public override int Advance(int target) { return SlowAdvance(target); } public override long GetCost() { return 1; } } } private class FilteredDocIdSetAnonymousClass : FilteredDocIdSet { private readonly TestDocIdSet outerInstance; public FilteredDocIdSetAnonymousClass(TestDocIdSet outerInstance, DocIdSet innerSet) : base(innerSet) { this.outerInstance = outerInstance; } protected override bool Match(int docid) { return docid % 2 == 0; //validate only even docids } } [Test] public virtual void TestNullDocIdSet() { // Tests that if a Filter produces a null DocIdSet, which is given to // IndexSearcher, everything works fine. this came up in LUCENE-1754. Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); doc.Add(NewStringField("c", "val", Field.Store.NO)); writer.AddDocument(doc); IndexReader reader = writer.GetReader(); writer.Dispose(); // First verify the document is searchable. IndexSearcher searcher = NewSearcher(reader); Assert.AreEqual(1, searcher.Search(new MatchAllDocsQuery(), 10).TotalHits); // Now search w/ a Filter which returns a null DocIdSet Filter f = new FilterAnonymousClass(this); Assert.AreEqual(0, searcher.Search(new MatchAllDocsQuery(), f, 10).TotalHits); reader.Dispose(); dir.Dispose(); } private class FilterAnonymousClass : Filter { private readonly TestDocIdSet outerInstance; public FilterAnonymousClass(TestDocIdSet outerInstance) { this.outerInstance = outerInstance; } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { return null; } } [Test] public virtual void TestNullIteratorFilteredDocIdSet() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); doc.Add(NewStringField("c", "val", Field.Store.NO)); writer.AddDocument(doc); IndexReader reader = writer.GetReader(); writer.Dispose(); // First verify the document is searchable. IndexSearcher searcher = NewSearcher(reader); Assert.AreEqual(1, searcher.Search(new MatchAllDocsQuery(), 10).TotalHits); // Now search w/ a Filter which returns a null DocIdSet Filter f = new FilterAnonymousClass2(this); Assert.AreEqual(0, searcher.Search(new MatchAllDocsQuery(), f, 10).TotalHits); reader.Dispose(); dir.Dispose(); } private class FilterAnonymousClass2 : Filter { private readonly TestDocIdSet outerInstance; public FilterAnonymousClass2(TestDocIdSet outerInstance) { this.outerInstance = outerInstance; } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { DocIdSet innerNullIteratorSet = new DocIdSetAnonymousClass2(this); return new FilteredDocIdSetAnonymousClass2(this, innerNullIteratorSet); } private class DocIdSetAnonymousClass2 : DocIdSet { private readonly FilterAnonymousClass2 outerInstance; public DocIdSetAnonymousClass2(FilterAnonymousClass2 outerInstance) { this.outerInstance = outerInstance; } public override DocIdSetIterator GetIterator() { return null; } } private class FilteredDocIdSetAnonymousClass2 : FilteredDocIdSet { private readonly FilterAnonymousClass2 outerInstance; public FilteredDocIdSetAnonymousClass2(FilterAnonymousClass2 outerInstance, DocIdSet innerNullIteratorSet) : base(innerNullIteratorSet) { this.outerInstance = outerInstance; } protected override bool Match(int docid) { return true; } } } } }
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.Service; using Microsoft.AspNetCore.Identity.Service.Extensions; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using SpentBook.Web.Identity.Models; using SpentBook.Web.Identity.Models.ManageViewModels; using SpentBook.Web.Identity.Services; namespace SpentBook.Web.Identity.Controllers { [Authorize(IdentityServiceOptions.LoginPolicyName)] [Area("IdentityService")] [IdentityServiceRoute("[controller]/[action]")] public class ManageController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public ManageController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<ManageController>(); } [HttpGet] public async Task<IActionResult> Index(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var model = new IndexViewModel { HasPassword = await _userManager.HasPasswordAsync(user), PhoneNumber = await _userManager.GetPhoneNumberAsync(user), TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user), Logins = await _userManager.GetLoginsAsync(user), BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user) }; return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account) { ManageMessageId? message = ManageMessageId.Error; var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); message = ManageMessageId.RemoveLoginSuccess; } } return RedirectToAction(nameof(ManageLogins), new { Message = message }); } [HttpGet] public IActionResult AddPhoneNumber() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } // Generate the token and send it var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber); await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code); return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber }); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EnableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, true); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(1, "User enabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> DisableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, false); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(2, "User disabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } [HttpGet] public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber) { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, phoneNumber); // Send an SMS to verify the phone number return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess }); } } // If we got this far, something failed, redisplay the form ModelState.AddModelError(string.Empty, "Failed to verify phone number"); return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemovePhoneNumber() { var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.SetPhoneNumberAsync(user, null); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess }); } } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } [HttpGet] public IActionResult ChangePassword() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User changed their password successfully."); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } [HttpGet] public IActionResult SetPassword() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.AddPasswordAsync(user, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } [HttpGet] public async Task<IActionResult> ManageLogins(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.AddLoginSuccess ? "The external login was added." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var userLogins = await _userManager.GetLoginsAsync(user); var schemes = await _signInManager.GetExternalAuthenticationSchemesAsync(); var otherLogins = schemes.Where(auth => userLogins.All(ul => auth.Name != ul.LoginProvider)).ToList(); ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins }); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LinkLogin(string provider) { // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityCookieOptions.ExternalScheme); // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Action(nameof(LinkLoginCallback), "Manage"); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User)); return Challenge(properties, provider); } [HttpGet] public async Task<ActionResult> LinkLoginCallback() { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user)); if (info == null) { return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error }); } var result = await _userManager.AddLoginAsync(user, info); var message = ManageMessageId.Error; if (result.Succeeded) { message = ManageMessageId.AddLoginSuccess; // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityCookieOptions.ExternalScheme); } return RedirectToAction(nameof(ManageLogins), new { Message = message }); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } public enum ManageMessageId { AddPhoneSuccess, AddLoginSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } private Task<ApplicationUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } #endregion } }
namespace MindEngine.Parser { using System; using System.Xml; using Core; using Core.Util; using Microsoft.Xna.Framework; public static class MMXmlReader { public static int ReadAttributeInt(XmlElement valueElement, string valueAttribute, int valueDefault, bool valueRequired) { return (int)ReadAttribute(valueElement, valueAttribute, typeof(int), valueDefault, valueRequired); } /// <remarks> /// The primary difference from the overloaded version is that it allow /// inherited from parent value when return value already has parent's value. /// </remarks> public static void ReadAttributeInt(XmlElement valueElement, string valueAttribute, ref int value, int valueDefault, bool valueRequired, bool valueInherited) { // Boxing the integer var valueObject = (object)value; // There is no need to unbox the value object ReadAttribute(valueElement, valueAttribute, ref valueObject, typeof(int), valueDefault, valueRequired, valueInherited); } public static bool ReadAttributeBool(XmlElement valueElement, string valueAttribute, bool valueDefault, bool valueRequired) { return (bool)ReadAttribute(valueElement, valueAttribute, typeof(bool), valueDefault, valueRequired); } /// <remarks> /// The primary difference from the overloaded version is that it allow /// inherited from parent value when return value already has parent's value. /// </remarks> public static void ReadAttributeBool(XmlElement valueElement, string valueAttribute, ref bool value, bool valueDefault, bool valueRequired, bool valueInherited) { var valueObject = (object)value; ReadAttribute(valueElement, valueAttribute, ref valueObject, typeof(bool), valueDefault, valueRequired, valueInherited); } public static byte ReadAttributeByte( XmlElement valueElement, string valueAttribute, byte valueDefault, bool valueRequired) { return (byte)ReadAttribute(valueElement, valueAttribute, typeof(byte), valueDefault, valueRequired); } /// <remarks> /// The primary difference from the overloaded version is that it allow /// inherited from parent value when return value already has parent's value. /// </remarks> public static void ReadAttributeByte(XmlElement valueElement, string valueAttribute, ref byte value, byte valueDefault, bool valueRequired, bool valueInherited) { var valueObject = (object)value; ReadAttribute(valueElement, valueAttribute, ref valueObject, typeof(byte), valueDefault, valueRequired, valueInherited); } /// <remarks> /// The primary difference from the overloaded version is that it allow /// inherited from parent value when return value already has parent's value. /// </remarks> public static void ReadAttributeVector2(XmlElement valueElement, string valueAttribute, ref Vector2 value, Vector2 valueDefault, bool valueRequired, bool valueInherited) { var valueString = value.ToString(); ReadAttributeString(valueElement, valueAttribute, ref valueString, valueDefault.ToString(), valueRequired, valueInherited); try { value = MMVectorConverter.ParseVector2(valueString); } catch (Exception) { value = valueDefault; } } public static Vector2 ReadAttributeVector2(XmlElement valueElement, string valueAttribute, Vector2 valueDefault, bool valueRequired) { var valueString = ReadAttributeString(valueElement, valueAttribute, valueDefault.ToString(), valueRequired); try { return MMVectorConverter.ParseVector2(valueString); } catch (Exception) { return valueDefault; } } /// <remarks> /// The primary difference from the overloaded version is that it allow /// inherited from parent value when return value already has parent's value. /// </remarks> public static void ReadAttributeColor(XmlElement valueElement, string valueAttribute, ref Color value, Color valueDefault, bool valueRequired, bool valueInherited) { var valueString = MMColorConverter.ToArgbHexString(value); ReadAttributeString(valueElement, valueAttribute, ref valueString, MMColorConverter.ToArgbHexString(valueDefault), valueRequired, valueInherited); try { value = MMColorConverter.ParseArgbHex(valueString); } catch (Exception) { value = valueDefault; } } public static Color ReadAttributeColor(XmlElement valueElement, string valueAttribute, Color valueDefault, bool valueRequired) { var valueString = ReadAttributeString(valueElement, valueAttribute, MMColorConverter.ToArgbHexString(valueDefault), valueRequired); try { return MMColorConverter.ParseArgbHex(valueString); } catch (Exception) { return valueDefault; } } public static string ReadAttributeString(XmlElement valueElement, string valueAttribute, string valueDefault, bool valueRequired) { if (valueElement != null && valueElement.HasAttribute(valueAttribute)) { return valueElement.Attributes[valueAttribute].Value; } else if (valueRequired) { throw new Exception( $@"Missing required attribute ""{valueAttribute}"" in the file."); } else { return valueDefault; } } /// <param name="value"> /// Return value. If you want to use value inheritance, you need to pass /// the inherited value in here. Ref parameter makes it possible for /// value to pass into argument. /// </param> /// <remarks> /// The primary difference from the overloaded version is that it allow /// inherited from parent value when return value already has parent's value. /// </remarks> public static void ReadAttributeString(XmlElement valueElement, string valueAttribute, ref string value, string valueDefault, bool valueRequired, bool valueInherited) { if (valueElement != null && valueElement.HasAttribute(valueAttribute)) { value = valueElement.Attributes[valueAttribute].Value; } else if (valueInherited) { // Change nothing to existing return value } else if (valueRequired) { throw new ArgumentException( $@"Missing required attribute ""{valueAttribute}"" in the file."); } else { // Set default value into ref value = valueDefault; } } /// <remarks> /// The primary difference from the overloaded version is that it allow /// inherited from parent value when return value already has parent's value. /// </remarks> private static void ReadAttribute(XmlElement valueElement, string valueAttribute, ref object value, Type valueType, object valueDefault, bool valueRequired, bool valueInherited) { // Necessary to make ref to work here var valueString = value.ToString(); ReadAttributeString(valueElement, valueAttribute, ref valueString, valueDefault.ToString(), valueRequired, valueInherited); value = MMValueReader.ReadValue(valueString, valueType, valueDefault); } private static object ReadAttribute(XmlElement valueElement, string valueAttribute, Type valueType, object valueDefault, bool valueRequired) { var valueString = ReadAttributeString(valueElement, valueAttribute, valueDefault.ToString(), valueRequired); return MMValueReader.ReadValue(valueString, valueType, valueDefault); } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Xml; using System.Text; using System.Drawing; using System.Globalization; namespace fyiReporting.RDL { ///<summary> /// The style of the border colors. Expressions for all sides as well as default expression. ///</summary> [Serializable] internal class StyleBorderColor : ReportLink { Expression _Default; // (Color) Color of the border (unless overridden for a specific // side). Default: Black. Expression _Left; // (Color) Color of the left border Expression _Right; // (Color) Color of the right border Expression _Top; // (Color) Color of the top border Expression _Bottom; // (Color) Color of the bottom border internal StyleBorderColor(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p) { _Default=null; _Left=null; _Right=null; _Top=null; _Bottom=null; // Loop thru all the child nodes foreach(XmlNode xNodeLoop in xNode.ChildNodes) { if (xNodeLoop.NodeType != XmlNodeType.Element) continue; switch (xNodeLoop.Name) { case "Default": _Default = new Expression(r, this, xNodeLoop, ExpressionType.Color); break; case "Left": _Left = new Expression(r, this, xNodeLoop, ExpressionType.Color); break; case "Right": _Right = new Expression(r, this, xNodeLoop, ExpressionType.Color); break; case "Top": _Top = new Expression(r, this, xNodeLoop, ExpressionType.Color); break; case "Bottom": _Bottom = new Expression(r, this, xNodeLoop, ExpressionType.Color); break; default: // don't know this element - log it OwnerReport.rl.LogError(4, "Unknown BorderColor element '" + xNodeLoop.Name + "' ignored."); break; } } } // Handle parsing of function in final pass override internal void FinalPass() { if (_Default != null) _Default.FinalPass(); if (_Left != null) _Left.FinalPass(); if (_Right != null) _Right.FinalPass(); if (_Top != null) _Top.FinalPass(); if (_Bottom != null) _Bottom.FinalPass(); return; } // Generate a CSS string from the specified styles internal string GetCSS(Report rpt, Row row, bool bDefaults) { StringBuilder sb = new StringBuilder(); if (_Default != null) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "border-color:{0};",_Default.EvaluateString(rpt, row)); else if (bDefaults) sb.Append("border-color:black;"); if (_Left != null) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "border-left:{0};",_Left.EvaluateString(rpt, row)); if (_Right != null) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "border-right:{0};",_Right.EvaluateString(rpt, row)); if (_Top != null) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "border-top:{0};",_Top.EvaluateString(rpt, row)); if (_Bottom != null) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "border-bottom:{0};",_Bottom.EvaluateString(rpt, row)); return sb.ToString(); } internal bool IsConstant() { bool rc = true; if (_Default != null) rc = _Default.IsConstant(); if (!rc) return false; if (_Left != null) rc = _Left.IsConstant(); if (!rc) return false; if (_Right != null) rc = _Right.IsConstant(); if (!rc) return false; if (_Top != null) rc = _Top.IsConstant(); if (!rc) return false; if (_Bottom != null) rc = _Bottom.IsConstant(); return rc; } static internal string GetCSSDefaults() { return "border-color:black;"; } internal Expression Default { get { return _Default; } set { _Default = value; } } internal Color EvalDefault(Report rpt, Row r) { if (_Default == null) return System.Drawing.Color.Black; string c = _Default.EvaluateString(rpt, r); return XmlUtil.ColorFromHtml(c, System.Drawing.Color.Black, rpt); } internal Expression Left { get { return _Left; } set { _Left = value; } } internal Color EvalLeft(Report rpt, Row r) { if (_Left == null) return EvalDefault(rpt, r); string c = _Left.EvaluateString(rpt, r); return XmlUtil.ColorFromHtml(c, System.Drawing.Color.Black, rpt); } internal Expression Right { get { return _Right; } set { _Right = value; } } internal Color EvalRight(Report rpt, Row r) { if (_Right == null) return EvalDefault(rpt, r); string c = _Right.EvaluateString(rpt, r); return XmlUtil.ColorFromHtml(c, System.Drawing.Color.Black, rpt); } internal Expression Top { get { return _Top; } set { _Top = value; } } internal Color EvalTop(Report rpt, Row r) { if (_Top == null) return EvalDefault(rpt, r); string c = _Top.EvaluateString(rpt, r); return XmlUtil.ColorFromHtml(c, System.Drawing.Color.Black, rpt); } internal Expression Bottom { get { return _Bottom; } set { _Bottom = value; } } internal Color EvalBottom(Report rpt, Row r) { if (_Bottom == null) return EvalDefault(rpt, r); string c = _Bottom.EvaluateString(rpt, r); return XmlUtil.ColorFromHtml(c, System.Drawing.Color.Black, rpt); } } }
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.IO; using System.Linq; namespace ForieroEditor.Platforms.iOS.Xcode.PBX { class PropertyCommentChecker { private int m_Level; private bool m_All; private List<List<string>> m_Props; /* The argument is an array of matcher strings each of which determine whether a property with a certain path needs to be decorated with a comment. A path is a number of path elements concatenated by '/'. The last path element is either: the key if we're referring to a dict key the value if we're referring to a value in an array the value if we're referring to a value in a dict All other path elements are either: the key if the container is dict '*' if the container is array Path matcher has the same structure as a path, except that any of the elements may be '*'. Matcher matches a path if both have the same number of elements and for each pair matcher element is the same as path element or is '*'. a/b/c matches a/b/c but not a/b nor a/b/c/d a/* /c matches a/d/c but not a/b nor a/b/c/d * /* /* matches any path from three elements */ protected PropertyCommentChecker(int level, List<List<string>> props) { m_Level = level; m_All = false; m_Props = props; } public PropertyCommentChecker() { m_Level = 0; m_All = false; m_Props = new List<List<string>>(); } public PropertyCommentChecker(IEnumerable<string> props) { m_Level = 0; m_All = false; m_Props = new List<List<string>>(); foreach (var prop in props) { m_Props.Add(new List<string>(prop.Split('/'))); } } bool CheckContained(string prop) { if (m_All) return true; foreach (var list in m_Props) { if (list.Count == m_Level+1) { if (list[m_Level] == prop) return true; if (list[m_Level] == "*") { m_All = true; // short-circuit all at this level return true; } } } return false; } public bool CheckStringValueInArray(string value) { return CheckContained(value); } public bool CheckKeyInDict(string key) { return CheckContained(key); } public bool CheckStringValueInDict(string key, string value) { foreach (var list in m_Props) { if (list.Count == m_Level + 2) { if ((list[m_Level] == "*" || list[m_Level] == key) && list[m_Level+1] == "*" || list[m_Level+1] == value) return true; } } return false; } public PropertyCommentChecker NextLevel(string prop) { var newList = new List<List<string>>(); foreach (var list in m_Props) { if (list.Count <= m_Level+1) continue; if (list[m_Level] == "*" || list[m_Level] == prop) newList.Add(list); } return new PropertyCommentChecker(m_Level + 1, newList); } } class Serializer { public static PBXElementDict ParseTreeAST(TreeAST ast, TokenList tokens, string text) { var el = new PBXElementDict(); foreach (var kv in ast.values) { PBXElementString key = ParseIdentifierAST(kv.key, tokens, text); PBXElement value = ParseValueAST(kv.value, tokens, text); el[key.value] = value; } return el; } public static PBXElementArray ParseArrayAST(ArrayAST ast, TokenList tokens, string text) { var el = new PBXElementArray(); foreach (var v in ast.values) { el.values.Add(ParseValueAST(v, tokens, text)); } return el; } public static PBXElement ParseValueAST(ValueAST ast, TokenList tokens, string text) { if (ast is TreeAST) return ParseTreeAST((TreeAST)ast, tokens, text); if (ast is ArrayAST) return ParseArrayAST((ArrayAST)ast, tokens, text); if (ast is IdentifierAST) return ParseIdentifierAST((IdentifierAST)ast, tokens, text); return null; } public static PBXElementString ParseIdentifierAST(IdentifierAST ast, TokenList tokens, string text) { Token tok = tokens[ast.value]; string value; switch (tok.type) { case TokenType.String: value = text.Substring(tok.begin, tok.end - tok.begin); return new PBXElementString(value); case TokenType.QuotedString: value = text.Substring(tok.begin, tok.end - tok.begin); value = PBXStream.UnquoteString(value); return new PBXElementString(value); default: throw new Exception("Internal parser error"); } } static string k_Indent = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; static string GetIndent(int indent) { return k_Indent.Substring(0, indent); } static void WriteStringImpl(StringBuilder sb, string s, bool comment, GUIDToCommentMap comments) { if (comment) comments.WriteStringBuilder(sb, s); else sb.Append(PBXStream.QuoteStringIfNeeded(s)); } public static void WriteDictKeyValue(StringBuilder sb, string key, PBXElement value, int indent, bool compact, PropertyCommentChecker checker, GUIDToCommentMap comments) { if (!compact) { sb.Append("\n"); sb.Append(GetIndent(indent)); } WriteStringImpl(sb, key, checker.CheckKeyInDict(key), comments); sb.Append(" = "); if (value is PBXElementString) WriteStringImpl(sb, value.AsString(), checker.CheckStringValueInDict(key, value.AsString()), comments); else if (value is PBXElementDict) WriteDict(sb, value.AsDict(), indent, compact, checker.NextLevel(key), comments); else if (value is PBXElementArray) WriteArray(sb, value.AsArray(), indent, compact, checker.NextLevel(key), comments); sb.Append(";"); if (compact) sb.Append(" "); } public static void WriteDict(StringBuilder sb, PBXElementDict el, int indent, bool compact, PropertyCommentChecker checker, GUIDToCommentMap comments) { sb.Append("{"); if (el.Contains("isa")) WriteDictKeyValue(sb, "isa", el["isa"], indent+1, compact, checker, comments); var keys = new List<string>(el.values.Keys); keys.Sort(StringComparer.Ordinal); foreach (var key in keys) { if (key != "isa") WriteDictKeyValue(sb, key, el[key], indent+1, compact, checker, comments); } if (!compact) { sb.Append("\n"); sb.Append(GetIndent(indent)); } sb.Append("}"); } public static void WriteArray(StringBuilder sb, PBXElementArray el, int indent, bool compact, PropertyCommentChecker checker, GUIDToCommentMap comments) { sb.Append("("); foreach (var value in el.values) { if (!compact) { sb.Append("\n"); sb.Append(GetIndent(indent+1)); } if (value is PBXElementString) WriteStringImpl(sb, value.AsString(), checker.CheckStringValueInArray(value.AsString()), comments); else if (value is PBXElementDict) WriteDict(sb, value.AsDict(), indent+1, compact, checker.NextLevel("*"), comments); else if (value is PBXElementArray) WriteArray(sb, value.AsArray(), indent+1, compact, checker.NextLevel("*"), comments); sb.Append(","); if (compact) sb.Append(" "); } if (!compact) { sb.Append("\n"); sb.Append(GetIndent(indent)); } sb.Append(")"); } } } // namespace ForieroEditor.Platforms.iOS.Xcode
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.GrainDirectory; using Orleans.Runtime.Scheduler; using Orleans.Configuration; using System.Collections.Immutable; using System.Runtime.Serialization; namespace Orleans.Runtime.GrainDirectory { internal class LocalGrainDirectory : ILocalGrainDirectory, ISiloStatusListener { private readonly AdaptiveDirectoryCacheMaintainer maintainer; private readonly ILogger log; private readonly SiloAddress seed; private readonly ISiloStatusOracle siloStatusOracle; private readonly IInternalGrainFactory grainFactory; private readonly object writeLock = new object(); private Action<SiloAddress, SiloStatus> catalogOnSiloRemoved; private DirectoryMembership directoryMembership = DirectoryMembership.Default; // Consider: move these constants into an apropriate place internal const int HOP_LIMIT = 6; // forward a remote request no more than 5 times public static readonly TimeSpan RETRY_DELAY = TimeSpan.FromMilliseconds(200); // Pause 200ms between forwards to let the membership directory settle down protected SiloAddress Seed { get { return seed; } } internal ILogger Logger { get { return log; } } // logger is shared with classes that manage grain directory internal bool Running; internal SiloAddress MyAddress { get; private set; } internal IGrainDirectoryCache DirectoryCache { get; private set; } internal GrainDirectoryPartition DirectoryPartition { get; private set; } public RemoteGrainDirectory RemoteGrainDirectory { get; private set; } public RemoteGrainDirectory CacheValidator { get; private set; } internal GrainDirectoryHandoffManager HandoffManager { get; private set; } public string ClusterId { get; } private readonly CounterStatistic localLookups; private readonly CounterStatistic localSuccesses; private readonly CounterStatistic fullLookups; private readonly CounterStatistic cacheLookups; private readonly CounterStatistic cacheSuccesses; private readonly CounterStatistic registrationsIssued; private readonly CounterStatistic registrationsSingleActIssued; private readonly CounterStatistic unregistrationsIssued; private readonly CounterStatistic unregistrationsManyIssued; private readonly IntValueStatistic directoryPartitionCount; internal readonly CounterStatistic RemoteLookupsSent; internal readonly CounterStatistic RemoteLookupsReceived; internal readonly CounterStatistic LocalDirectoryLookups; internal readonly CounterStatistic LocalDirectorySuccesses; internal readonly CounterStatistic CacheValidationsSent; internal readonly CounterStatistic CacheValidationsReceived; internal readonly CounterStatistic RegistrationsLocal; internal readonly CounterStatistic RegistrationsRemoteSent; internal readonly CounterStatistic RegistrationsRemoteReceived; internal readonly CounterStatistic RegistrationsSingleActLocal; internal readonly CounterStatistic RegistrationsSingleActRemoteSent; internal readonly CounterStatistic RegistrationsSingleActRemoteReceived; internal readonly CounterStatistic UnregistrationsLocal; internal readonly CounterStatistic UnregistrationsRemoteSent; internal readonly CounterStatistic UnregistrationsRemoteReceived; internal readonly CounterStatistic UnregistrationsManyRemoteSent; internal readonly CounterStatistic UnregistrationsManyRemoteReceived; public LocalGrainDirectory( IServiceProvider serviceProvider, ILocalSiloDetails siloDetails, ISiloStatusOracle siloStatusOracle, IInternalGrainFactory grainFactory, Factory<GrainDirectoryPartition> grainDirectoryPartitionFactory, IOptions<DevelopmentClusterMembershipOptions> developmentClusterMembershipOptions, IOptions<GrainDirectoryOptions> grainDirectoryOptions, ILoggerFactory loggerFactory) { this.log = loggerFactory.CreateLogger<LocalGrainDirectory>(); var clusterId = siloDetails.ClusterId; MyAddress = siloDetails.SiloAddress; this.siloStatusOracle = siloStatusOracle; this.grainFactory = grainFactory; ClusterId = clusterId; DirectoryCache = GrainDirectoryCacheFactory.CreateGrainDirectoryCache(serviceProvider, grainDirectoryOptions.Value); maintainer = GrainDirectoryCacheFactory.CreateGrainDirectoryCacheMaintainer( this, this.DirectoryCache, grainFactory, loggerFactory); var primarySiloEndPoint = developmentClusterMembershipOptions.Value.PrimarySiloEndpoint; if (primarySiloEndPoint != null) { this.seed = this.MyAddress.Endpoint.Equals(primarySiloEndPoint) ? this.MyAddress : SiloAddress.New(primarySiloEndPoint, 0); } DirectoryPartition = grainDirectoryPartitionFactory(); HandoffManager = new GrainDirectoryHandoffManager(this, siloStatusOracle, grainFactory, grainDirectoryPartitionFactory, loggerFactory); RemoteGrainDirectory = new RemoteGrainDirectory(this, Constants.DirectoryServiceType, loggerFactory); CacheValidator = new RemoteGrainDirectory(this, Constants.DirectoryCacheValidatorType, loggerFactory); // add myself to the list of members AddServer(MyAddress); Func<SiloAddress, string> siloAddressPrint = (SiloAddress addr) => String.Format("{0}/{1:X}", addr.ToLongString(), addr.GetConsistentHashCode()); localLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_ISSUED); localSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_SUCCESSES); fullLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_FULL_ISSUED); RemoteLookupsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_SENT); RemoteLookupsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_RECEIVED); LocalDirectoryLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_ISSUED); LocalDirectorySuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_SUCCESSES); cacheLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_ISSUED); cacheSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_SUCCESSES); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_HITRATIO, () => { long delta1, delta2; long curr1 = cacheSuccesses.GetCurrentValueAndDelta(out delta1); long curr2 = cacheLookups.GetCurrentValueAndDelta(out delta2); return String.Format("{0}, Delta={1}", (curr2 != 0 ? (float)curr1 / (float)curr2 : 0) ,(delta2 !=0 ? (float)delta1 / (float)delta2 : 0)); }); CacheValidationsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_SENT); CacheValidationsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_RECEIVED); registrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_ISSUED); RegistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_LOCAL); RegistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_SENT); RegistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_RECEIVED); registrationsSingleActIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_ISSUED); RegistrationsSingleActLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_LOCAL); RegistrationsSingleActRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_SENT); RegistrationsSingleActRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_RECEIVED); unregistrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_ISSUED); UnregistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_LOCAL); UnregistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_SENT); UnregistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_RECEIVED); unregistrationsManyIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_ISSUED); UnregistrationsManyRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_SENT); UnregistrationsManyRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_RECEIVED); directoryPartitionCount = IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_PARTITION_SIZE, () => DirectoryPartition.Count); IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGDISTANCE, () => RingDistanceToSuccessor()); FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGPERCENTAGE, () => (((float)this.RingDistanceToSuccessor()) / ((float)(int.MaxValue * 2L))) * 100); FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_AVERAGERINGPERCENTAGE, () => { var ring = this.directoryMembership.MembershipRingList; return ring.Count == 0 ? 0 : ((float)100 / (float)ring.Count); }); IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_RINGSIZE, () => this.directoryMembership.MembershipRingList.Count); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING, () => { var ring = this.directoryMembership.MembershipRingList; return Utils.EnumerableToString(ring, siloAddressPrint); }); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_PREDECESSORS, () => Utils.EnumerableToString(this.FindPredecessors(this.MyAddress, 1), siloAddressPrint)); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_SUCCESSORS, () => Utils.EnumerableToString(this.FindSuccessors(this.MyAddress, 1), siloAddressPrint)); } public void Start() { log.Info("Start"); Running = true; if (maintainer != null) { maintainer.Start(); } } // Note that this implementation stops processing directory change requests (Register, Unregister, etc.) when the Stop event is raised. // This means that there may be a short period during which no silo believes that it is the owner of directory information for a set of // grains (for update purposes), which could cause application requests that require a new activation to be created to time out. // The alternative would be to allow the silo to process requests after it has handed off its partition, in which case those changes // would receive successful responses but would not be reflected in the eventual state of the directory. // It's easy to change this, if we think the trade-off is better the other way. public void Stop() { // This will cause remote write requests to be forwarded to the silo that will become the new owner. // Requests might bounce back and forth for a while as membership stabilizes, but they will either be served by the // new owner of the grain, or will wind up failing. In either case, we avoid requests succeeding at this silo after we've // begun stopping, which could cause them to not get handed off to the new owner. //mark Running as false will exclude myself from CalculateGrainDirectoryPartition(grainId) Running = false; if (maintainer != null) { maintainer.Stop(); } DirectoryPartition.Clear(); DirectoryCache.Clear(); } /// <inheritdoc /> public void SetSiloRemovedCatalogCallback(Action<SiloAddress, SiloStatus> callback) { if (callback == null) throw new ArgumentNullException(nameof(callback)); lock (this.writeLock) { this.catalogOnSiloRemoved = callback; } } protected void AddServer(SiloAddress silo) { lock (this.writeLock) { var existing = this.directoryMembership; if (existing.MembershipCache.Contains(silo)) { // we have already cached this silo return; } // insert new silo in the sorted order long hash = silo.GetConsistentHashCode(); // Find the last silo with hash smaller than the new silo, and insert the latter after (this is why we have +1 here) the former. // Notice that FindLastIndex might return -1 if this should be the first silo in the list, but then // 'index' will get 0, as needed. int index = existing.MembershipRingList.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1; this.directoryMembership = new DirectoryMembership( existing.MembershipRingList.Insert(index, silo), existing.MembershipCache.Add(silo)); HandoffManager.ProcessSiloAddEvent(silo); AdjustLocalDirectory(silo, dead: false); AdjustLocalCache(silo, dead: false); if (log.IsEnabled(LogLevel.Debug)) log.Debug("Silo {0} added silo {1}", MyAddress, silo); } } protected void RemoveServer(SiloAddress silo, SiloStatus status) { lock (this.writeLock) { try { // Only notify the catalog once. Order is important: call BEFORE updating membershipRingList. this.catalogOnSiloRemoved?.Invoke(silo, status); } catch (Exception exc) { log.Error(ErrorCode.Directory_SiloStatusChangeNotification_Exception, String.Format("CatalogSiloStatusListener.SiloStatusChangeNotification has thrown an exception when notified about removed silo {0}.", silo.ToStringWithHashCode()), exc); } var existing = this.directoryMembership; if (!existing.MembershipCache.Contains(silo)) { // we have already removed this silo return; } // the call order is important HandoffManager.ProcessSiloRemoveEvent(silo); this.directoryMembership = new DirectoryMembership( existing.MembershipRingList.Remove(silo), existing.MembershipCache.Remove(silo)); AdjustLocalDirectory(silo, dead: true); AdjustLocalCache(silo, dead: true); if (log.IsEnabled(LogLevel.Debug)) log.Debug("Silo {0} removed silo {1}", MyAddress, silo); } } /// <summary> /// Adjust local directory following the addition/removal of a silo /// </summary> protected void AdjustLocalDirectory(SiloAddress silo, bool dead) { // Determine which activations to remove. var activationsToRemove = new List<(GrainId, ActivationId)>(); foreach (var entry in this.DirectoryPartition.GetItems()) { var (grain, grainInfo) = (entry.Key, entry.Value); if (grainInfo.Activation is { } address) { // Include any activations from dead silos and from predecessors. var siloIsDead = dead && address.SiloAddress.Equals(silo); var siloIsPredecessor = address.SiloAddress.IsPredecessorOf(silo); if (siloIsDead || siloIsPredecessor) { activationsToRemove.Add((grain, address.ActivationId)); } } } // Remove all defunct activations. foreach (var activation in activationsToRemove) { DirectoryPartition.RemoveActivation(activation.Item1, activation.Item2); } } /// Adjust local cache following the removal of a silo by dropping: /// 1) entries that point to activations located on the removed silo /// 2) entries for grains that are now owned by this silo (me) /// 3) entries for grains that were owned by this removed silo - we currently do NOT do that. /// If we did 3, we need to do that BEFORE we change the membershipRingList (based on old Membership). /// We don't do that since first cache refresh handles that. /// Second, since Membership events are not guaranteed to be ordered, we may remove a cache entry that does not really point to a failed silo. /// To do that properly, we need to store for each cache entry who was the directory owner that registered this activation (the original partition owner). protected void AdjustLocalCache(SiloAddress silo, bool dead) { // remove all records of activations located on the removed silo foreach (var tuple in DirectoryCache.KeyValues) { var activationAddress = tuple.ActivationAddress; // 2) remove entries now owned by me (they should be retrieved from my directory partition) if (MyAddress.Equals(CalculateGrainDirectoryPartition(activationAddress.GrainId))) { DirectoryCache.Remove(activationAddress.GrainId); } // 1) remove entries that point to activations located on the removed silo // For dead silos, remove any activation registered to that silo or one of its predecessors. // For new silos, remove any activation registered to one of its predecessors. if (activationAddress.SiloAddress.IsPredecessorOf(silo) || (activationAddress.SiloAddress.Equals(silo) && dead)) { DirectoryCache.Remove(activationAddress.GrainId); } } } internal List<SiloAddress> FindPredecessors(SiloAddress silo, int count) { var existing = this.directoryMembership; int index = existing.MembershipRingList.FindIndex(elem => elem.Equals(silo)); if (index == -1) { log.Warn(ErrorCode.Runtime_Error_100201, "Got request to find predecessors of silo " + silo + ", which is not in the list of members"); return null; } var result = new List<SiloAddress>(); int numMembers = existing.MembershipRingList.Count; for (int i = index - 1; ((i + numMembers) % numMembers) != index && result.Count < count; i--) { result.Add(existing.MembershipRingList[(i + numMembers) % numMembers]); } return result; } internal List<SiloAddress> FindSuccessors(SiloAddress silo, int count) { var existing = this.directoryMembership; int index = existing.MembershipRingList.FindIndex(elem => elem.Equals(silo)); if (index == -1) { log.Warn(ErrorCode.Runtime_Error_100203, "Got request to find successors of silo " + silo + ", which is not in the list of members"); return null; } var result = new List<SiloAddress>(); int numMembers = existing.MembershipRingList.Count; for (int i = index + 1; i % numMembers != index && result.Count < count; i++) { result.Add(existing.MembershipRingList[i % numMembers]); } return result; } public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { // This silo's status has changed if (!Equals(updatedSilo, MyAddress)) // Status change for some other silo { if (status.IsTerminating()) { // QueueAction up the "Remove" to run on a system turn CacheValidator.WorkItemGroup.QueueAction(() => RemoveServer(updatedSilo, status)); } else if (status == SiloStatus.Active) // do not do anything with SiloStatus.Starting -- wait until it actually becomes active { // QueueAction up the "Remove" to run on a system turn CacheValidator.WorkItemGroup.QueueAction(() => AddServer(updatedSilo)); } } } private bool IsValidSilo(SiloAddress silo) { return this.siloStatusOracle.IsFunctionalDirectory(silo); } /// <summary> /// Finds the silo that owns the directory information for the given grain ID. /// This method will only be null when I'm the only silo in the cluster and I'm shutting down /// </summary> /// <param name="grainId"></param> /// <returns></returns> public SiloAddress CalculateGrainDirectoryPartition(GrainId grainId) { // give a special treatment for special grains if (grainId.IsSystemTarget()) { if (Constants.SystemMembershipTableType.Equals(grainId)) { if (Seed == null) { var errorMsg = $"Development clustering cannot run without a primary silo. " + $"Please configure {nameof(DevelopmentClusterMembershipOptions)}.{nameof(DevelopmentClusterMembershipOptions.PrimarySiloEndpoint)} " + "or provide a primary silo address to the UseDevelopmentClustering extension. " + "Alternatively, you may want to use reliable membership, such as Azure Table."; throw new ArgumentException(errorMsg, "grainId = " + grainId); } } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Silo {0} looked for a system target {1}, returned {2}", MyAddress, grainId, MyAddress); // every silo owns its system targets return MyAddress; } SiloAddress siloAddress = null; int hash = unchecked((int)grainId.GetUniformHashCode()); // excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method. // excludeThisSIloIfStopping flag was removed because we believe that flag complicates things unnecessarily. We can add it back if it turns out that flag // is doing something valuable. bool excludeMySelf = !Running; var existing = this.directoryMembership; if (existing.MembershipRingList.Count == 0) { // If the membership ring is empty, then we're the owner by default unless we're stopping. return !Running ? null : MyAddress; } // need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes for (var index = existing.MembershipRingList.Count - 1; index >= 0; --index) { var item = existing.MembershipRingList[index]; if (IsSiloNextInTheRing(item, hash, excludeMySelf)) { siloAddress = item; break; } } if (siloAddress == null) { // If not found in the traversal, last silo will do (we are on a ring). // We checked above to make sure that the list isn't empty, so this should always be safe. siloAddress = existing.MembershipRingList[existing.MembershipRingList.Count - 1]; // Make sure it's not us... if (siloAddress.Equals(MyAddress) && excludeMySelf) { siloAddress = existing.MembershipRingList.Count > 1 ? existing.MembershipRingList[existing.MembershipRingList.Count - 2] : null; } } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Silo {0} calculated directory partition owner silo {1} for grain {2}: {3} --> {4}", MyAddress, siloAddress, grainId, hash, siloAddress?.GetConsistentHashCode()); return siloAddress; } public SiloAddress CheckIfShouldForward(GrainId grainId, int hopCount, string operationDescription) { SiloAddress owner = CalculateGrainDirectoryPartition(grainId); if (owner == null) { // We don't know about any other silos, and we're stopping, so throw throw new OrleansGrainDirectoryException("Grain directory is stopping"); } if (owner.Equals(MyAddress)) { // if I am the owner, perform the operation locally return null; } if (hopCount >= HOP_LIMIT) { // we are not forwarding because there were too many hops already throw new OrleansException($"Silo {MyAddress} is not owner of {grainId}, cannot forward {operationDescription} to owner {owner} because hop limit is reached"); } // forward to the silo that we think is the owner return owner; } public async Task<AddressAndTag> RegisterAsync(GrainAddress address, int hopCount) { var counterStatistic = hopCount > 0 ? this.RegistrationsSingleActRemoteReceived : this.registrationsSingleActIssued ; counterStatistic.Increment(); // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(address.GrainId, hopCount, "RegisterAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardAddress != null) { await Task.Delay(RETRY_DELAY); forwardAddress = this.CheckIfShouldForward(address.GrainId, hopCount, "RegisterAsync"); if (forwardAddress is object) { int hash = unchecked((int)address.GrainId.GetUniformHashCode()); this.log.LogWarning($"RegisterAsync - It seems we are not the owner of activation {address} (hash: {hash:X}), trying to forward it to {forwardAddress} (hopCount={hopCount})"); } } if (forwardAddress == null) { RegistrationsSingleActLocal.Increment(); var result = DirectoryPartition.AddSingleActivation(address); return result; } else { RegistrationsSingleActRemoteSent.Increment(); // otherwise, notify the owner AddressAndTag result = await GetDirectoryReference(forwardAddress).RegisterAsync(address, hopCount + 1); // Caching optimization: // cache the result of a successfull RegisterSingleActivation call, only if it is not a duplicate activation. // this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup! if (result.Address == null) return result; if (!address.Equals(result.Address) || !IsValidSilo(address.SiloAddress)) return result; // update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup. DirectoryCache.AddOrUpdate(address, result.VersionTag); return result; } } public Task UnregisterAfterNonexistingActivation(GrainAddress addr, SiloAddress origin) { log.Trace("UnregisterAfterNonexistingActivation addr={0} origin={1}", addr, origin); if (origin == null || this.directoryMembership.MembershipCache.Contains(origin)) { // the request originated in this cluster, call unregister here return UnregisterAsync(addr, UnregistrationCause.NonexistentActivation, 0); } else { // the request originated in another cluster, call unregister there var remoteDirectory = GetDirectoryReference(origin); return remoteDirectory.UnregisterAsync(addr, UnregistrationCause.NonexistentActivation); } } public async Task UnregisterAsync(GrainAddress address, UnregistrationCause cause, int hopCount) { (hopCount > 0 ? UnregistrationsRemoteReceived : unregistrationsIssued).Increment(); if (hopCount == 0) InvalidateCacheEntry(address); // see if the owner is somewhere else (returns null if we are owner) var forwardaddress = this.CheckIfShouldForward(address.GrainId, hopCount, "UnregisterAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardaddress != null) { await Task.Delay(RETRY_DELAY); forwardaddress = this.CheckIfShouldForward(address.GrainId, hopCount, "UnregisterAsync"); this.log.LogWarning($"UnregisterAsync - It seems we are not the owner of activation {address}, trying to forward it to {forwardaddress} (hopCount={hopCount})"); } if (forwardaddress == null) { // we are the owner UnregistrationsLocal.Increment(); DirectoryPartition.RemoveActivation(address.GrainId, address.ActivationId, cause); } else { UnregistrationsRemoteSent.Increment(); // otherwise, notify the owner await GetDirectoryReference(forwardaddress).UnregisterAsync(address, cause, hopCount + 1); } } private void AddToDictionary<K,V>(ref Dictionary<K, List<V>> dictionary, K key, V value) { if (dictionary == null) dictionary = new Dictionary<K,List<V>>(); List<V> list; if (! dictionary.TryGetValue(key, out list)) dictionary[key] = list = new List<V>(); list.Add(value); } // helper method to avoid code duplication inside UnregisterManyAsync private void UnregisterOrPutInForwardList(IEnumerable<GrainAddress> addresses, UnregistrationCause cause, int hopCount, ref Dictionary<SiloAddress, List<GrainAddress>> forward, List<Task> tasks, string context) { foreach (var address in addresses) { // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(address.GrainId, hopCount, context); if (forwardAddress != null) { AddToDictionary(ref forward, forwardAddress, address); } else { // we are the owner UnregistrationsLocal.Increment(); DirectoryPartition.RemoveActivation(address.GrainId, address.ActivationId, cause); } } } public async Task UnregisterManyAsync(List<GrainAddress> addresses, UnregistrationCause cause, int hopCount) { (hopCount > 0 ? UnregistrationsManyRemoteReceived : unregistrationsManyIssued).Increment(); Dictionary<SiloAddress, List<GrainAddress>> forwardlist = null; var tasks = new List<Task>(); UnregisterOrPutInForwardList(addresses, cause, hopCount, ref forwardlist, tasks, "UnregisterManyAsync"); // before forwarding to other silos, we insert a retry delay and re-check destination if (hopCount > 0 && forwardlist != null) { await Task.Delay(RETRY_DELAY); Dictionary<SiloAddress, List<GrainAddress>> forwardlist2 = null; UnregisterOrPutInForwardList(addresses, cause, hopCount, ref forwardlist2, tasks, "UnregisterManyAsync"); forwardlist = forwardlist2; if (forwardlist != null) { this.log.LogWarning($"RegisterAsync - It seems we are not the owner of some activations, trying to forward it to {forwardlist.Count} silos (hopCount={hopCount})"); } } // forward the requests if (forwardlist != null) { foreach (var kvp in forwardlist) { UnregistrationsManyRemoteSent.Increment(); tasks.Add(GetDirectoryReference(kvp.Key).UnregisterManyAsync(kvp.Value, cause, hopCount + 1)); } } // wait for all the requests to finish await Task.WhenAll(tasks); } public bool LocalLookup(GrainId grain, out AddressAndTag result) { localLookups.Increment(); SiloAddress silo = CalculateGrainDirectoryPartition(grain); if (log.IsEnabled(LogLevel.Debug)) log.Debug("Silo {0} tries to lookup for {1}-->{2} ({3}-->{4})", MyAddress, grain, silo, grain.GetUniformHashCode(), silo?.GetConsistentHashCode()); //this will only happen if I'm the only silo in the cluster and I'm shutting down if (silo == null) { if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup mine {0}=null", grain); result = new AddressAndTag(); return false; } // handle cache cacheLookups.Increment(); var address = GetLocalCacheData(grain); if (address != default) { result = new AddressAndTag { Address = address, }; if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup cache {0}={1}", grain, result.Address); cacheSuccesses.Increment(); localSuccesses.Increment(); return true; } // check if we own the grain if (silo.Equals(MyAddress)) { LocalDirectoryLookups.Increment(); result = GetLocalDirectoryData(grain); if (result.Address == null) { // it can happen that we cannot find the grain in our partition if there were // some recent changes in the membership if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup mine {0}=null", grain); return false; } if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup mine {0}={1}", grain, result.Address); LocalDirectorySuccesses.Increment(); localSuccesses.Increment(); return true; } if (log.IsEnabled(LogLevel.Trace)) log.Trace("TryFullLookup else {0}=null", grain); result = default; return false; } public AddressAndTag GetLocalDirectoryData(GrainId grain) { return DirectoryPartition.LookUpActivation(grain); } public GrainAddress GetLocalCacheData(GrainId grain) { if (DirectoryCache.LookUp(grain, out var cache) && IsValidSilo(cache.SiloAddress)) { return cache; } return null; } public async Task<AddressAndTag> LookupAsync(GrainId grainId, int hopCount = 0) { (hopCount > 0 ? RemoteLookupsReceived : fullLookups).Increment(); // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardAddress != null) { await Task.Delay(RETRY_DELAY); forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync"); if (forwardAddress is object) { int hash = unchecked((int)grainId.GetUniformHashCode()); this.log.LogWarning($"LookupAsync - It seems we are not the owner of grain {grainId} (hash: {hash:X}), trying to forward it to {forwardAddress} (hopCount={hopCount})"); } } if (forwardAddress == null) { // we are the owner LocalDirectoryLookups.Increment(); var localResult = DirectoryPartition.LookUpActivation(grainId); if (localResult.Address == null) { // it can happen that we cannot find the grain in our partition if there were // some recent changes in the membership if (log.IsEnabled(LogLevel.Trace)) log.Trace("FullLookup mine {0}=none", grainId); localResult.Address = default; localResult.VersionTag = GrainInfo.NO_ETAG; return localResult; } if (log.IsEnabled(LogLevel.Trace)) log.Trace("FullLookup mine {0}={1}", grainId, localResult.Address); LocalDirectorySuccesses.Increment(); return localResult; } else { // Just a optimization. Why sending a message to someone we know is not valid. if (!IsValidSilo(forwardAddress)) { throw new OrleansException($"Current directory at {MyAddress} is not stable to perform the lookup for grainId {grainId} (it maps to {forwardAddress}, which is not a valid silo). Retry later."); } RemoteLookupsSent.Increment(); var result = await GetDirectoryReference(forwardAddress).LookupAsync(grainId, hopCount + 1); // update the cache if (result.Address is { } address && IsValidSilo(address.SiloAddress)) { DirectoryCache.AddOrUpdate(address, result.VersionTag); } if (log.IsEnabled(LogLevel.Trace)) log.Trace("FullLookup remote {0}={1}", grainId, result.Address); return result; } } public async Task DeleteGrainAsync(GrainId grainId, int hopCount) { // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardAddress != null) { await Task.Delay(RETRY_DELAY); forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync"); this.log.LogWarning($"DeleteGrainAsync - It seems we are not the owner of grain {grainId}, trying to forward it to {forwardAddress} (hopCount={hopCount})"); } if (forwardAddress == null) { // we are the owner DirectoryPartition.RemoveGrain(grainId); } else { // otherwise, notify the owner DirectoryCache.Remove(grainId); await GetDirectoryReference(forwardAddress).DeleteGrainAsync(grainId, hopCount + 1); } } public void InvalidateCacheEntry(GrainId grainId) { DirectoryCache.Remove(grainId); } public void InvalidateCacheEntry(GrainAddress activationAddress) { DirectoryCache.Remove(activationAddress); } /// <summary> /// For testing purposes only. /// Returns the silo that this silo thinks is the primary owner of directory information for /// the provided grain ID. /// </summary> /// <param name="grain"></param> /// <returns></returns> public SiloAddress GetPrimaryForGrain(GrainId grain) { return CalculateGrainDirectoryPartition(grain); } public override string ToString() { var sb = new StringBuilder(); long localLookupsDelta; long localLookupsCurrent = localLookups.GetCurrentValueAndDelta(out localLookupsDelta); long localLookupsSucceededDelta; long localLookupsSucceededCurrent = localSuccesses.GetCurrentValueAndDelta(out localLookupsSucceededDelta); long fullLookupsDelta; long fullLookupsCurrent = fullLookups.GetCurrentValueAndDelta(out fullLookupsDelta); long directoryPartitionSize = directoryPartitionCount.GetCurrentValue(); sb.AppendLine("Local Grain Directory:"); sb.AppendFormat(" Local partition: {0} entries", directoryPartitionSize).AppendLine(); sb.AppendLine(" Since last call:"); sb.AppendFormat(" Local lookups: {0}", localLookupsDelta).AppendLine(); sb.AppendFormat(" Local found: {0}", localLookupsSucceededDelta).AppendLine(); if (localLookupsDelta > 0) sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededDelta) / localLookupsDelta).AppendLine(); sb.AppendFormat(" Full lookups: {0}", fullLookupsDelta).AppendLine(); sb.AppendLine(" Since start:"); sb.AppendFormat(" Local lookups: {0}", localLookupsCurrent).AppendLine(); sb.AppendFormat(" Local found: {0}", localLookupsSucceededCurrent).AppendLine(); if (localLookupsCurrent > 0) sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededCurrent) / localLookupsCurrent).AppendLine(); sb.AppendFormat(" Full lookups: {0}", fullLookupsCurrent).AppendLine(); sb.Append(DirectoryCache.ToString()); return sb.ToString(); } private long RingDistanceToSuccessor() { long distance; List<SiloAddress> successorList = FindSuccessors(MyAddress, 1); if (successorList == null || successorList.Count == 0) { distance = 0; } else { SiloAddress successor = successorList[0]; distance = successor == null ? 0 : CalcRingDistance(MyAddress, successor); } return distance; } private static long CalcRingDistance(SiloAddress silo1, SiloAddress silo2) { const long ringSize = int.MaxValue * 2L; long hash1 = silo1.GetConsistentHashCode(); long hash2 = silo2.GetConsistentHashCode(); if (hash2 > hash1) return hash2 - hash1; if (hash2 < hash1) return ringSize - (hash1 - hash2); return 0; } public string RingStatusToString() { var sb = new StringBuilder(); sb.AppendFormat("Silo address is {0}, silo consistent hash is {1:X}.", MyAddress, MyAddress.GetConsistentHashCode()).AppendLine(); sb.AppendLine("Ring is:"); var membershipRingList = this.directoryMembership.MembershipRingList; foreach (var silo in membershipRingList) sb.AppendFormat(" Silo {0}, consistent hash is {1:X}", silo, silo.GetConsistentHashCode()).AppendLine(); sb.AppendFormat("My predecessors: {0}", FindPredecessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- ")).AppendLine(); sb.AppendFormat("My successors: {0}", FindSuccessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- ")); return sb.ToString(); } internal IRemoteGrainDirectory GetDirectoryReference(SiloAddress silo) { return this.grainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryServiceType, silo); } private bool IsSiloNextInTheRing(SiloAddress siloAddr, int hash, bool excludeMySelf) { return siloAddr.GetConsistentHashCode() <= hash && (!excludeMySelf || !siloAddr.Equals(MyAddress)); } public bool IsSiloInCluster(SiloAddress silo) { return this.directoryMembership.MembershipCache.Contains(silo); } public void CachePlacementDecision(GrainAddress activation) => this.DirectoryCache.AddOrUpdate(activation, 0); public bool TryCachedLookup(GrainId grainId, out GrainAddress address) => (address = GetLocalCacheData(grainId)) is not null; private class DirectoryMembership { public DirectoryMembership(ImmutableList<SiloAddress> membershipRingList, ImmutableHashSet<SiloAddress> membershipCache) { this.MembershipRingList = membershipRingList; this.MembershipCache = membershipCache; } public static DirectoryMembership Default { get; } = new DirectoryMembership(ImmutableList<SiloAddress>.Empty, ImmutableHashSet<SiloAddress>.Empty); public ImmutableList<SiloAddress> MembershipRingList { get; } public ImmutableHashSet<SiloAddress> MembershipCache { get; } } } [Serializable] [GenerateSerializer] public class OrleansGrainDirectoryException : OrleansException { public OrleansGrainDirectoryException() { } public OrleansGrainDirectoryException(string message) : base(message) { } public OrleansGrainDirectoryException(string message, Exception innerException) : base(message, innerException) { } protected OrleansGrainDirectoryException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using DemoGame.DbObjs; using DemoGame.Server.DbObjs; using DemoGame.Server.Properties; using DemoGame.Server.Queries; using log4net; using NetGore; using NetGore.Cryptography; using NetGore.Db; using NetGore.Network; namespace DemoGame.Server { public class UserAccountManager { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); static readonly string _passwordSalt = ServerSettings.Default.PasswordSalt; readonly IDictionary<string, UserAccount> _accounts = new Dictionary<string, UserAccount>(StringComparer.OrdinalIgnoreCase); readonly object _accountsSync = new object(); readonly IDbController _dbController; /// <summary> /// Initializes a new instance of the <see cref="UserAccountManager"/> class. /// </summary> /// <param name="dbController">The <see cref="IDbController"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="dbController" /> is <c>null</c>.</exception> public UserAccountManager(IDbController dbController) { if (dbController == null) throw new ArgumentNullException("dbController"); _dbController = dbController; } /// <summary> /// Gets the <see cref="IDbController"/> to use. /// </summary> public IDbController DbController { get { return _dbController; } } /// <summary> /// Generates a salted hash for a password. /// </summary> /// <param name="originalPassword">The original (raw text) password.</param> /// <returns>The salted and hashed password.</returns> public static string EncodePassword(string originalPassword) { // Apply the salt (if one exists) string saltedPassword; if (!string.IsNullOrEmpty(_passwordSalt)) saltedPassword = _passwordSalt + originalPassword; else saltedPassword = originalPassword; // Hash the salted password return Hasher.GetHashAsBase16String(saltedPassword); } /// <summary> /// Finds the <see cref="IUserAccount"/> for a given user. Can only find the <see cref="IUserAccount"/> instance for /// a user that is logged into this server. /// </summary> /// <param name="userName">The name of the user to find the <see cref="IUserAccount"/> for.</param> /// <returns>The <see cref="IUserAccount"/> for the <paramref name="userName"/>, or null if not found.</returns> public IUserAccount FindUserAccount(string userName) { lock (_accountsSync) { UserAccount ret; if (!_accounts.TryGetValue(userName, out ret)) return null; return ret; } } /// <summary> /// Tries to log in an account. /// </summary> /// <param name="socket">The socket used to communicate with the client.</param> /// <param name="name">The name of the account.</param> /// <param name="password">The account password.</param> /// <param name="userAccount">When this method returns <see cref="AccountLoginResult.Successful"/>, /// contains the <see cref="IUserAccount"/> that was logged in to. Otherwise, this value will be null.</param> /// <returns>If <see cref="AccountLoginResult.Successful"/>, the login was successful. Otherwise, contains /// the reason why the login failed.</returns> public AccountLoginResult Login(IIPSocket socket, string name, string password, out IUserAccount userAccount) { // Try to load the account data var accountTable = DbController.GetQuery<SelectAccountQuery>().TryExecute(name); if (accountTable == null) { userAccount = null; return AccountLoginResult.InvalidName; } // Check the password var encodedPass = EncodePassword(password); if (!StringComparer.OrdinalIgnoreCase.Equals(encodedPass, accountTable.Password)) { userAccount = null; return AccountLoginResult.InvalidPassword; } // Check if the account is already logged in to if (accountTable.CurrentIp.HasValue) { if (ServerSettings.Default.AccountDropExistingConnectionWhenInUse) { // Kick existing user so the new connection can enter the account UserAccount existingAccount; lock (_accountsSync) { if (!_accounts.TryGetValue(name, out existingAccount)) existingAccount = null; } if (existingAccount != null) existingAccount.Dispose(); } else { // Let the existing user stay connected and reject the new connection to the account userAccount = null; return AccountLoginResult.AccountInUse; } } // Try to mark the account as in use if (!DbController.GetQuery<TrySetAccountIPIfNullQuery>().Execute(accountTable.ID, socket.IP)) { userAccount = null; return AccountLoginResult.AccountInUse; } // Try to add the new account to the collection lock (_accountsSync) { // If for some reason an account instance already exists, close it UserAccount existingAccount; if (_accounts.TryGetValue(name, out existingAccount)) { const string errmsg = "UserAccount for `{0}` already existing in _accounts collection somehow."; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, name); Debug.Fail(string.Format(errmsg, name)); userAccount = null; return AccountLoginResult.AccountInUse; } // Create the account instance userAccount = new UserAccount(accountTable, socket, this); // Add _accounts.Add(name, (UserAccount)userAccount); } // Load the characters in this account userAccount.LoadCharacterIDs(); // Record the login IP DbController.GetQuery<InsertAccountIPQuery>().Execute(userAccount.ID, socket.IP); return AccountLoginResult.Successful; } /// <summary> /// Handles when a <see cref="UserAccount"/> is disposed. /// </summary> /// <param name="account">The <see cref="UserAccount"/> that was disposed.</param> void NotifyAccountDisposed(UserAccount account) { lock (_accountsSync) { _accounts.Remove(account.Name); } } /// <summary> /// Tries to add a <see cref="Character"/> to an account. /// </summary> /// <param name="accountName">Name of the account.</param> /// <param name="characterName">Name of the character.</param> /// <param name="errorMsg">If this method returns false, contains the error message.</param> /// <returns>True if the character was successfully added to the account; otherwise false.</returns> public bool TryAddCharacter(string accountName, string characterName, out string errorMsg) { // Try to execute the query var createUserQuery = DbController.GetQuery<CreateUserOnAccountQuery>(); if (!createUserQuery.TryExecute(accountName, characterName, out errorMsg)) return false; errorMsg = string.Empty; return true; } /// <summary> /// Tries to create a new user account. /// </summary> /// <param name="socket">The socket containing the connection trying to create the account. Can be null.</param> /// <param name="name">The account name.</param> /// <param name="password">The account password.</param> /// <param name="email">The account email address.</param> /// <param name="failReason">When this method returns false, contains a <see cref="GameMessage"/> that will be /// used to describe why the account failed to be created.</param> /// <returns>True if the account was successfully created; otherwise false.</returns> public bool TryCreateAccount(IIPSocket socket, string name, string password, string email, out GameMessage failReason) { // Check for valid values if (!GameData.AccountName.IsValid(name)) { failReason = GameMessage.CreateAccountInvalidName; return false; } if (!GameData.AccountPassword.IsValid(password)) { failReason = GameMessage.CreateAccountInvalidPassword; return false; } if (!GameData.AccountEmail.IsValid(email)) { failReason = GameMessage.CreateAccountInvalidEmail; return false; } // Get the IP to use var ip = socket != null ? socket.IP : GameData.DefaultCreateAccountIP; // Check if too many accounts have been created from this IP if (ip != GameData.DefaultCreateAccountIP) { var recentCreatedCount = DbController.GetQuery<CountRecentlyCreatedAccounts>().Execute(ip); if (recentCreatedCount >= ServerSettings.Default.MaxRecentlyCreatedAccounts) { failReason = GameMessage.CreateAccountTooManyCreated; return false; } } // Check if the account exists var existingAccountID = DbController.GetQuery<SelectAccountIDFromNameQuery>().Execute(name); if (existingAccountID.HasValue) { failReason = GameMessage.CreateAccountAlreadyExists; return false; } // Try to execute the query var success = DbController.GetQuery<CreateAccountQuery>().TryExecute(name, password, email, ip); failReason = GameMessage.CreateAccountUnknownError; return success; } /// <summary> /// Tries to get the AccountID for the account with the given name. /// </summary> /// <param name="accountName">The name of the account.</param> /// <param name="accountID">When the method returns true, contains the ID of the account with the given /// <paramref name="accountName"/>.</param> /// <returns>True if the <paramref name="accountID"/> was found; otherwise false.</returns> public bool TryGetAccountID(string accountName, out AccountID accountID) { var value = DbController.GetQuery<SelectAccountIDFromNameQuery>().Execute(accountName); if (!value.HasValue) { accountID = new AccountID(0); return false; } else { accountID = value.Value; return true; } } /// <summary> /// Contains the information for a <see cref="DemoGame.Server.User"/>'s account. /// </summary> class UserAccount : AccountTable, IUserAccount { readonly List<CharacterID> _characterIDs = new List<CharacterID>(); readonly UserAccountManager _parent; readonly IIPSocket _socket; User _user; /// <summary> /// Initializes a new instance of the <see cref="UserAccount"/> class. /// </summary> /// <param name="accountTable">The account table.</param> /// <param name="socket">The socket.</param> /// <param name="parent">The <see cref="UserAccountManager"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="socket" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException"><paramref name="parent" /> is <c>null</c>.</exception> internal UserAccount(IAccountTable accountTable, IIPSocket socket, UserAccountManager parent) : base(accountTable) { if (socket == null) throw new ArgumentNullException("socket"); if (parent == null) throw new ArgumentNullException("parent"); _socket = socket; _parent = parent; } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { return string.Format("{0} [{1}]", Name, ID); } #region IUserAccount Members /// <summary> /// Gets the number of Characters in this UserAccount. /// </summary> public byte CharacterCount { get { return (byte)_characterIDs.Count; } } /// <summary> /// Gets an IEnumerable of the <see cref="CharacterID"/>s for the <see cref="Character"/>s that are in /// this <see cref="IUserAccount"/>. /// </summary> public IEnumerable<CharacterID> CharacterIDs { get { return _characterIDs; } } public IDbController DbController { get { return _parent.DbController; } } /// <summary> /// Gets the <see cref="IIPSocket"/> that is used to communicate with the client connected to this <see cref="IUserAccount"/>. /// </summary> public IIPSocket Socket { get { return _socket; } } /// <summary> /// Gets the <see cref="DemoGame.Server.User"/> currently logged in on this <see cref="IUserAccount"/>. /// </summary> public User User { get { return _user; } } /// <summary> /// Logs out the User from this UserAccount. If the <see cref="User"/> is not null and has not been disposed, /// this method will dispose of the User, too. /// </summary> public void CloseUser() { ThreadAsserts.IsMainThread(); var u = _user; if (u == null) return; _user = null; if (log.IsInfoEnabled) log.InfoFormat("Closed User `{0}` on account `{1}`.", u, this); // Make sure the user was disposed if (!u.IsDisposed) u.Dispose(); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <param name="disconnectMessage">The message to use for when disconnecting the socket. When disposing an active connection, /// this can provide the client a reason why they were disconnected. The default is /// <see cref="GameMessage.DisconnectUserDisposed"/>.</param> /// <param name="p">The arguments for the <paramref name="disconnectMessage"/>.</param> public void Dispose(GameMessage disconnectMessage, params object[] p) { ThreadAsserts.IsMainThread(); try { // Make sure the User is closed CloseUser(); // Break the connection, if connected if (Socket != null) Socket.Disconnect(disconnectMessage, p); // Log the account out in the database DbController.GetQuery<SetAccountCurrentIPNullQuery>().Execute(ID); if (log.IsInfoEnabled) log.InfoFormat("Disposed account `{0}`.", this); } finally { _parent.NotifyAccountDisposed(this); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(GameMessage.DisconnectUserDisposed); } /// <summary> /// Gets the CharacterID for a Character in the UserAccount by the given index. /// </summary> /// <param name="index">The 0-based index of the CharacterID.</param> /// <returns>The CharacterID for the Character at the given <paramref name="index"/>.</returns> public CharacterID GetCharacterID(byte index) { return _characterIDs[index]; } /// <summary> /// Loads the <see cref="CharacterID"/>s for the Characters in this account. /// </summary> public void LoadCharacterIDs() { var ids = DbController.GetQuery<SelectAccountCharacterIDsQuery>().Execute(ID); _characterIDs.Clear(); _characterIDs.AddRange(ids); } /// <summary> /// Sends the <see cref="AccountCharacterInfo"/>s for the <see cref="Character"/>s in this account to the /// client. /// </summary> public void SendAccountCharacterInfos() { var charInfos = new AccountCharacterInfo[CharacterCount]; for (var i = 0; i < charInfos.Length; i++) { var characterID = _characterIDs[i]; var v = DbController.GetQuery<SelectAccountCharacterInfoQuery>().Execute(characterID, (byte)i); if (v != null) { var eqBodies = DbController.GetQuery<SelectCharacterEquippedBodiesQuery>().Execute(characterID); if (eqBodies != null) v.SetEquippedBodies(eqBodies); charInfos[i] = v; } } using (var pw = ServerPacket.SendAccountCharacters(charInfos)) { Socket.Send(pw, ServerMessageType.System); } } /// <summary> /// Sets the permission level for this account. /// </summary> /// <param name="newPermissions">The new <see cref="UserPermissions"/> level.</param> public void SetPermissions(UserPermissions newPermissions) { if (newPermissions == Permissions) return; // Set the new value Permissions = newPermissions; // Update the database DbController.GetQuery<UpdateAccountPermissionsQuery>().Execute(ID, Permissions); } /// <summary> /// Sets the friends list for this account. /// </summary> /// <param name="friends">The friends list.</param> public void SetFriends(string friends) { if (String.IsNullOrEmpty(friends)) return; // Set the new value Friends = friends; // Update the database DbController.GetQuery<UpdateAccountFriendsQuery>().Execute(ID, Friends); } /// <summary> /// Loads and sets the User being used by this account. /// </summary> /// <param name="world">The World that the User will be part of.</param> /// <param name="characterID">The CharacterID of the user to use.</param> public void SetUser(World world, CharacterID characterID) { ThreadAsserts.IsMainThread(); // Make sure the user is not already set if (User != null) { const string errmsg = "Cannot use SetUser when the User is not null."; Debug.Fail(errmsg); if (log.IsErrorEnabled) log.Error(errmsg); return; } // Make sure the CharacterID is an ID of a character belonging to this UserAccount if (!_characterIDs.Contains(characterID)) { const string errmsg = "Cannot use CharacterID `{0}` - that character does not belong to this UserAccount."; Debug.Fail(string.Format(errmsg, characterID)); if (log.IsErrorEnabled) log.ErrorFormat(errmsg, characterID); return; } // Load the User try { _user = new User(this, world, characterID); } catch (Exception ex) { const string errmsg = "Failed to create user with ID `{0}`. Exception: {1}"; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, characterID, ex); Debug.Fail(string.Format(errmsg, characterID, ex)); Dispose(); return; } if (log.IsInfoEnabled) log.InfoFormat("Set User `{0}` on account `{1}`.", _user, this); } /// <summary> /// Tries to get the CharacterID for a Character in the UserAccount by the given index. /// </summary> /// <param name="index">The 0-based index of the CharacterID.</param> /// <param name="value">The CharacterID for the Character at the given <paramref name="index"/>.</param> /// <returns>True if the <paramref name="value"/> was successfully acquired; otherwise false.</returns> public bool TryGetCharacterID(byte index, out CharacterID value) { if (index < 0 || index >= _characterIDs.Count) { value = new CharacterID(0); return false; } value = _characterIDs[index]; return true; } #endregion } } }
/// Copyright (C) 2012-2014 Soomla 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 UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.IO; using Soomla; using Soomla.Profile; using Soomla.Example; /// <summary> /// This class contains functions that initialize the game and that display the different screens of the game. /// </summary> public class ExampleWindow : MonoBehaviour { private static ExampleWindow instance = null; public string fontSuffix = ""; private static bool isVisible = false; private bool isInit = false; private Provider targetProvider = Provider.GOOGLE; private Reward exampleReward = new BadgeReward("example_reward", "Example Social Reward"); /// <summary> /// Initializes the game state before the game starts. /// </summary> void Awake(){ if(instance == null){ //making sure we only initialize one instance. instance = this; GameObject.DontDestroyOnLoad(this.gameObject); } else { //Destroying unused instances. GameObject.Destroy(this); } //FONT //using max to be certain we have the longest side of the screen, even if we are in portrait. if(Mathf.Max(Screen.width, Screen.height) > 640){ fontSuffix = "_2X"; //a nice suffix to show the fonts are twice as big as the original } } private Texture2D tBackground; private Texture2D tShed; private Texture2D tBGBar; private Texture2D tShareDisable; private Texture2D tShare; private Texture2D tSharePress; private Texture2D tShareStoryDisable; private Texture2D tShareStory; private Texture2D tShareStoryPress; private Texture2D tUploadDisable; private Texture2D tUpload; private Texture2D tUploadPress; private Texture2D tConnect; private Texture2D tConnectPress; private Texture2D tLogout; private Texture2D tLogoutPress; private Font fgoodDog; // private bool bScreenshot = false; /// <summary> /// Starts this instance. /// Use this for initialization. /// </summary> void Start () { fgoodDog = (Font)Resources.Load("Fonts/GoodDog" + fontSuffix); tBackground = (Texture2D)Resources.Load("Profile/BG"); tShed = (Texture2D)Resources.Load("Profile/Headline"); tBGBar = (Texture2D)Resources.Load("Profile/BG-Bar"); tShareDisable = (Texture2D)Resources.Load("Profile/BTN-Share-Disable"); tShare = (Texture2D)Resources.Load("Profile/BTN-Share-Normal"); tSharePress = (Texture2D)Resources.Load("Profile/BTN-Share-Press"); tShareStoryDisable = (Texture2D)Resources.Load("Profile/BTN-ShareStory-Disable"); tShareStory = (Texture2D)Resources.Load("Profile/BTN-ShareStory-Normal"); tShareStoryPress = (Texture2D)Resources.Load("Profile/BTN-ShareStory-Press"); tUploadDisable = (Texture2D)Resources.Load("Profile/BTN-Upload-Disable"); tUpload = (Texture2D)Resources.Load("Profile/BTN-Upload-Normal"); tUploadPress = (Texture2D)Resources.Load("Profile/BTN-Upload-Press"); tConnect = (Texture2D)Resources.Load("Profile/BTN-Connect"); tConnectPress = (Texture2D)Resources.Load("Profile/BTN-Connect-Press"); tLogout = (Texture2D)Resources.Load("Profile/BTN-LogOut"); tLogoutPress = (Texture2D)Resources.Load("Profile/BTN-LogOut-Press"); // examples of catching fired events ProfileEvents.OnSoomlaProfileInitialized += () => { Soomla.SoomlaUtils.LogDebug("ExampleWindow", "SoomlaProfile Initialized !"); isInit = true; }; ProfileEvents.OnUserRatingEvent += () => { Soomla.SoomlaUtils.LogDebug("ExampleWindow", "User opened rating page"); }; ProfileEvents.OnGetScoresFinished += (GetScoresFinishedEvent ev) => { foreach (Score score in ev.Scores.PageData) { Debug.Log(score.Player.ProfileId); } }; ProfileEvents.OnGetLeaderboardsFinished += (GetLeaderboardsFinishedEvent ev) => { Debug.Log("leaderboard 1: " + ev.Leaderboards.PageData[0].ID); SoomlaProfile.GetScores(targetProvider, ev.Leaderboards.PageData[0]); }; ProfileEvents.OnGetLeaderboardsFailed += (GetLeaderboardsFailedEvent ev) => { SoomlaUtils.LogDebug("ExampleWindow", "leaderboard error: " + ev.ErrorDescription); }; ProfileEvents.OnLoginFinished += (UserProfile UserProfile, bool autoLogin, string payload) => { Debug.Log("logged in"); //SoomlaProfile.ShowLeaderboards(targetProvider); SoomlaProfile.GetLeaderboards(targetProvider); }; ProfileEvents.OnGetContactsFinished += (Provider provider, SocialPageData<UserProfile> contactsData, string payload) => { Soomla.SoomlaUtils.LogDebug("ExampleWindow", "get contacts for: " + contactsData.PageData.Count + " page: " + contactsData.PageNumber + " More? " + contactsData.HasMore); foreach (var profile in contactsData.PageData) { Soomla.SoomlaUtils.LogDebug("ExampleWindow", "Contact: " + profile.toJSONObject().print()); } if (contactsData.HasMore) { SoomlaProfile.GetContacts(targetProvider); } }; SoomlaProfile.Initialize(); // SoomlaProfile.OpenAppRatingPage(); #if UNITY_IPHONE Handheld.SetActivityIndicatorStyle(UnityEngine.iOS.ActivityIndicatorStyle.Gray); #elif UNITY_ANDROID Handheld.SetActivityIndicatorStyle(AndroidActivityIndicatorStyle.Small); #endif } /// <summary> /// Sets the window to open, and sets the GUI state to welcome. /// </summary> public static void OpenWindow(){ isVisible = true; } /// <summary> /// Sets the window to closed. /// </summary> public static void CloseWindow(){ isVisible = false; } /// <summary> /// Implements the game behavior of MuffinRush. /// Overrides the superclass function in order to provide functionality for our game. /// </summary> void Update () { if (Application.platform == RuntimePlatform.Android) { if (Input.GetKeyUp(KeyCode.Escape)) { //quit application on back button Application.Quit(); return; } } } /// <summary> /// Calls the relevant function to display the correct screen of the game. /// </summary> void OnGUI(){ if(!isVisible){ return; } GUI.skin.horizontalScrollbar = GUIStyle.none; GUI.skin.verticalScrollbar = GUIStyle.none; welcomeScreen(); } /// <summary> /// Displays the welcome screen of the game. /// </summary> void welcomeScreen() { Color backupColor = GUI.color; float vertGap = 80f; //drawing background, just using a white pixel here GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),tBackground); GUI.DrawTexture(new Rect(0,0,Screen.width,timesH(240f)), tShed, ScaleMode.StretchToFill, true); float rowsTop = 300.0f; float rowsHeight = 120.0f; GUI.DrawTexture(new Rect(timesW(65.0f),timesH(rowsTop+10f),timesW(516.0f),timesH(102.0f)), tBGBar, ScaleMode.StretchToFill, true); if (SoomlaProfile.IsLoggedIn(targetProvider)) { GUI.skin.button.normal.background = tShare; GUI.skin.button.hover.background = tShare; GUI.skin.button.active.background = tSharePress; if(GUI.Button(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), "")){ SoomlaProfile.UpdateStatus(targetProvider, "I LOVE SOOMLA ! http://www.soom.la", null, exampleReward); } } else { GUI.DrawTexture(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), tShareDisable, ScaleMode.StretchToFill, true); } GUI.color = Color.black; GUI.skin.label.font = fgoodDog; GUI.skin.label.fontSize = 30; GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUI.Label(new Rect(timesW(270.0f),timesH(rowsTop),timesW(516.0f-212.0f),timesH(120.0f)),"I Love SOOMLA!"); GUI.color = backupColor; rowsTop += vertGap + rowsHeight; GUI.DrawTexture(new Rect(timesW(65.0f),timesH(rowsTop+10f),timesW(516.0f),timesH(102.0f)), tBGBar, ScaleMode.StretchToFill, true); if (SoomlaProfile.IsLoggedIn(targetProvider)) { GUI.skin.button.normal.background = tShareStory; GUI.skin.button.hover.background = tShareStory; GUI.skin.button.active.background = tShareStoryPress; if(GUI.Button(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), "")){ SoomlaProfile.UpdateStory(targetProvider, "The story of SOOMBOT (Profile Test App)", "The story of SOOMBOT (Profile Test App)", "SOOMBOT Story", "DESCRIPTION", "http://about.soom.la/soombots", "http://about.soom.la/wp-content/uploads/2014/05/330x268-spockbot.png", null, exampleReward); } } else { GUI.DrawTexture(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), tShareStoryDisable, ScaleMode.StretchToFill, true); } GUI.color = Color.black; GUI.skin.label.font = fgoodDog; GUI.skin.label.fontSize = 25; GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUI.Label(new Rect(timesW(270.0f),timesH(rowsTop),timesW(516.0f-212.0f),timesH(120.0f)),"Full story of The SOOMBOT!"); GUI.color = backupColor; rowsTop += vertGap + rowsHeight; GUI.DrawTexture(new Rect(timesW(65.0f),timesH(rowsTop+10f),timesW(516.0f),timesH(102.0f)), tBGBar, ScaleMode.StretchToFill, true); if (SoomlaProfile.IsLoggedIn(targetProvider)) { GUI.skin.button.normal.background = tUpload; GUI.skin.button.hover.background = tUpload; GUI.skin.button.active.background = tUploadPress; if(GUI.Button(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), "")){ // string fileName = "soom.jpg"; // string path = ""; // // #if UNITY_IOS // path = Application.dataPath + "/Raw/" + fileName; // #elif UNITY_ANDROID // path = "jar:file://" + Application.dataPath + "!/assets/" + fileName; // #endif // // byte[] bytes = File.ReadAllBytes(path); // SoomlaProfile.UploadImage(targetProvider, "Awesome Test App of SOOMLA Profile!", fileName, bytes, 10, null, exampleReward); SoomlaProfile.UploadCurrentScreenShot(this, targetProvider, "Awesome Test App of SOOMLA Profile!", "This a screenshot of the current state of SOOMLA's test app on my computer.", null); } } else { GUI.DrawTexture(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), tUploadDisable, ScaleMode.StretchToFill, true); } GUI.color = Color.black; GUI.skin.label.font = fgoodDog; GUI.skin.label.fontSize = 28; GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUI.Label(new Rect(timesW(270.0f),timesH(rowsTop),timesW(516.0f-212.0f),timesH(120.0f)),"Current Screenshot"); GUI.color = backupColor; if (SoomlaProfile.IsLoggedIn(targetProvider)) { GUI.skin.button.normal.background = tLogout; GUI.skin.button.hover.background = tLogout; GUI.skin.button.active.background = tLogoutPress; if(GUI.Button(new Rect(timesW(20.0f),timesH(950f),timesW(598.0f),timesH(141.0f)), "")){ SoomlaProfile.Logout(targetProvider); } } else if (isInit) { GUI.skin.button.normal.background = tConnect; GUI.skin.button.hover.background = tConnect; GUI.skin.button.active.background = tConnectPress; if(GUI.Button(new Rect(timesW(20.0f),timesH(950f),timesW(598.0f),timesH(141.0f)), "")){ //SoomlaProfile.GetLeaderboards(Provider.GAME_CENTER); SoomlaProfile.Login(targetProvider, null, exampleReward); } } } private static string ScreenShotName(int width, int height) { return string.Format("{0}/screen_{1}x{2}_{3}.png", Application.persistentDataPath, width, height, System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss")); } private float timesW(float f) { return (float)(f/640.0)*Screen.width; } private float timesH(float f) { return (float)(f/1136.0)*Screen.height; } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Logging.Logging File: LoggingHelper.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Logging { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using Ecng.Common; using Ecng.Configuration; using StockSharp.Localization; /// <summary> /// Extension class for <see cref="ILogSource"/>. /// </summary> public static class LoggingHelper { /// <summary> /// To record a message to the log. /// </summary> /// <param name="receiver">Logs receiver.</param> /// <param name="getMessage">The function returns the text for <see cref="LogMessage.Message"/>.</param> public static void AddInfoLog(this ILogReceiver receiver, Func<string> getMessage) { receiver.AddLog(LogLevels.Info, getMessage); } /// <summary> /// To record a warning to the log. /// </summary> /// <param name="receiver">Logs receiver.</param> /// <param name="getMessage">The function returns the text for <see cref="LogMessage.Message"/>.</param> public static void AddWarningLog(this ILogReceiver receiver, Func<string> getMessage) { receiver.AddLog(LogLevels.Warning, getMessage); } /// <summary> /// To record an error to the log. /// </summary> /// <param name="receiver">Logs receiver.</param> /// <param name="getMessage">The function returns the text for <see cref="LogMessage.Message"/>.</param> public static void AddErrorLog(this ILogReceiver receiver, Func<string> getMessage) { receiver.AddLog(LogLevels.Error, getMessage); } /// <summary> /// To record a message to the log. /// </summary> /// <param name="receiver">Logs receiver.</param> /// <param name="level">The level of the log message.</param> /// <param name="getMessage">The function returns the text for <see cref="LogMessage.Message"/>.</param> public static void AddLog(this ILogReceiver receiver, LogLevels level, Func<string> getMessage) { if (receiver == null) throw new ArgumentNullException(nameof(receiver)); receiver.AddLog(new LogMessage(receiver, receiver.CurrentTime, level, getMessage)); } /// <summary> /// To record a message to the log. /// </summary> /// <param name="receiver">Logs receiver.</param> /// <param name="message">Text message.</param> /// <param name="args">Text message settings. Used if a message is the format string. For details, see <see cref="string.Format(string,object[])"/>.</param> public static void AddInfoLog(this ILogReceiver receiver, string message, params object[] args) { receiver.AddMessage(LogLevels.Info, message, args); } /// <summary> /// To record a verbose message to the log. /// </summary> /// <param name="receiver">Logs receiver.</param> /// <param name="message">Text message.</param> /// <param name="args">Text message settings. Used if a message is the format string. For details, see <see cref="string.Format(string,object[])"/>.</param> public static void AddVerboseLog(this ILogReceiver receiver, string message, params object[] args) { receiver.AddMessage(LogLevels.Verbose, message, args); } /// <summary> /// To record a debug message to the log. /// </summary> /// <param name="receiver">Logs receiver.</param> /// <param name="message">Text message.</param> /// <param name="args">Text message settings. Used if a message is the format string. For details, see <see cref="string.Format(string,object[])"/>.</param> public static void AddDebugLog(this ILogReceiver receiver, string message, params object[] args) { receiver.AddMessage(LogLevels.Debug, message, args); } /// <summary> /// To record a warning to the log. /// </summary> /// <param name="receiver">Logs receiver.</param> /// <param name="message">Text message.</param> /// <param name="args">Text message settings. Used if a message is the format string. For details, see <see cref="string.Format(string,object[])"/>.</param> public static void AddWarningLog(this ILogReceiver receiver, string message, params object[] args) { receiver.AddMessage(LogLevels.Warning, message, args); } /// <summary> /// To record an error to the log. /// </summary> /// <param name="receiver">Logs receiver.</param> /// <param name="exception">Error details.</param> public static void AddErrorLog(this ILogReceiver receiver, Exception exception) { receiver.AddErrorLog(exception, null); } /// <summary> /// To record an error to the log. /// </summary> /// <param name="receiver">Logs receiver.</param> /// <param name="exception">Error details.</param> /// <param name="format">A format string.</param> public static void AddErrorLog(this ILogReceiver receiver, Exception exception, string format) { if (receiver == null) throw new ArgumentNullException(nameof(receiver)); if (exception == null) throw new ArgumentNullException(nameof(exception)); receiver.AddLog(new LogMessage(receiver, receiver.CurrentTime, LogLevels.Error, () => { var msg = exception.ToString(); if (exception is ReflectionTypeLoadException refExc) { msg += Environment.NewLine + refExc .LoaderExceptions .Select(e => e.ToString()) .Join(Environment.NewLine); } if (format != null) msg = format.Put(msg); return msg; })); } /// <summary> /// To record an error to the log. /// </summary> /// <param name="message">Text message.</param> /// <param name="args">Text message settings. Used if a message is the format string. For details, see <see cref="string.Format(string,object[])"/>.</param> public static void AddErrorLog(this string message, params object[] args) { ConfigManager.TryGetService<LogManager>()?.Application.AddMessage(LogLevels.Error, message, args); } /// <summary> /// To record an error to the log. /// </summary> /// <param name="receiver">Logs receiver.</param> /// <param name="message">Text message.</param> /// <param name="args">Text message settings. Used if a message is the format string. For details, see <see cref="string.Format(string,object[])"/>.</param> public static void AddErrorLog(this ILogReceiver receiver, string message, params object[] args) { receiver.AddMessage(LogLevels.Error, message, args); } private static void AddMessage(this ILogReceiver receiver, LogLevels level, string message, params object[] args) { if (receiver == null) throw new ArgumentNullException(nameof(receiver)); if (level < receiver.LogLevel) return; receiver.AddLog(new LogMessage(receiver, receiver.CurrentTime, level, message, args)); } /// <summary> /// To record an error to the <see cref="LogManager.Application"/>. /// </summary> /// <param name="error">Error.</param> /// <param name="format">A format string.</param> public static void LogError(this Exception error, string format = null) { if (error == null) throw new ArgumentNullException(nameof(error)); LogManager.Instance?.Application.AddErrorLog(error, format); } /// <summary> /// Get <see cref="ILogSource.LogLevel"/> for the source. If the value is equal to <see cref="LogLevels.Inherit"/>, then parental source level is taken. /// </summary> /// <param name="source">The log source.</param> /// <returns>Logging level.</returns> public static LogLevels GetLogLevel(this ILogSource source) { if (source == null) throw new ArgumentNullException(nameof(source)); do { var level = source.LogLevel; if (level != LogLevels.Inherit) return level; source = source.Parent; } while (source != null); return LogLevels.Inherit; } /// <summary> /// Wrap the specified action in try/catch clause with logging. /// </summary> /// <param name="action">The action.</param> public static void DoWithLog(this Action action) { if (action == null) throw new ArgumentNullException(nameof(action)); try { action(); } catch (Exception ex) { ex.LogError(); } } /// <summary> /// Wrap the specified action in try/catch clause with logging. /// </summary> /// <typeparam name="T">The type of returned result.</typeparam> /// <param name="action">The action.</param> /// <returns>The resulting value.</returns> public static T DoWithLog<T>(this Func<T> action) { if (action == null) throw new ArgumentNullException(nameof(action)); try { return action(); } catch (Exception ex) { ex.LogError(); return default; } } /// <summary> /// Wrap the specified action in try/catch clause with logging. /// </summary> /// <typeparam name="T">The type of returned result.</typeparam> /// <param name="action">The action.</param> /// <returns>The resulting value.</returns> public static void DoWithLog<T>(Func<IDictionary<T, Exception>> action) { if (action == null) throw new ArgumentNullException(nameof(action)); try { var dict = action(); foreach (var pair in dict) { new InvalidOperationException(pair.Key.ToString(), pair.Value).LogError(LocalizedStrings.CorruptedFile); } } catch (Exception ex) { ex.LogError(); } } /// <summary> /// Wrap the specified action in try/catch clause with logging. /// </summary> /// <typeparam name="T1">The type of source values.</typeparam> /// <typeparam name="T2">The type of returned result.</typeparam> /// <param name="from">Source values</param> /// <param name="func">Converter.</param> /// <returns>Result.</returns> public static T2[] SafeAdd<T1, T2>(this IEnumerable from, Func<T1, T2> func) { if (from == null) throw new ArgumentNullException(nameof(from)); var list = new List<T2>(); foreach (T1 item in from) { try { list.Add(func(item)); } catch (Exception e) { e.LogError(); } } return list.ToArray(); } /// <summary> /// The filter that only accepts messages of <see cref="LogLevels.Warning"/> type. /// </summary> public static readonly Func<LogMessage, bool> OnlyWarning = message => message.Level == LogLevels.Warning; /// <summary> /// The filter that only accepts messages of <see cref="LogLevels.Error"/> type. /// </summary> public static readonly Func<LogMessage, bool> OnlyError = message => message.Level == LogLevels.Error; /// <summary> /// Filter messages. /// </summary> /// <param name="messages">Incoming messages.</param> /// <param name="filters">Messages filters that specify which messages should be handled.</param> /// <returns>Filtered collection.</returns> public static IEnumerable<LogMessage> Filter(this IEnumerable<LogMessage> messages, ICollection<Func<LogMessage, bool>> filters) { if (filters.Count > 0) messages = messages.Where(m => filters.Any(f => f(m))); return messages; } } }
// 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 Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Protocols.TestTools; using Microsoft.Protocols.TestTools.StackSdk; using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpbcgr; using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpedyc; using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpegfx; using Microsoft.Protocols.TestSuites.Rdpbcgr; using Microsoft.Protocols.TestSuites.Rdp; namespace Microsoft.Protocols.TestSuites.Rdpegfx { public partial class RdpegfxTestSuite : RdpTestClassBase { [TestMethod] [Priority(0)] [TestCategory("BVT")] [TestCategory("Positive")] [TestCategory("RDP8.0")] [TestCategory("RDPEGFX")] [Description("This test case is used to test intra-SurfacetoSurface copy command.")] public void RDPEGFX_SurfaceToSurface_PositiveTest_IntraSurfaceCopy() { uint fid; // Init for capability exchange RDPEGFX_CapabilityExchange(); // Create & output source surface, then fill it with green color RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id); RDPGFX_RECT16 fillSurfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); RDPGFX_RECT16[] fillRects = { RdpegfxTestUtility.copySrcRect }; // Relative to surface fid = this.rdpegfxAdapter.SolidFillSurface(surf, RdpegfxTestUtility.fillColorGreen, fillRects); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled with solid color in frame: {0}", fid); this.rdpegfxAdapter.ExpectFrameAck(fid); // Fill a rectangle with red color and copy it to another position of the surface RDPGFX_POINT16[] destPts = {RdpegfxTestUtility.imgPos2}; fid = this.rdpegfxAdapter.IntraSurfaceCopy(surf, RdpegfxTestUtility.copySrcRect, destPts); this.rdpegfxAdapter.ExpectFrameAck(fid); this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true."); this.VerifySUTDisplay(false, surfRect); // Delete the surface this.rdpegfxAdapter.DeleteSurface(surf.Id); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf.Id); } [TestMethod] [Priority(0)] [TestCategory("BVT")] [TestCategory("Positive")] [TestCategory("RDP8.0")] [TestCategory("RDPEGFX")] [Description("This test case is used to test inter-SurfacetoSurface copy command.")] public void RDPEGFX_SurfaceToSurface_PositiveTest_InterSurfaceCopy() { uint fid; // Init for capability exchange RDPEGFX_CapabilityExchange(); // Create & output source surface, then fill it with green color RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id); RDPGFX_RECT16 fillSurfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); RDPGFX_RECT16[] fillRects = { fillSurfRect }; // Relative to surface fid = this.rdpegfxAdapter.SolidFillSurface(surf, RdpegfxTestUtility.fillColorGreen, fillRects); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled with solid color in frame: {0}", fid); this.rdpegfxAdapter.ExpectFrameAck(fid); // Create & output destination surface, then fill it with blue color RDPGFX_RECT16 surfRect2 = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos2, RdpegfxTestUtility.surfWidth2, RdpegfxTestUtility.surfHeight2); Surface surf2 = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect2, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf2.Id); RDPGFX_RECT16 fillSurfRect2 = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.surfWidth2, RdpegfxTestUtility.surfHeight2); RDPGFX_RECT16[] fillRects2 = { fillSurfRect2 }; fid = this.rdpegfxAdapter.SolidFillSurface(surf2, RdpegfxTestUtility.fillColorBlue, fillRects2); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled with solid color in frame: {0}", fid); this.rdpegfxAdapter.ExpectFrameAck(fid); RDPGFX_POINT16[] destPts = { RdpegfxTestUtility.imgPos2 }; // Relative to destination surface fid = this.rdpegfxAdapter.InterSurfaceCopy(surf, RdpegfxTestUtility.copySrcRect, RdpegfxTestUtility.fillColorRed, surf2, destPts); this.rdpegfxAdapter.ExpectFrameAck(fid); this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true."); this.VerifySUTDisplay(false, new RDPGFX_RECT16[] { surfRect, surfRect2 }); // Delete the surfaces this.rdpegfxAdapter.DeleteSurface(surf.Id); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf.Id); this.rdpegfxAdapter.DeleteSurface(surf2.Id); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf2.Id); } [TestMethod] [Priority(1)] [TestCategory("Non-BVT")] [TestCategory("Positive")] [TestCategory("RDP8.0")] [TestCategory("RDPEGFX")] [Description("This test case is used to verify whether RDP client can process correctly when receive a RDPGFX_SURFACE_TO_SURFACE_PDU message with source RECT whose specific borders are overlapped with surface.")] public void RDPEGFX_SurfaceToSurface_PositiveTest_SrcRectBorderOverlapSurface() { uint fid; // Init for capability exchange RDPEGFX_CapabilityExchange(); // Create & output source surface, then fill it with green color RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id); RDPGFX_RECT16 fillSurfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); RDPGFX_RECT16[] fillRects = { fillSurfRect }; // Relative to surface fid = this.rdpegfxAdapter.SolidFillSurface(surf, RdpegfxTestUtility.fillColorGreen, fillRects); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled with solid color in frame: {0}", fid); this.rdpegfxAdapter.ExpectFrameAck(fid); // Create & output destination surface, then fill it with blue color RDPGFX_RECT16 surfRect2 = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos2, RdpegfxTestUtility.surfWidth2, RdpegfxTestUtility.surfHeight2); Surface surf2 = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect2, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf2, "Surface {0} is created", surf2.Id); RDPGFX_RECT16 fillSurfRect2 = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.surfWidth2, RdpegfxTestUtility.surfHeight2); RDPGFX_RECT16[] fillRects2 = { fillSurfRect2 }; fid = this.rdpegfxAdapter.SolidFillSurface(surf2, RdpegfxTestUtility.fillColorBlue, fillRects2); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled with solid color in frame: {0}", fid); this.rdpegfxAdapter.ExpectFrameAck(fid); // Generate Source Rect to overlap its border with surface RDPGFX_RECT16 srcRect = new RDPGFX_RECT16(); srcRect.left = (ushort)(RdpegfxTestUtility.surfWidth - RdpegfxTestUtility.smallWidth); srcRect.top = (ushort)(RdpegfxTestUtility.surfHeight - RdpegfxTestUtility.smallHeight); srcRect.right = RdpegfxTestUtility.surfWidth; srcRect.bottom = RdpegfxTestUtility.surfHeight; RDPGFX_POINT16[] destPts = { RdpegfxTestUtility.imgPos2 }; // Relative to destination surface fid = this.rdpegfxAdapter.InterSurfaceCopy(surf, srcRect, RdpegfxTestUtility.fillColorRed, surf2, destPts); this.TestSite.Log.Add(LogEntryKind.Debug, "Send RDPGFX_SURFACE_TO_SURFACE_PDU message in frame {0}, specific borders of source rect are overlapped with surface.", fid); this.rdpegfxAdapter.ExpectFrameAck(fid); this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true."); this.VerifySUTDisplay(false, new RDPGFX_RECT16[] { surfRect, surfRect2 }); // Delete the surfaces this.rdpegfxAdapter.DeleteSurface(surf.Id); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf.Id); this.rdpegfxAdapter.DeleteSurface(surf2.Id); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf2.Id); } [TestMethod] [Priority(1)] [TestCategory("Non-BVT")] [TestCategory("Positive")] [TestCategory("RDP8.0")] [TestCategory("RDPEGFX")] [Description("This test case is used to verify whether RDP client can process correctly when receive a RDPGFX_SURFACE_TO_SURFACE_PDU message with destRects whose specific borders are overlapped with surface.")] public void RDPEGFX_SurfaceToSurface_PositiveTest_DestRectsBorderOverlapSurface() { uint fid; // Init for capability exchange RDPEGFX_CapabilityExchange(); // Create & output source surface, then fill it with green color RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id); RDPGFX_RECT16 fillSurfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); RDPGFX_RECT16[] fillRects = { fillSurfRect }; // Relative to surface fid = this.rdpegfxAdapter.SolidFillSurface(surf, RdpegfxTestUtility.fillColorGreen, fillRects); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled with solid color in frame: {0}", fid); this.rdpegfxAdapter.ExpectFrameAck(fid); // Create & output destination surface, then fill it with blue color RDPGFX_RECT16 surfRect2 = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos2, RdpegfxTestUtility.surfWidth2, RdpegfxTestUtility.surfHeight2); Surface surf2 = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect2, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf2.Id); RDPGFX_RECT16 fillSurfRect2 = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.surfWidth2, RdpegfxTestUtility.surfHeight2); RDPGFX_RECT16[] fillRects2 = { fillSurfRect2 }; fid = this.rdpegfxAdapter.SolidFillSurface(surf2, RdpegfxTestUtility.fillColorBlue, fillRects2); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled with solid color in frame: {0}", fid); this.rdpegfxAdapter.ExpectFrameAck(fid); // Generate destPts array List<RDPGFX_POINT16> destPtsList = new List<RDPGFX_POINT16>(); // Top-right corner int x = RdpegfxTestUtility.surfWidth2 -RdpegfxTestUtility.copySrcRect.Width; int y = 0; destPtsList.Add(new RDPGFX_POINT16((ushort)x, (ushort)y)); // Bottom-right corner x = RdpegfxTestUtility.surfWidth2 - RdpegfxTestUtility.copySrcRect.Width; y = RdpegfxTestUtility.surfHeight2 - RdpegfxTestUtility.copySrcRect.Height; destPtsList.Add(new RDPGFX_POINT16((ushort)x, (ushort)y)); // Bottom-left corner x = 0; y = RdpegfxTestUtility.surfHeight2 - RdpegfxTestUtility.copySrcRect.Height; destPtsList.Add(new RDPGFX_POINT16((ushort)x, (ushort)y)); fid = this.rdpegfxAdapter.InterSurfaceCopy(surf, RdpegfxTestUtility.copySrcRect, RdpegfxTestUtility.fillColorRed, surf2, destPtsList.ToArray()); this.TestSite.Log.Add(LogEntryKind.Debug, "Send RDPGFX_SURFACE_TO_SURFACE_PDU message in frame {0}, specific borders of dest rects are overlapped with surface.", fid); this.rdpegfxAdapter.ExpectFrameAck(fid); this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true."); this.VerifySUTDisplay(false, new RDPGFX_RECT16[] { surfRect, surfRect2 }); // Delete the surfaces this.rdpegfxAdapter.DeleteSurface(surf.Id); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf.Id); this.rdpegfxAdapter.DeleteSurface(surf2.Id); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf2.Id); } [TestMethod] [Priority(1)] [TestCategory("Non-BVT")] [TestCategory("Positive")] [TestCategory("RDP8.0")] [TestCategory("RDPEGFX")] [Description("This test case is used to verify whether RDP client can process correctly when receive a RDPGFX_SURFACE_TO_SURFACE_PDU message with destRects partially overlapped with each other.")] public void RDPEGFX_SurfaceToSurface_PositiveTest_DestRectsOverlapped() { uint fid; // Init for capability exchange RDPEGFX_CapabilityExchange(); // Create & output source surface, then fill it with green color RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id); RDPGFX_RECT16 fillSurfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); RDPGFX_RECT16[] fillRects = { fillSurfRect }; // Relative to surface fid = this.rdpegfxAdapter.SolidFillSurface(surf, RdpegfxTestUtility.fillColorGreen, fillRects); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled with solid color in frame: {0}", fid); this.rdpegfxAdapter.ExpectFrameAck(fid); // Create & output destination surface, then fill it with blue color RDPGFX_RECT16 surfRect2 = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos2, RdpegfxTestUtility.surfWidth2, RdpegfxTestUtility.surfHeight2); Surface surf2 = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect2, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf2.Id); RDPGFX_RECT16 fillSurfRect2 = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.surfWidth2, RdpegfxTestUtility.surfHeight2); RDPGFX_RECT16[] fillRects2 = { fillSurfRect2 }; fid = this.rdpegfxAdapter.SolidFillSurface(surf2, RdpegfxTestUtility.fillColorBlue, fillRects2); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled with solid color in frame {0}, dest rects are overlapped each other", fid); this.rdpegfxAdapter.ExpectFrameAck(fid); // Generate destPts array List<RDPGFX_POINT16> destPtsList = new List<RDPGFX_POINT16>(); // First point int x = 0; int y = 0; destPtsList.Add(new RDPGFX_POINT16((ushort)x, (ushort)y)); // Second Point, the rect ovelap partial of the first one x = RdpegfxTestUtility.copySrcRect.Width / 2; y = RdpegfxTestUtility.copySrcRect.Height / 2; destPtsList.Add(new RDPGFX_POINT16((ushort)x, (ushort)y)); fid = this.rdpegfxAdapter.InterSurfaceCopy(surf, RdpegfxTestUtility.copySrcRect, RdpegfxTestUtility.fillColorRed, surf2, destPtsList.ToArray()); this.TestSite.Log.Add(LogEntryKind.Debug, "Send RDPGFX_SURFACE_TO_SURFACE_PDU message in frame: {0}", fid); this.rdpegfxAdapter.ExpectFrameAck(fid); this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true."); this.VerifySUTDisplay(false, new RDPGFX_RECT16[] { surfRect, surfRect2 }); // Delete the surfaces this.rdpegfxAdapter.DeleteSurface(surf.Id); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf.Id); this.rdpegfxAdapter.DeleteSurface(surf2.Id); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf2.Id); } [TestMethod] [Priority(1)] [TestCategory("Non-BVT")] [TestCategory("Positive")] [TestCategory("RDP8.0")] [TestCategory("RDPEGFX")] [Description("This test case is used to verify whether RDP client can process correctly when receive a RDPGFX_SURFACE_TO_SURFACE_PDU message whose dest rect is partially overlapped with src rect.")] public void RDPEGFX_SurfaceToSurface_PositiveTest_DestRectOverlapSourceRect() { uint fid; // Init for capability exchange RDPEGFX_CapabilityExchange(); // Create & output source surface, then fill it with green color RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id); RDPGFX_RECT16 fillSurfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.smallWidth, RdpegfxTestUtility.smallHeight); RDPGFX_RECT16[] fillRects = { fillSurfRect }; // Relative to surface fid = this.rdpegfxAdapter.SolidFillSurface(surf, RdpegfxTestUtility.fillColorGreen, fillRects); this.TestSite.Log.Add(LogEntryKind.Debug, "Solid fill first area of surface by Green in frame: {0}", fid); this.rdpegfxAdapter.ExpectFrameAck(fid); fillSurfRect = new RDPGFX_RECT16(RdpegfxTestUtility.smallWidth, RdpegfxTestUtility.smallHeight, (ushort)(RdpegfxTestUtility.smallWidth*2), (ushort)(RdpegfxTestUtility.smallHeight*2)); fillRects = new RDPGFX_RECT16[] { fillSurfRect }; // Relative to surface fid = this.rdpegfxAdapter.SolidFillSurface(surf, RdpegfxTestUtility.fillColorRed, fillRects); this.TestSite.Log.Add(LogEntryKind.Debug, "Solid fill first area of surface by Red in frame: {0}", fid); this.rdpegfxAdapter.ExpectFrameAck(fid); // Fill a rectangle with red color and copy it to another position of the surface RDPGFX_POINT16[] destPts = { new RDPGFX_POINT16(RdpegfxTestUtility.smallWidth, RdpegfxTestUtility.smallHeight) }; RDPGFX_RECT16 srcRect = new RDPGFX_RECT16(0, 0, (ushort)(RdpegfxTestUtility.smallWidth * 2), (ushort)(RdpegfxTestUtility.smallHeight * 2)); fid = this.rdpegfxAdapter.IntraSurfaceCopy(surf, RdpegfxTestUtility.copySrcRect, destPts); this.rdpegfxAdapter.ExpectFrameAck(fid); this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true."); this.VerifySUTDisplay(false, surfRect); // Delete the surface this.rdpegfxAdapter.DeleteSurface(surf.Id); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf.Id); } [TestMethod] [Priority(1)] [TestCategory("Non-BVT")] [TestCategory("Negative")] [TestCategory("RDP8.0")] [TestCategory("RDPEGFX")] [Description("Attempt to copy bitmap from inexistent source surface to destination surface")] public void RDPEGFX_SurfaceToSurface_Negative_InterSurfaceCopy_InexistentSrc() { this.TestSite.Log.Add(LogEntryKind.Comment, "Do capability exchange."); RDPEGFX_CapabilityExchange(); // Create & output source surface, then fill it with green color RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id); RDPGFX_RECT16 fillSurfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); RDPGFX_RECT16[] fillRects = { fillSurfRect }; // Relative to surface uint fid = this.rdpegfxAdapter.SolidFillSurface(surf, RdpegfxTestUtility.fillColorGreen, fillRects); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled with solid color in frame: {0}", fid); // Expect the client to send a frame acknowledge pdu this.rdpegfxAdapter.ExpectFrameAck(fid); // Create & output destination surface RDPGFX_RECT16 surfRect2 = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos2, RdpegfxTestUtility.surfWidth2, RdpegfxTestUtility.surfHeight2); Surface surf2 = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect2, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf2.Id); this.TestSite.Log.Add(LogEntryKind.Comment, "Set the test type to {0}.", RdpegfxNegativeTypes.SurfaceManagement_InterSurfaceCopy_InexistentSrc); this.rdpegfxAdapter.SetTestType(RdpegfxNegativeTypes.SurfaceManagement_InterSurfaceCopy_InexistentSrc); // Trigger client to copy bitmap from inexistent source to destination surface RDPGFX_POINT16[] destPts = { RdpegfxTestUtility.imgPos2 }; this.TestSite.Log.Add(LogEntryKind.Comment, "Trigger client to copy bitmap from inexistent source to destination surface."); fid = this.rdpegfxAdapter.InterSurfaceCopy(surf, RdpegfxTestUtility.copySrcRect, RdpegfxTestUtility.fillColorRed, surf2, destPts); this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to drop the connection"); bool bDisconnected = this.rdpbcgrAdapter.WaitForDisconnection(waitTime); this.TestSite.Assert.IsTrue(bDisconnected, "RDP client should terminate the connection when invalid message received."); } [TestMethod] [Priority(1)] [TestCategory("Non-BVT")] [TestCategory("Negative")] [TestCategory("RDP8.0")] [TestCategory("RDPEGFX")] [Description("Attempt to copy bitmap from source surface to inexistent destination surface")] public void RDPEGFX_SurfaceToSurface_Negative_InterSurfaceCopy_InexistentDest() { this.TestSite.Log.Add(LogEntryKind.Comment, "Do capability exchange."); RDPEGFX_CapabilityExchange(); // Create & output source surface, then fill it with green color RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id); RDPGFX_RECT16 fillSurfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); RDPGFX_RECT16[] fillRects = { fillSurfRect }; // Relative to surface uint fid = this.rdpegfxAdapter.SolidFillSurface(surf, RdpegfxTestUtility.fillColorGreen, fillRects); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled with solid color in frame: {0}", fid); // Expect the client to send a frame acknowledge pdu this.rdpegfxAdapter.ExpectFrameAck(fid); // Create & output destination surface RDPGFX_RECT16 surfRect2 = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos2, RdpegfxTestUtility.surfWidth2, RdpegfxTestUtility.surfHeight2); Surface surf2 = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect2, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf2.Id); this.TestSite.Log.Add(LogEntryKind.Comment, "Set the test type to {0}.", RdpegfxNegativeTypes.SurfaceManagement_InterSurfaceCopy_InexistentDest); this.rdpegfxAdapter.SetTestType(RdpegfxNegativeTypes.SurfaceManagement_InterSurfaceCopy_InexistentDest); // Trigger client to copy bitmap from source to inexistent destination surface RDPGFX_POINT16[] destPts = { RdpegfxTestUtility.imgPos2 }; this.TestSite.Log.Add(LogEntryKind.Comment, "Trigger client to copy bitmap from source to inexistent destination surface."); fid = this.rdpegfxAdapter.InterSurfaceCopy(surf, RdpegfxTestUtility.copySrcRect, RdpegfxTestUtility.fillColorRed, surf2, destPts); this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to drop the connection"); bool bDisconnected = this.rdpbcgrAdapter.WaitForDisconnection(waitTime); this.TestSite.Assert.IsTrue(bDisconnected, "RDP client should terminate the connection when invalid message received."); } [TestMethod] [Priority(1)] [TestCategory("Non-BVT")] [TestCategory("Negative")] [TestCategory("RDP8.0")] [TestCategory("RDPEGFX")] [Description("Attempt to copy bitmap with boundary out of source surface to destination surface")] public void RDPEGFX_SurfaceToSurface_Negative_InterSurfaceCopy_SrcOutOfBoundary() { this.TestSite.Log.Add(LogEntryKind.Comment, "Do capability exchange."); RDPEGFX_CapabilityExchange(); // Create & output source surface, then fill it with green color RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id); RDPGFX_RECT16 fillSurfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); RDPGFX_RECT16[] fillRects = { fillSurfRect }; // Relative to surface uint fid = this.rdpegfxAdapter.SolidFillSurface(surf, RdpegfxTestUtility.fillColorGreen, fillRects); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled with solid color in frame: {0}", fid); // Expect the client to send a frame acknowledge pdu this.rdpegfxAdapter.ExpectFrameAck(fid); // Create & output destination surface RDPGFX_RECT16 surfRect2 = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth3, RdpegfxTestUtility.surfHeight3); Surface surf2 = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect2, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf2.Id); // Trigger client to copy bitmap with boundary out of source surface to destination surface RDPGFX_POINT16[] destPts = { RdpegfxTestUtility.imgPos2 }; // Relative to destination surface this.TestSite.Log.Add(LogEntryKind.Comment, "Trigger client to copy bitmap with boundary out of source surface to destination surface."); fid = this.rdpegfxAdapter.InterSurfaceCopy(surf, RdpegfxTestUtility.copySrcRect2, RdpegfxTestUtility.fillColorRed, surf2, destPts); this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to drop the connection"); bool bDisconnected = this.rdpbcgrAdapter.WaitForDisconnection(waitTime); this.TestSite.Assert.IsTrue(bDisconnected, "RDP client should terminate the connection when received an invalid message."); } [TestMethod] [Priority(1)] [TestCategory("Non-BVT")] [TestCategory("Negative")] [TestCategory("RDP8.0")] [TestCategory("RDPEGFX")] [Description("Attempt to copy bitmap of source surface to illegal position outside destination surface")] public void RDPEGFX_SurfaceToSurface_Negative_InterSurfaceCopy_DestOutOfBoundary() { this.TestSite.Log.Add(LogEntryKind.Comment, "Do capability exchange."); RDPEGFX_CapabilityExchange(); // Create & output source surface, then fill it with green color RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id); RDPGFX_RECT16 fillSurfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); RDPGFX_RECT16[] fillRects = { fillSurfRect }; // Relative to surface uint fid = this.rdpegfxAdapter.SolidFillSurface(surf, RdpegfxTestUtility.fillColorGreen, fillRects); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled with solid color in frame: {0}", fid); // Expect the client to send a frame acknowledge pdu this.rdpegfxAdapter.ExpectFrameAck(fid); // Create & output destination surface RDPGFX_RECT16 surfRect2 = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth3, RdpegfxTestUtility.surfHeight3); Surface surf2 = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect2, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf2.Id); // Trigger client to copy bitmap of source surface to illegal position outside destination surface RDPGFX_POINT16[] destPts = { RdpegfxTestUtility.imgPos4 }; // imgPos4 is a position outside destination surface this.TestSite.Log.Add(LogEntryKind.Comment, "Trigger client to copy bitmap of source surface to illegal position outside destination surface."); fid = this.rdpegfxAdapter.InterSurfaceCopy(surf, RdpegfxTestUtility.copySrcRect, RdpegfxTestUtility.fillColorRed, surf2, destPts); this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to drop the connection"); bool bDisconnected = this.rdpbcgrAdapter.WaitForDisconnection(waitTime); TestSite.Assert.IsTrue(bDisconnected, "RDP client should terminate the connection when received an invalid message."); } [TestMethod] [Priority(1)] [TestCategory("Non-BVT")] [TestCategory("Negative")] [TestCategory("RDP8.0")] [TestCategory("RDPEGFX")] [Description("Check if the client can handle the situation where value of destPtsCount and the length of destPts doesn't match")] public void RDPEGFX_SurfaceToSurface_Negative_DestPtsMismatch() { this.TestSite.Log.Add(LogEntryKind.Comment, "Do capability exchange."); RDPEGFX_CapabilityExchange(); // Create & output source surface, then fill it with green color RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888); this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id); RDPGFX_RECT16 fillSurfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.imgPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight); RDPGFX_RECT16[] fillRects = { fillSurfRect }; // Relative to surface uint fid = this.rdpegfxAdapter.SolidFillSurface(surf, RdpegfxTestUtility.fillColorGreen, fillRects); this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled with solid color in frame: {0}", fid); // Expect the client to send a frame acknowledge pdu this.rdpegfxAdapter.ExpectFrameAck(fid); // Create & output destination surface RDPGFX_RECT16 surfRect2 = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth3, RdpegfxTestUtility.surfHeight3); Surface surf2 = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect2, PixelFormat.PIXEL_FORMAT_ARGB_8888); Site.Assert.IsNotNull(surf, "Surface {0} is created", surf2.Id); this.TestSite.Log.Add(LogEntryKind.Comment, "Set the test type to {0}.", RdpegfxNegativeTypes.SurfaceManagement_InterSurfaceCopy_DestPtsCount_Mismatch); this.rdpegfxAdapter.SetTestType(RdpegfxNegativeTypes.SurfaceManagement_InterSurfaceCopy_DestPtsCount_Mismatch); // Send a SurfaceToSurface PDU to client with value of destPtsCount and the length of destPts doesn't match RDPGFX_POINT16[] destPts = { RdpegfxTestUtility.imgPos2 }; // Relative to destination surface this.TestSite.Log.Add(LogEntryKind.Comment, "Send a SurfaceToSurface PDU to client with value of destPtsCount and the length of destPts doesn't match."); fid = this.rdpegfxAdapter.InterSurfaceCopy(surf, RdpegfxTestUtility.copySrcRect, RdpegfxTestUtility.fillColorRed, surf2, destPts); this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to drop the connection"); bool bDisconnected = this.rdpbcgrAdapter.WaitForDisconnection(waitTime); TestSite.Assert.IsTrue(bDisconnected, "RDP client should terminate the connection when received an invalid message."); } } }
namespace DeOps.Services.Storage { partial class DetailsForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { DeOps.Interface.TLVex.ToggleColumnHeader toggleColumnHeader1 = new DeOps.Interface.TLVex.ToggleColumnHeader(); DeOps.Interface.TLVex.ToggleColumnHeader toggleColumnHeader2 = new DeOps.Interface.TLVex.ToggleColumnHeader(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DetailsForm)); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.EditLink = new System.Windows.Forms.LinkLabel(); this.RemoveLink = new System.Windows.Forms.LinkLabel(); this.AddLink = new System.Windows.Forms.LinkLabel(); this.VisList = new DeOps.Interface.TLVex.ContainerListViewEx(); this.ExitButton = new System.Windows.Forms.Button(); this.OkButton = new System.Windows.Forms.Button(); this.NameBox = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.SizeLabel = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox1.Controls.Add(this.EditLink); this.groupBox1.Controls.Add(this.RemoveLink); this.groupBox1.Controls.Add(this.AddLink); this.groupBox1.Controls.Add(this.VisList); this.groupBox1.Location = new System.Drawing.Point(12, 71); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(237, 180); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "Restrict Scope"; // // EditLink // this.EditLink.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.EditLink.AutoSize = true; this.EditLink.Location = new System.Drawing.Point(97, 161); this.EditLink.Name = "EditLink"; this.EditLink.Size = new System.Drawing.Size(25, 13); this.EditLink.TabIndex = 8; this.EditLink.TabStop = true; this.EditLink.Text = "Edit"; this.EditLink.Visible = false; this.EditLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.EditLink_LinkClicked); // // RemoveLink // this.RemoveLink.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.RemoveLink.AutoSize = true; this.RemoveLink.Location = new System.Drawing.Point(44, 161); this.RemoveLink.Name = "RemoveLink"; this.RemoveLink.Size = new System.Drawing.Size(47, 13); this.RemoveLink.TabIndex = 2; this.RemoveLink.TabStop = true; this.RemoveLink.Text = "Remove"; this.RemoveLink.Visible = false; this.RemoveLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.RemoveLink_LinkClicked); // // AddLink // this.AddLink.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.AddLink.AutoSize = true; this.AddLink.Location = new System.Drawing.Point(12, 161); this.AddLink.Name = "AddLink"; this.AddLink.Size = new System.Drawing.Size(26, 13); this.AddLink.TabIndex = 1; this.AddLink.TabStop = true; this.AddLink.Text = "Add"; this.AddLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.AddLink_LinkClicked); // // VisList // this.VisList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.VisList.BackColor = System.Drawing.SystemColors.Window; this.VisList.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; toggleColumnHeader1.Hovered = false; toggleColumnHeader1.Image = null; toggleColumnHeader1.Index = 0; toggleColumnHeader1.Pressed = false; toggleColumnHeader1.ScaleStyle = DeOps.Interface.TLVex.ColumnScaleStyle.Spring; toggleColumnHeader1.Selected = false; toggleColumnHeader1.Text = "Person"; toggleColumnHeader1.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; toggleColumnHeader1.Visible = true; toggleColumnHeader1.Width = 133; toggleColumnHeader2.Hovered = false; toggleColumnHeader2.Image = null; toggleColumnHeader2.Index = 0; toggleColumnHeader2.Pressed = false; toggleColumnHeader2.ScaleStyle = DeOps.Interface.TLVex.ColumnScaleStyle.Slide; toggleColumnHeader2.Selected = false; toggleColumnHeader2.Text = "Sub-Levels"; toggleColumnHeader2.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; toggleColumnHeader2.Visible = true; this.VisList.Columns.AddRange(new DeOps.Interface.TLVex.ToggleColumnHeader[] { toggleColumnHeader1, toggleColumnHeader2}); this.VisList.ColumnSortColor = System.Drawing.Color.Gainsboro; this.VisList.ColumnTrackColor = System.Drawing.Color.WhiteSmoke; this.VisList.DisableHorizontalScroll = true; this.VisList.GridLineColor = System.Drawing.Color.WhiteSmoke; this.VisList.HeaderMenu = null; this.VisList.ItemMenu = null; this.VisList.LabelEdit = false; this.VisList.Location = new System.Drawing.Point(6, 19); this.VisList.MultiSelect = true; this.VisList.Name = "VisList"; this.VisList.RowSelectColor = System.Drawing.SystemColors.Highlight; this.VisList.RowTrackColor = System.Drawing.Color.WhiteSmoke; this.VisList.Size = new System.Drawing.Size(225, 139); this.VisList.SmallImageList = null; this.VisList.StateImageList = null; this.VisList.TabIndex = 0; this.VisList.Text = "VisList"; this.VisList.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.VisList_MouseDoubleClick); this.VisList.SelectedIndexChanged += new System.EventHandler(this.VisList_SelectedIndexChanged); // // ExitButton // this.ExitButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.ExitButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.ExitButton.Location = new System.Drawing.Point(174, 266); this.ExitButton.Name = "ExitButton"; this.ExitButton.Size = new System.Drawing.Size(75, 23); this.ExitButton.TabIndex = 2; this.ExitButton.Text = "Close"; this.ExitButton.UseVisualStyleBackColor = true; this.ExitButton.Click += new System.EventHandler(this.ExitButton_Click); // // OkButton // this.OkButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.OkButton.Location = new System.Drawing.Point(93, 266); this.OkButton.Name = "OkButton"; this.OkButton.Size = new System.Drawing.Size(75, 23); this.OkButton.TabIndex = 3; this.OkButton.Text = "OK"; this.OkButton.UseVisualStyleBackColor = true; this.OkButton.Click += new System.EventHandler(this.OkButton_Click); // // NameBox // this.NameBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.NameBox.Location = new System.Drawing.Point(51, 12); this.NameBox.Name = "NameBox"; this.NameBox.Size = new System.Drawing.Size(198, 20); this.NameBox.TabIndex = 4; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(12, 44); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(30, 13); this.label6.TabIndex = 5; this.label6.Text = "Size:"; // // SizeLabel // this.SizeLabel.AutoSize = true; this.SizeLabel.Location = new System.Drawing.Point(48, 44); this.SizeLabel.Name = "SizeLabel"; this.SizeLabel.Size = new System.Drawing.Size(83, 13); this.SizeLabel.TabIndex = 6; this.SizeLabel.Text = "1,023,234 bytes"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(12, 15); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(38, 13); this.label8.TabIndex = 7; this.label8.Text = "Name:"; // // DetailsForm // this.AcceptButton = this.OkButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.ExitButton; this.ClientSize = new System.Drawing.Size(261, 301); this.Controls.Add(this.label8); this.Controls.Add(this.SizeLabel); this.Controls.Add(this.label6); this.Controls.Add(this.NameBox); this.Controls.Add(this.OkButton); this.Controls.Add(this.ExitButton); this.Controls.Add(this.groupBox1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "DetailsForm"; this.Text = "Details"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button ExitButton; private System.Windows.Forms.Button OkButton; private System.Windows.Forms.TextBox NameBox; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label SizeLabel; private System.Windows.Forms.Label label8; private DeOps.Interface.TLVex.ContainerListViewEx VisList; private System.Windows.Forms.LinkLabel RemoveLink; private System.Windows.Forms.LinkLabel AddLink; private System.Windows.Forms.LinkLabel EditLink; } }
namespace Epi.Windows.Analysis.Dialogs { partial class DefineVariableDialog : CommandDesignDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DefineVariableDialog)); this.btnHelp = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.lblDLLObjectDef = new System.Windows.Forms.Label(); this.txtDLLObjectDef = new System.Windows.Forms.TextBox(); this.cmbVarType = new Epi.Windows.Controls.LocalizedComboBox(); this.lblVarType = new System.Windows.Forms.Label(); this.rdbPermanent = new System.Windows.Forms.RadioButton(); this.rdbGlobal = new System.Windows.Forms.RadioButton(); this.rdbStandard = new System.Windows.Forms.RadioButton(); this.lblVarName = new System.Windows.Forms.Label(); this.txtVarName = new System.Windows.Forms.TextBox(); this.gbxScope = new System.Windows.Forms.GroupBox(); this.btnSaveOnly = new System.Windows.Forms.Button(); this.lblVarNameErr = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); this.gbxScope.SuspendLayout(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); this.baseImageList.Images.SetKeyName(76, ""); this.baseImageList.Images.SetKeyName(77, ""); this.baseImageList.Images.SetKeyName(78, ""); // // btnHelp // resources.ApplyResources(this.btnHelp, "btnHelp"); this.btnHelp.Name = "btnHelp"; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.Name = "btnCancel"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; // // btnClear // resources.ApplyResources(this.btnClear, "btnClear"); this.btnClear.Name = "btnClear"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // groupBox1 // resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Controls.Add(this.lblDLLObjectDef); this.groupBox1.Controls.Add(this.txtDLLObjectDef); this.groupBox1.Controls.Add(this.cmbVarType); this.groupBox1.Controls.Add(this.lblVarType); this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // lblDLLObjectDef // resources.ApplyResources(this.lblDLLObjectDef, "lblDLLObjectDef"); this.lblDLLObjectDef.Name = "lblDLLObjectDef"; // // txtDLLObjectDef // resources.ApplyResources(this.txtDLLObjectDef, "txtDLLObjectDef"); this.txtDLLObjectDef.Name = "txtDLLObjectDef"; this.txtDLLObjectDef.TextChanged += new System.EventHandler(this.txtDLLObjectDef_TextChanged); // // cmbVarType // this.cmbVarType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbVarType, "cmbVarType"); this.cmbVarType.Name = "cmbVarType"; this.cmbVarType.SkipTranslation = false; this.cmbVarType.SelectedIndexChanged += new System.EventHandler(this.cmbVarType_SelectedIndexChanged); // // lblVarType // this.lblVarType.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblVarType, "lblVarType"); this.lblVarType.Name = "lblVarType"; // // rdbPermanent // resources.ApplyResources(this.rdbPermanent, "rdbPermanent"); this.rdbPermanent.Name = "rdbPermanent"; this.rdbPermanent.Tag = "PERMANENT"; // // rdbGlobal // resources.ApplyResources(this.rdbGlobal, "rdbGlobal"); this.rdbGlobal.Name = "rdbGlobal"; this.rdbGlobal.Tag = "GLOBAL"; // // rdbStandard // this.rdbStandard.Checked = true; resources.ApplyResources(this.rdbStandard, "rdbStandard"); this.rdbStandard.Name = "rdbStandard"; this.rdbStandard.TabStop = true; this.rdbStandard.Tag = "STANDARD"; // // lblVarName // resources.ApplyResources(this.lblVarName, "lblVarName"); this.lblVarName.FlatStyle = System.Windows.Forms.FlatStyle.System; this.lblVarName.Name = "lblVarName"; // // txtVarName // resources.ApplyResources(this.txtVarName, "txtVarName"); this.txtVarName.Name = "txtVarName"; this.txtVarName.TextChanged += new System.EventHandler(this.txtVarName_TextChanged); this.txtVarName.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtVarName_KeyDown); this.txtVarName.Leave += new System.EventHandler(this.txtVarName_Leave); // // gbxScope // resources.ApplyResources(this.gbxScope, "gbxScope"); this.gbxScope.Controls.Add(this.rdbPermanent); this.gbxScope.Controls.Add(this.rdbGlobal); this.gbxScope.Controls.Add(this.rdbStandard); this.gbxScope.FlatStyle = System.Windows.Forms.FlatStyle.System; this.gbxScope.Name = "gbxScope"; this.gbxScope.TabStop = false; // // btnSaveOnly // resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly"); this.btnSaveOnly.Name = "btnSaveOnly"; // // lblVarNameErr // resources.ApplyResources(this.lblVarNameErr, "lblVarNameErr"); this.lblVarNameErr.Name = "lblVarNameErr"; // // DefineVariableDialog // resources.ApplyResources(this, "$this"); this.CancelButton = this.btnCancel; this.Controls.Add(this.lblVarNameErr); this.Controls.Add(this.btnSaveOnly); this.Controls.Add(this.lblVarName); this.Controls.Add(this.txtVarName); this.Controls.Add(this.gbxScope); this.Controls.Add(this.groupBox1); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.btnClear); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DefineVariableDialog"; this.ShowIcon = false; this.Load += new System.EventHandler(this.DefineVariableDialog_Load); this.Leave += new System.EventHandler(this.txtVarName_Leave); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.gbxScope.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.GroupBox groupBox1; private Epi.Windows.Controls.LocalizedComboBox cmbVarType; private System.Windows.Forms.Label lblVarType; private System.Windows.Forms.RadioButton rdbPermanent; private System.Windows.Forms.RadioButton rdbGlobal; private System.Windows.Forms.RadioButton rdbStandard; private System.Windows.Forms.Label lblVarName; private System.Windows.Forms.TextBox txtVarName; private System.Windows.Forms.GroupBox gbxScope; private System.Windows.Forms.Button btnSaveOnly; private System.Windows.Forms.Label lblDLLObjectDef; private System.Windows.Forms.TextBox txtDLLObjectDef; private System.Windows.Forms.Label lblVarNameErr; } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using mshtml; using OpenLiveWriter.CoreServices; namespace OpenLiveWriter.Mshtml { /// <summary> /// Interface used for relaying events from Mshtml /// </summary> public interface IMshtmlDocumentEvents { /// <summary> /// Event raised when the mouse is clicked. /// </summary> event HtmlEventHandler Click; /// <summary> /// Event raised when the mouse is double clicked. /// </summary> event HtmlEventHandler DoubleClick; /// <summary> /// Event raised when the mouse button is down. /// </summary> event HtmlEventHandler MouseDown; /// <summary> /// Event raised when the mouse button is up. /// </summary> event HtmlEventHandler MouseUp; /// <summary> /// Event raised when the selection has changed /// </summary> event EventHandler SelectionChanged; /// <summary> /// Event raised when an alphanumeric key has been pressed /// </summary> event HtmlEventHandler KeyPress; /// <summary> /// Event raised when *any* key has been pressed /// </summary> event HtmlEventHandler KeyDown; /// <summary> /// Event raised when *any* key has been released /// </summary> event HtmlEventHandler KeyUp; /// <summary> /// Notification that a property on the page has changed /// </summary> event HtmlEventHandler PropertyChange; /// <summary> /// Event raised when the document "ReadyState" property changes /// </summary> event EventHandler ReadyStateChanged; /// <summary> /// Event raised when the document gets focus /// </summary> event EventHandler GotFocus; /// <summary> /// Event raised when the document loses focus /// </summary> event EventHandler LostFocus; } /// <summary> /// Defines the Event Handler interface for dealing with events from the MshtmlControl. /// </summary> public delegate void HtmlEventHandler(object o, HtmlEventArgs e); /// <summary> /// Event that wraps the raw IHTMLEventObj fired by the document. /// </summary> public class HtmlEventArgs : EventArgs { private readonly IHTMLEventObj _htmlEvt; private readonly IHTMLEventObj2 _htmlEvt2; public HtmlEventArgs(IHTMLEventObj evt) { _htmlEvt = evt; _htmlEvt2 = evt as IHTMLEventObj2; } public IHTMLEventObj htmlEvt { get { return _htmlEvt; } } public IHTMLEventObj2 htmlEvt2 { get { return _htmlEvt2; } } /// <summary> /// Cancels the event and kills its propogation. /// </summary> public void Cancel() { //set the cancelBubble value htmlEvt.cancelBubble = true; //the returnValue controls the propogation of the event. htmlEvt.returnValue = false; // update state _wasCancelled = true; } public bool WasCancelled { get { return _wasCancelled; } } private bool _wasCancelled = false; } /// <summary> /// Class which implements HTMLDocumentEvents2 to provide an event repeater to /// .NET clients. This enables .NET to directly sink to the events of an /// existing IHTMLDocument2 instance (i.e. one that was not created as part /// of an ActiveX control and therefore doesn't have built in .NET event /// handling). Note that we are only implementing repeaters as needed so many /// of these event handlers are simply no-ops. /// </summary> public class HtmlDocumentEventRepeater : IMshtmlDocumentEvents, HTMLDocumentEvents2 { private readonly EventCounter _eventCounter = new EventCounter(); /// <summary> /// Initialize without attaching to a document instance /// </summary> public HtmlDocumentEventRepeater() { } /// <summary> /// Initialize by attaching to a document instance /// </summary> /// <param name="webBrowser">browser to attach to</param> public HtmlDocumentEventRepeater(IHTMLDocument2 document) { Attach(document); } /// <summary> /// Attach the event repeater to the specified document instance. Call Detach /// when you no longer want to receive events from the document. /// </summary> /// <param name="webBrowser"></param> public void Attach(IHTMLDocument2 document) { // confirm pre-conditions Debug.Assert(document != null); Debug.Assert(connectionPoint == null); // query for the IConnectionPointContainer interface IConnectionPointContainer cpContainer = (IConnectionPointContainer)document; // find the HTMLDocumentEvents2 connection point cpContainer.FindConnectionPoint(ref iidHTMLDocumentEvents2, out connectionPoint); // attach to the event interface connectionPoint.Advise(this, out connectionPointCookie); //cache a handle to the document HtmlDocument = document; _eventCounter.Reset(); } /// <summary> /// Detach the event repeater from the document instance /// </summary> public void Detach() { // confirm preconditions Debug.Assert(connectionPoint != null); // detach and set internal references to null connectionPoint.Unadvise(connectionPointCookie); connectionPoint = null; HtmlDocument = null; _eventCounter.AssertAllEventsAreUnhooked(); } /// <summary> /// Event raised when the mouse is clicked. /// </summary> public event HtmlEventHandler Click { add { ClickEventHandler += value; _eventCounter.EventHooked(ClickEventHandler); } remove { ClickEventHandler -= value; _eventCounter.EventUnhooked(ClickEventHandler); } } private event HtmlEventHandler ClickEventHandler; /// <summary> /// Event raised when the mouse is double clicked. /// </summary> public event HtmlEventHandler DoubleClick { add { DoubleClickEventHandler += value; _eventCounter.EventHooked(DoubleClickEventHandler); } remove { DoubleClickEventHandler -= value; _eventCounter.EventUnhooked(DoubleClickEventHandler); } } private event HtmlEventHandler DoubleClickEventHandler; /// <summary> /// Event raised when the mouse is pressed down. /// </summary> public event HtmlEventHandler MouseDown { add { MouseDownEventHandler += value; _eventCounter.EventHooked(MouseDownEventHandler); } remove { MouseDownEventHandler -= value; _eventCounter.EventUnhooked(MouseDownEventHandler); } } private event HtmlEventHandler MouseDownEventHandler; /// <summary> /// Event raised when the mouse is raised up. /// </summary> public event HtmlEventHandler MouseUp { add { MouseUpEventHandler += value; _eventCounter.EventHooked(MouseUpEventHandler); } remove { MouseUpEventHandler -= value; _eventCounter.EventUnhooked(MouseUpEventHandler); } } private event HtmlEventHandler MouseUpEventHandler; /// <summary> /// Event raised when the selection has changed /// </summary> public event EventHandler SelectionChanged { add { SelectionChangedEventHandler += value; _eventCounter.EventHooked(SelectionChangedEventHandler); } remove { SelectionChangedEventHandler -= value; _eventCounter.EventUnhooked(SelectionChangedEventHandler); } } private event EventHandler SelectionChangedEventHandler; /// <summary> /// Event raised when an alphanumeric key has been pressed /// </summary> public event HtmlEventHandler KeyPress { add { KeyPressEventHandler += value; _eventCounter.EventHooked(KeyPressEventHandler); } remove { KeyPressEventHandler -= value; _eventCounter.EventUnhooked(KeyPressEventHandler); } } private event HtmlEventHandler KeyPressEventHandler; /// <summary> /// Event raised when any key has been pressed (including /// delete, function, and symbols keys, etc) /// </summary> public event HtmlEventHandler KeyDown { add { KeyDownEventHandler += value; _eventCounter.EventHooked(KeyDownEventHandler); } remove { KeyDownEventHandler -= value; _eventCounter.EventUnhooked(KeyDownEventHandler); } } private event HtmlEventHandler KeyDownEventHandler; /// <summary> /// Event raised when any key has been released (including /// delete, function, and symbols keys, etc) /// </summary> public event HtmlEventHandler KeyUp { add { KeyUpEventHandler += value; _eventCounter.EventHooked(KeyUpEventHandler); } remove { KeyUpEventHandler -= value; _eventCounter.EventUnhooked(KeyUpEventHandler); } } private event HtmlEventHandler KeyUpEventHandler; /// <summary> /// Event raised when a property on the page changes /// </summary> public event HtmlEventHandler PropertyChange { add { PropertyChangeEventHandler += value; _eventCounter.EventHooked(PropertyChangeEventHandler); } remove { PropertyChangeEventHandler -= value; _eventCounter.EventUnhooked(PropertyChangeEventHandler); } } private event HtmlEventHandler PropertyChangeEventHandler; /// <summary> /// Event raised when the document "ReadyState" property changes /// </summary> public event EventHandler ReadyStateChanged { add { ReadyStateChangedEventHandler += value; _eventCounter.EventHooked(ReadyStateChangedEventHandler); } remove { ReadyStateChangedEventHandler -= value; _eventCounter.EventUnhooked(ReadyStateChangedEventHandler); } } private event EventHandler ReadyStateChangedEventHandler; /// <summary> /// Event raised when the document gets focus /// </summary> public event EventHandler GotFocus { add { GotFocusEventHandler += value; _eventCounter.EventHooked(GotFocusEventHandler); } remove { GotFocusEventHandler -= value; _eventCounter.EventUnhooked(GotFocusEventHandler); } } private event EventHandler GotFocusEventHandler; /// <summary> /// Event raised when the document loses focus /// </summary> public event EventHandler LostFocus { add { LostFocusEventHandler += value; _eventCounter.EventHooked(LostFocusEventHandler); } remove { LostFocusEventHandler -= value; _eventCounter.EventUnhooked(LostFocusEventHandler); } } private event EventHandler LostFocusEventHandler; ///////////////////////////////////////////////////////////////////////////////// // HTMLDocumentEvents2 implemented event handlers -- These event handlers are // used to 'repeat' events to outside listeners. // void HTMLDocumentEvents2.onselectionchange(IHTMLEventObj pEvtObj) { if (SelectionChangedEventHandler != null) SelectionChangedEventHandler(this, new HtmlEventArgs(pEvtObj)); } void HTMLDocumentEvents2.onreadystatechange(IHTMLEventObj pEvtObj) { if (ReadyStateChangedEventHandler != null) ReadyStateChangedEventHandler(this, EventArgs.Empty); } bool HTMLDocumentEvents2.onkeypress(IHTMLEventObj pEvtObj) { if (KeyPressEventHandler != null) KeyPressEventHandler(this, new HtmlEventArgs(pEvtObj)); return !pEvtObj.cancelBubble; } void HTMLDocumentEvents2.onfocusin(IHTMLEventObj pEvtObj) { if (GotFocusEventHandler != null) GotFocusEventHandler(this, EventArgs.Empty); } void HTMLDocumentEvents2.onfocusout(IHTMLEventObj pEvtObj) { if (LostFocusEventHandler != null) LostFocusEventHandler(this, EventArgs.Empty); } ///////////////////////////////////////////////////////////////////////////////// // HTMLDocumentEvents2 no-op event handlers -- As we need to handle the various // events we will fill in the implementations. NOTE that even though the MSDN // documentation asserts that we should return FALSE from these event handlers // to allow event bubbling the reverse of this is in fact in the case. You // actually must return TRUE to allow events to propagate. See the extended // comment at the bottom of this file for more info. // void HTMLDocumentEvents2.ondataavailable(IHTMLEventObj pEvtObj) { } bool HTMLDocumentEvents2.onbeforedeactivate(IHTMLEventObj pEvtObj) { return true; } bool HTMLDocumentEvents2.onstop(IHTMLEventObj pEvtObj) { return true; } void HTMLDocumentEvents2.onrowsinserted(IHTMLEventObj pEvtObj) { } bool HTMLDocumentEvents2.onselectstart(IHTMLEventObj pEvtObj) { return true; } bool HTMLDocumentEvents2.onhelp(IHTMLEventObj pEvtObj) { return true; } void HTMLDocumentEvents2.onpropertychange(IHTMLEventObj pEvtObj) { if (PropertyChangeEventHandler != null) PropertyChangeEventHandler(this, new HtmlEventArgs(pEvtObj)); } void HTMLDocumentEvents2.oncellchange(IHTMLEventObj pEvtObj) { } bool HTMLDocumentEvents2.oncontextmenu(IHTMLEventObj pEvtObj) { return true; } bool HTMLDocumentEvents2.ondblclick(IHTMLEventObj pEvtObj) { if (DoubleClickEventHandler != null) DoubleClickEventHandler(this, new HtmlEventArgs(pEvtObj)); return !pEvtObj.cancelBubble; } void HTMLDocumentEvents2.ondatasetcomplete(IHTMLEventObj pEvtObj) { } void HTMLDocumentEvents2.onbeforeeditfocus(IHTMLEventObj pEvtObj) { } bool HTMLDocumentEvents2.ondragstart(IHTMLEventObj pEvtObj) { return true; } bool HTMLDocumentEvents2.oncontrolselect(IHTMLEventObj pEvtObj) { return true; } void HTMLDocumentEvents2.onactivate(IHTMLEventObj pEvtObj) { } void HTMLDocumentEvents2.onmouseup(IHTMLEventObj pEvtObj) { if (MouseUpEventHandler != null) MouseUpEventHandler(this, new HtmlEventArgs(pEvtObj)); } bool HTMLDocumentEvents2.onbeforeactivate(IHTMLEventObj pEvtObj) { return true; } void HTMLDocumentEvents2.onkeydown(IHTMLEventObj pEvtObj) { if (KeyDownEventHandler != null) KeyDownEventHandler(this, new HtmlEventArgs(pEvtObj)); } void HTMLDocumentEvents2.onkeyup(IHTMLEventObj pEvtObj) { if (KeyUpEventHandler != null) KeyUpEventHandler(this, new HtmlEventArgs(pEvtObj)); } bool HTMLDocumentEvents2.onrowexit(IHTMLEventObj pEvtObj) { return true; } bool HTMLDocumentEvents2.onbeforeupdate(IHTMLEventObj pEvtObj) { return true; } void HTMLDocumentEvents2.onrowsdelete(IHTMLEventObj pEvtObj) { } void HTMLDocumentEvents2.onmousemove(IHTMLEventObj pEvtObj) { } void HTMLDocumentEvents2.onrowenter(IHTMLEventObj pEvtObj) { } void HTMLDocumentEvents2.onafterupdate(IHTMLEventObj pEvtObj) { } void HTMLDocumentEvents2.ondeactivate(IHTMLEventObj pEvtObj) { } void HTMLDocumentEvents2.ondatasetchanged(IHTMLEventObj pEvtObj) { } void HTMLDocumentEvents2.onmouseover(IHTMLEventObj pEvtObj) { } bool HTMLDocumentEvents2.onmousewheel(IHTMLEventObj pEvtObj) { return true; } bool HTMLDocumentEvents2.onerrorupdate(IHTMLEventObj pEvtObj) { return true; } void HTMLDocumentEvents2.onmouseout(IHTMLEventObj pEvtObj) { } void HTMLDocumentEvents2.onmousedown(IHTMLEventObj pEvtObj) { if (MouseDownEventHandler != null) MouseDownEventHandler(this, new HtmlEventArgs(pEvtObj)); } bool HTMLDocumentEvents2.onclick(IHTMLEventObj pEvtObj) { if (ClickEventHandler != null) ClickEventHandler(this, new HtmlEventArgs(pEvtObj)); return !pEvtObj.cancelBubble; } // interface id for document events private Guid iidHTMLDocumentEvents2 = typeof(HTMLDocumentEvents2).GUID; // connection point cookie used for call to IConnectionPoint.Unadvise private int connectionPointCookie = 0; // connection point that we attach our event interface to private IConnectionPoint connectionPoint = null; /// <summary> /// document that this object repeats events for. /// </summary> public IHTMLDocument2 HtmlDocument; /// <summary> /// Internal utility for providing IE6-compatible focus events on IE 5.5. /// his method keeps track of focus states and fires focus events if a focus change has occured. /// </summary> internal void NotifyDocumentDisplayChanged() { if (HtmlDocument != null && !SupportsIE6Events) { //IE 5.5 doesn't fire focus events, so keep track of the focus state and fire the event //when a change is detected (bug 1957). bool hasFocus = (HtmlDocument as IHTMLDocument4).hasFocus(); if (wasFocused != hasFocus) { if (hasFocus) { if (GotFocusEventHandler != null) GotFocusEventHandler(this, EventArgs.Empty); } else { if (LostFocusEventHandler != null) LostFocusEventHandler(this, EventArgs.Empty); } wasFocused = hasFocus; } } } bool wasFocused; /// <summary> /// Returns true if the control is running with an IE6-event-compatible browser. /// </summary> private bool SupportsIE6Events { get { if (supportsIE6Events == -1 && HtmlDocument != null) { try { //attempt to use a method that is only supported by IE6 and later. If this throws an //exception, then we know that we know that IE6 events are not supported. supportsIE6Events = (HtmlDocument as IHTMLDocument5).onfocusin != null ? 1 : 0; } catch (Exception) { supportsIE6Events = 0; } if (supportsIE6Events == 0) Trace.WriteLine("Using IE6 event compatibility mode"); } return supportsIE6Events == 1; } } private int supportsIE6Events = -1; //use an int so that we can have 3 states(unknown/false/true) } } /* INFORMATION ON HTMLDocumentEvents2 Workaround Google Groups Search: DotNet HTMLDocumentEvents2 URL for newsgroup posting on workaround: http://groups.google.com/groups?q=DotNet+HTMLDocumentEvents2&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=9YiIa.12479%24Xj1.5184%40fe04.atl2.webusenet.com&rnum=2 Contents on newsgroup posting: Okay, now that we've all felt the pain of watching "+=" event handler registration kill all OTHER (default/existing) event handling in our MSHTML-related code, here's a workaround of sorts. I say "of sorts", because it doesn't allow you to selectively (on a per-event basis) cancel or enable event bubbling. Blame for the C# code goes to me, credit to the MSIE support team for the trick of using the "wrong" return values from the event handlers so that other (existing) event handlers get invoked (the thing that has killed us all when we use "+=" to register an onmousemove, only to watch keyboard handling disappear, etc.). Rumor has it that there will be a KB article with this workaround in the next month or so. 1) Declare that your class implements HTMLDocumentEvents2 public class YourClass : mshtml.HTMLDocumentEvents2[, other interfaces implemented by your class] 2) Declare the equivalent of the following class members: private UCOMIConnectionPoint m_ConnectionPoint; // connection point for advisory notifications private Int32 m_ConnectionPointCookie = -1; // the cookie val that idents the connection instance 3) Implement all the members of that interface, coding your "specializations" where desired: NOTE: The Platform SDK documentation for the following members that return boolean values states they should return "false" to allow other (registered) event handlers to continue processing the event, or "true" to PREVENT other handlers from handling the event. The current interop code does NOT function this way - "false" prevents other event handlers from processing the event, "true" ALLOWS them to process the event. Rumor has it that returning "false" actually cancels subsequent event handling in an intermittent fashion, but I have not seen this behavior. #region HTMLDocumentEvents2 interface members public void onactivate(mshtml.IHTMLEventObj evtObj ) { } public void onafterupdate(mshtml.IHTMLEventObj evtObj) { } public bool onbeforeactivate(mshtml.IHTMLEventObj evtObj) { return true; } public bool onbeforedeactivate(mshtml.IHTMLEventObj evtObj) { return true; } public void onbeforeeditfocus(mshtml.IHTMLEventObj evtObj) { } public bool onbeforeupdate(mshtml.IHTMLEventObj evtObj) { return true; } public void oncellchange(mshtml.IHTMLEventObj evtObj) { } public bool onclick(mshtml.IHTMLEventObj evtObj) { return true; } public bool oncontextmenu(mshtml.IHTMLEventObj evtObj) { return true; } public bool oncontrolselect(mshtml.IHTMLEventObj evtObj) { return true; } public void ondataavailable(mshtml.IHTMLEventObj evtObj) { } public void ondatasetchanged(mshtml.IHTMLEventObj evtObj) { } public void ondatasetcomplete(mshtml.IHTMLEventObj evtObj) { } public bool ondblclick(mshtml.IHTMLEventObj evtObj) { return true; } public void ondeactivate(mshtml.IHTMLEventObj evtObj) { } public bool ondragstart(mshtml.IHTMLEventObj evtObj) { return true; } public bool onerrorupdate(mshtml.IHTMLEventObj evtObj) { return true; } public void onfocusin(mshtml.IHTMLEventObj evtObj) { } public void onfocusout(mshtml.IHTMLEventObj evtObj) { } public bool onhelp(mshtml.IHTMLEventObj evtObj) { return true; } public void onkeydown(mshtml.IHTMLEventObj evtObj) { } public bool onkeypress(mshtml.IHTMLEventObj evtObj) { return true; } public void onkeyup(mshtml.IHTMLEventObj evtObj) { } public void onmousedown(mshtml.IHTMLEventObj evtObj) { } public void onmousemove(mshtml.IHTMLEventObj evtObj) { } public void onmouseout(mshtml.IHTMLEventObj evtObj) { } public void onmouseover(mshtml.IHTMLEventObj evtObj) { } public void onmouseup(mshtml.IHTMLEventObj evtObj) { } public bool onmousewheel(mshtml.IHTMLEventObj evtObj) { return true; } public void onpropertychange(mshtml.IHTMLEventObj evtObj) { } public void onreadystatechange(mshtml.IHTMLEventObj evtObj) { } public void onrowenter(mshtml.IHTMLEventObj evtObj) { } public bool onrowexit(mshtml.IHTMLEventObj evtObj) { return true; } public void onrowsdelete(mshtml.IHTMLEventObj evtObj) { } public void onrowsinserted(mshtml.IHTMLEventObj evtObj) { } public void onselectionchange(mshtml.IHTMLEventObj evtObj) { } public bool onselectstart(mshtml.IHTMLEventObj evtObj) { return true; } public bool onstop(mshtml.IHTMLEventObj evtObj) { return true; } #endregion 4)In your DocumentComplete handler (or some other point where the document state is "Ready"), // find the source interface GUID for HTMLDocumentEvents2 // HKEY_CLASSES_ROOT\Interface\{3050F60F-98B5-11CF-BB82-00AA00BDCE0B} Guid guid = typeof(mshtml.HTMLDocumentEvents2).GUID; // // m_HtmlDoc is the HTML doc; in my case, mshtml.IHTMLDocument2 UCOMIConnectionPointContainer icpc = (UCOMIConnectionPointContainer)m_HtmlDoc; icpc.FindConnectionPoint(ref guid, out m_ConnectionPoint); m_ConnectionPoint.Advise(this, out m_ConnectionPointCookie); 5) Unregister your event sink in your BeforeNavigate2 handler (or other point where you will no longer want to receive HTMLDocumentEvents2 notifications): if (this.m_ConnectionPointCookie != -1) m_ConnectionPoint.Unadvise( this.m_ConnectionPointCookie); BOL -- Regards, Jim Allison jwallison.1@bellsouth.net (de-mung by removing '.1') */
using System; using System.Collections; using System.IO; using System.Reflection; using System.Web.Services.Description; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Globalization; using Thinktecture.Tools.Wscf.Services.ServiceDescription.Exceptions; using FxMessage = System.Web.Services.Description.Message; using FxOperation = System.Web.Services.Description.Operation; using System.ServiceModel.Description; using System.Collections.Generic; using System.ServiceModel; using System.ServiceModel.Channels; using System.Collections.Specialized; using Thinktecture.Tools.Web.Services.Wscf.Environment; namespace Thinktecture.Tools.Wscf.Services.ServiceDescription { #region ServiceDescriptionEngine class /// <summary> /// Provides static methods for WSDL generation. /// </summary> /// <remarks>This class could not be inherited.</remarks> public sealed class ServiceDescriptionEngine { #region Constructors /// <summary> /// Initializes a new instance of ServiceDescriptionEngine class. /// </summary> private ServiceDescriptionEngine() { } #endregion #region Public static methods for WSDL Construction. /// <summary> /// Generates the WSDL file for specified <see cref="InterfaceContract"/>. /// </summary> /// <param name="serviceInterfaceContract"> /// <see cref="InterfaceContract"/> to use for the WSDL generation. /// </param> /// <param name="wsdlSaveLocation">Location to save the generated WSDL file.</param> /// <param name="xmlComment">XML comment to add to the top of the WSDL file.</param> /// <returns>The path of the WSDL file generated.</returns> public static string GenerateWsdl(InterfaceContract serviceInterfaceContract, string wsdlSaveLocation, string xmlComment) { return GenerateWsdl(serviceInterfaceContract, wsdlSaveLocation, xmlComment, null); } /// <summary> /// Generates the WSDL file for a specified <see cref="InterfaceContract"/>. /// </summary> /// <param name="serviceInterfaceContract"> /// <see cref="InterfaceContract"/> to use for the WSDL generation. /// </param> /// <param name="wsdlSaveLocation">Location to save the generated WSDL file.</param> /// <param name="xmlComment">XML comment to add to the top of the WSDL file.</param> /// <param name="currWsdlLocation">Path of an existing WSDL file to overwrite with the generated /// WSDL file.</param> /// <returns>The path of the WSDL file generated.</returns> /// <remarks> /// This methods loads the information, it receive in a <see cref="InterfaceContract"/> to /// a <see cref="System.Web.Services.Description.ServiceDescription"/> class, which is later /// used to generate the WSDL file. The loading process takes place in several steps. <br></br> /// 1. Load the basic meta data from <see cref="InterfaceContract"/>.<br></br> /// 2. Load the schema imports in the <see cref="SchemaImports"/> collection.<br></br> /// 3. Load the messages in <see cref="OperationsCollection"/>.<br></br> /// 4. Create the WSDL Port Type.<br></br> /// 5. Add each operation and it's corresponding in/out messages to the Port Type.<br></br> /// 6. Create a WSDL Binding section and add OperationBinding for each operation.<br></br> /// 7. Generate the WSDL 'service' tags if required.<br></br> /// 8. Finally write the file to the output stream.<br></br> /// /// This method generates <see cref="WsdlGenerationException"/> exception, if it fails to create the WSDL file. /// If a file is specified to overwrite with the new file, the original file is restored in case of /// a failure. /// </remarks> public static string GenerateWsdl(InterfaceContract serviceInterfaceContract, string wsdlSaveLocation, string xmlComment, string currWsdlLocation) { // delegate the wsdl data construction to another method string wsdlData = GenerateWsdlData(serviceInterfaceContract, xmlComment, currWsdlLocation); // return the file name into which the wsdl data is persisted return PersistWsdl(serviceInterfaceContract.ServiceName, wsdlSaveLocation, xmlComment, currWsdlLocation, wsdlData); } /// <summary> /// Generates the WSDL file for a specified <see cref="InterfaceContract"></see>. /// </summary> /// <param name="serviceInterfaceContract"> /// <see cref="InterfaceContract"></see> to use for the WSDL generation. /// </param> /// <param name="xmlComment">XML comment to add to the top of the WSDL file.</param> /// <param name="currWsdlLocation">Path of an existing WSDL file to overwrite with the generated /// WSDL file.</param> /// <returns>The path of the WSDL file generated.</returns> /// <remarks> /// This methods loads the information, it receive in a <see cref="InterfaceContract"></see> to /// a <see cref="System.Web.Services.Description.ServiceDescription"></see> class, which is later /// used to generate the WSDL file. The loading process takes place in several steps. <br></br> /// 1. Load the basic meta data from <see cref="InterfaceContract"></see>.<br></br> /// 2. Load the schema imports in the <see cref="SchemaImports"></see> collection.<br></br> /// 3. Load the messages in <see cref="OperationsCollection"></see>.<br></br> /// 4. Create the WSDL Port Type.<br></br> /// 5. Add each operation and it's corresponding in/out messages to the Port Type.<br></br> /// 6. Create a WSDL Binding section and add OperationBinding for each operation.<br></br> /// 7. Generate the WSDL 'service' tags if required.<br></br> /// 8. Finally write the WSDL to the output string.<br></br> /// /// This method generates <see cref="WsdlGenerationException"></see> exception, if it fails to create the WSDL file. /// If a file is specified to overwrite with the new file, the original file is restored in case of /// a failure. /// </remarks> public static string GenerateWsdlData(InterfaceContract serviceInterfaceContract, string xmlComment, string currWsdlLocation) { System.Web.Services.Description.ServiceDescription desc = null; string serviceAttributeName = ""; string bindingName = ""; string serviceName = ""; string portTypeName = ""; bool isRoundtrip = false; if (currWsdlLocation != null) { isRoundtrip = true; } // Load the existing WSDL if one specified. // TODO:(SB): Shouldn't we be using the existing WsdlLoader class here? if (isRoundtrip) { ResetDescription(serviceInterfaceContract, currWsdlLocation, ref desc, ref serviceAttributeName, ref bindingName, ref serviceName, ref portTypeName); } else { InitializeDescription(serviceInterfaceContract, ref desc, ref serviceAttributeName, ref bindingName, ref serviceName, ref portTypeName); } ConstructMetadata(serviceInterfaceContract, desc, serviceAttributeName); ConstructSchemaImports(serviceInterfaceContract, isRoundtrip, desc); ConstructMessages(serviceInterfaceContract, desc); PortType portType = ConstructPortTypes(serviceInterfaceContract, desc, portTypeName); List<ServiceEndpoint> endpoints = ConstructBindings(serviceInterfaceContract, desc, portTypeName, portType); ConstructServiceElement(serviceInterfaceContract, isRoundtrip, desc, serviceName, portTypeName, endpoints); //Now write the initial wsdl string wsdlData = WriteInitialWsdl(serviceInterfaceContract, xmlComment, desc); //Update the Wsdl with Policy Information // TODO: How do we know that policy information is required? Should it be an option? wsdlData = PolicyWriter.UpdateWsdlWithPolicyInfo(wsdlData, endpoints, portTypeName); // Now return the fully written Wsdl return wsdlData; } #endregion #region "WSDL Construction - Private methods" private static void ResetDescription(InterfaceContract serviceInterfaceContract, string currWsdlLocation, ref System.Web.Services.Description.ServiceDescription desc, ref string serviceAttributeName, ref string bindingName, ref string serviceName, ref string portTypeName) { desc = System.Web.Services.Description.ServiceDescription.Read(currWsdlLocation); // Read the existing name values. serviceAttributeName = desc.Name; bindingName = desc.Bindings[0].Name; portTypeName = desc.PortTypes[0].Name; // Check whether we have a service element and save it's name for the // future use. if (desc.Services.Count > 0) { serviceName = desc.Services[0].Name; } else { serviceName = serviceInterfaceContract.ServiceName + "Port"; ; } // Check for the place which has the Service name and assign the new value // appropriatly. if (serviceAttributeName != null && serviceAttributeName != "") { serviceAttributeName = serviceInterfaceContract.ServiceName; } else if (serviceName != null && serviceName != "") { // If the user has selected to remove the service element, // use the service name in the attribute by default. if (serviceInterfaceContract.NeedsServiceElement) { serviceName = serviceInterfaceContract.ServiceName; } else { serviceAttributeName = serviceInterfaceContract.ServiceName; } } else if (bindingName != null && bindingName != "") { bindingName = serviceInterfaceContract.ServiceName; } // Clear the service description. But do not clear the types definitions. desc.Extensions.Clear(); desc.Bindings.Clear(); desc.Documentation = ""; desc.Imports.Clear(); desc.Messages.Clear(); desc.PortTypes.Clear(); desc.RetrievalUrl = ""; if (desc.ServiceDescriptions != null) { desc.ServiceDescriptions.Clear(); } if (!serviceInterfaceContract.NeedsServiceElement) { desc.Services.Clear(); } } private static void InitializeDescription(InterfaceContract serviceInterfaceContract, ref System.Web.Services.Description.ServiceDescription desc, ref string serviceAttributeName, ref string bindingName, ref string serviceName, ref string portTypeName) { desc = new System.Web.Services.Description.ServiceDescription(); // Create the default names. serviceAttributeName = serviceInterfaceContract.ServiceName; bindingName = serviceInterfaceContract.ServiceName; portTypeName = serviceInterfaceContract.ServiceName + "Interface"; serviceName = serviceInterfaceContract.ServiceName + "Port"; } private static void ConstructMetadata(InterfaceContract serviceInterfaceContract, System.Web.Services.Description.ServiceDescription desc, string serviceAttributeName) { if (serviceAttributeName != null && serviceAttributeName != "") { desc.Name = serviceAttributeName; } desc.TargetNamespace = serviceInterfaceContract.ServiceNamespace; desc.Documentation = serviceInterfaceContract.ServiceDocumentation; } private static void ConstructSchemaImports(InterfaceContract serviceInterfaceContract, bool isRoundTrip, System.Web.Services.Description.ServiceDescription desc) { XmlSchema typesSchema = null; // Are we round-tripping? Then we have to access the existing types // section. // Otherwise we just initialize a new XmlSchema for types. if (isRoundTrip) { typesSchema = desc.Types.Schemas[desc.TargetNamespace]; // if we don't have a types section belonging to the same namespace as service description // we take the first types section available. if (typesSchema == null) { typesSchema = desc.Types.Schemas[0]; } // Remove the includes. We gonna re-add them later in this operation. typesSchema.Includes.Clear(); } else { typesSchema = new XmlSchema(); } // Add imports to the types section resolved above. foreach (SchemaImport import in serviceInterfaceContract.Imports) { XmlSchemaExternal importedSchema = null; if (import.SchemaNamespace == null || import.SchemaNamespace == "") { importedSchema = new XmlSchemaInclude(); } else { importedSchema = new XmlSchemaImport(); ((XmlSchemaImport)importedSchema).Namespace = import.SchemaNamespace; } if (serviceInterfaceContract.UseAlternateLocationForImports) { importedSchema.SchemaLocation = import.AlternateLocation; } else { importedSchema.SchemaLocation = import.SchemaLocation; } typesSchema.Includes.Add(importedSchema); } // If we are not round-tripping we have to link the types schema we just created to // the service description. if (!isRoundTrip) { // Finally add the type schema to the ServiceDescription.Types.Schemas collection. desc.Types.Schemas.Add(typesSchema); } } private static void ConstructMessages(InterfaceContract serviceInterfaceContract, System.Web.Services.Description.ServiceDescription desc) { MessageCollection msgs = desc.Messages; foreach (Operation op in serviceInterfaceContract.Operations) { foreach (Message msg in op.MessagesCollection) { FxMessage tempMsg = new FxMessage(); tempMsg.Name = msg.Name; tempMsg.Documentation = msg.Documentation; MessagePart msgPart = new MessagePart(); msgPart.Name = Constants.DefaultMessagePartName; msgPart.Element = new XmlQualifiedName(msg.Element.ElementName, msg.Element.ElementNamespace); tempMsg.Parts.Add(msgPart); msgs.Add(tempMsg); } } } private static PortType ConstructPortTypes(InterfaceContract serviceInterfaceContract, System.Web.Services.Description.ServiceDescription desc, string portTypeName) { PortTypeCollection portTypes = desc.PortTypes; PortType portType = new PortType(); portType.Name = portTypeName; portType.Documentation = serviceInterfaceContract.ServiceDocumentation; // Add each operation and it's corresponding in/out messages to the WSDL Port Type. foreach (Operation op in serviceInterfaceContract.Operations) { FxOperation tempOperation = new FxOperation(); tempOperation.Name = op.Name; tempOperation.Documentation = op.Documentation; int i = 0; OperationInput operationInput = new OperationInput(); operationInput.Message = new XmlQualifiedName(op.MessagesCollection[i].Name, desc.TargetNamespace); tempOperation.Messages.Add(operationInput); if (op.Mep == Mep.RequestResponse) { OperationOutput operationOutput = new OperationOutput(); operationOutput.Message = new XmlQualifiedName(op.MessagesCollection[i + 1].Name, desc.TargetNamespace); tempOperation.Messages.Add(operationOutput); } portType.Operations.Add(tempOperation); i++; } portTypes.Add(portType); return portType; } private static List<ServiceEndpoint> ConstructBindings(InterfaceContract serviceInterfaceContract, System.Web.Services.Description.ServiceDescription desc, string portTypeName, PortType portType) { // Here we have a list of WCF endpoints. // Currently we populate this list with only two endpoints that has default // BasicHttpBinding and default NetTcpBinding. List<ServiceEndpoint> endpoints = new List<ServiceEndpoint>(); BasicHttpBinding basicHttpBinding = new BasicHttpBinding(); endpoints.Add(ServiceEndpointFactory<IDummyContract>.CreateServiceEndpoint(basicHttpBinding)); // BDS (10/22/2007): Commented out the TCP binding generation as we are not going to support this feature // in this version. //NetTcpBinding netTcpBinding = new NetTcpBinding(); //endpoints.Add(ServiceEndpointFactory<IDummyContract>.CreateServiceEndpoint(netTcpBinding)); // Now, for each endpoint we have to create a binding in our service description. foreach (ServiceEndpoint endpoint in endpoints) { // Create a WSDL BindingCollection. BindingCollection bindings = desc.Bindings; System.Web.Services.Description.Binding binding = new System.Web.Services.Description.Binding(); binding.Name = endpoint.Name.Replace(Constants.InternalContractName, portTypeName); binding.Type = new XmlQualifiedName(portType.Name, desc.TargetNamespace); // Create Operation binding for each operation and add it the the BindingCollection. foreach (Operation op in serviceInterfaceContract.Operations) { // SOAP 1.1 Operation bindings. OperationBinding operationBinding1 = new OperationBinding(); operationBinding1.Name = op.Name; InputBinding inputBinding1 = new InputBinding(); object bodyBindingExtension = GetSoapBodyBinding(endpoint.Binding); if (bodyBindingExtension != null) { inputBinding1.Extensions.Add(bodyBindingExtension); } operationBinding1.Input = inputBinding1; // Input message. // Look up the message headers for each Message and add them to the current binding. foreach (MessageHeader inHeader in op.MessagesCollection[0].HeadersCollection) { object headerBindingExtension = GetSoapHeaderBinding(endpoint.Binding, inHeader.Message, desc.TargetNamespace); if (headerBindingExtension != null) { inputBinding1.Extensions.Add(headerBindingExtension); } } if (op.Mep == Mep.RequestResponse) { // Output message. OutputBinding outputBinding1 = new OutputBinding(); object responseBodyBindingExtension = GetSoapBodyBinding(endpoint.Binding); if (responseBodyBindingExtension != null) { outputBinding1.Extensions.Add(responseBodyBindingExtension); } operationBinding1.Output = outputBinding1; // Look up the message headers for each Message and add them to the current binding. foreach (MessageHeader outHeader in op.MessagesCollection[1].HeadersCollection) { object headerBindingExtension = GetSoapHeaderBinding(endpoint.Binding, outHeader.Message, desc.TargetNamespace); if (headerBindingExtension != null) { outputBinding1.Extensions.Add(headerBindingExtension); } } } string action = desc.TargetNamespace + ":" + op.Input.Name; object operationBindingExtension = GetSoapOperationBinding(endpoint.Binding, action); if (operationBindingExtension != null) { operationBinding1.Extensions.Add(operationBindingExtension); } binding.Operations.Add(operationBinding1); // End of SOAP 1.1 operation bindings. } object soapBindingExtension = GetSoapBinding(endpoint.Binding); if (soapBindingExtension != null) { binding.Extensions.Add(soapBindingExtension); } bindings.Add(binding); } return endpoints; } private static void ConstructServiceElement(InterfaceContract serviceInterfaceContract, bool isRoundTrip, System.Web.Services.Description.ServiceDescription desc, string serviceName, string portTypeName, List<ServiceEndpoint> endpoints) { // Generate <service> element optionally - sometimes necessary for interop reasons if (serviceInterfaceContract.NeedsServiceElement) { Service defaultService = null; if (isRoundTrip || desc.Services.Count == 0) { // Create a new service element. defaultService = new Service(); defaultService.Name = serviceName; foreach (ServiceEndpoint endpoint in endpoints) { if (endpoint.Binding.MessageVersion.Envelope == EnvelopeVersion.Soap11) { Port defaultPort = new Port(); defaultPort.Name = serviceInterfaceContract.ServiceName + "Port"; defaultPort.Binding = new XmlQualifiedName(endpoint.Name.Replace(Constants.InternalContractName, portTypeName), desc.TargetNamespace); SoapAddressBinding defaultSoapAddressBinding = new SoapAddressBinding(); defaultSoapAddressBinding.Location = GetDefaultEndpoint(endpoint.Binding, serviceInterfaceContract.ServiceName); defaultPort.Extensions.Add(defaultSoapAddressBinding); defaultService.Ports.Add(defaultPort); } else if (endpoint.Binding.MessageVersion.Envelope == EnvelopeVersion.Soap12) { Port soap12Port = new Port(); soap12Port.Name = serviceInterfaceContract.ServiceName + "SOAP12Port"; soap12Port.Binding = new XmlQualifiedName(endpoint.Name.Replace(Constants.InternalContractName, portTypeName), desc.TargetNamespace); Soap12AddressBinding soap12AddressBinding = new Soap12AddressBinding(); soap12AddressBinding.Location = GetDefaultEndpoint(endpoint.Binding, serviceInterfaceContract.ServiceName); soap12Port.Extensions.Add(soap12AddressBinding); defaultService.Ports.Add(soap12Port); } } desc.Services.Add(defaultService); } else { defaultService = desc.Services[0]; defaultService.Name = serviceName; } } } private static string WriteInitialWsdl(InterfaceContract serviceInterfaceContract, string xmlComment,System.Web.Services.Description.ServiceDescription desc) { MemoryStream outputStream = new MemoryStream(); StreamWriter writer1 = new StreamWriter(outputStream); try { XmlTextWriter writer11 = new XmlTextWriter(writer1); writer11.Formatting = Formatting.Indented; writer11.Indentation = 2; writer11.WriteComment(xmlComment); // BDS: Added a new comment line with the date time of WSDL file. CultureInfo ci = new CultureInfo("en-US"); writer11.WriteComment(DateTime.Now.ToString("dddd", ci) + ", " + DateTime.Now.ToString("dd-MM-yyyy - hh:mm tt", ci)); XmlSerializer serializer1 = System.Web.Services.Description.ServiceDescription.Serializer; XmlSerializerNamespaces nsSer = new XmlSerializerNamespaces(); nsSer.Add("soap", "http://schemas.xmlsoap.org/wsdl/soap/"); nsSer.Add("soap12", "http://schemas.xmlsoap.org/wsdl/soap12/"); nsSer.Add("xsd", "http://www.w3.org/2001/XMLSchema"); nsSer.Add("tns", desc.TargetNamespace); // Add the imported namespaces to the WSDL <description> element. for (int importIndex = 0; importIndex < serviceInterfaceContract.Imports.Count; importIndex++) { if (serviceInterfaceContract.Imports[importIndex].SchemaNamespace != null && serviceInterfaceContract.Imports[importIndex].SchemaNamespace != "") { nsSer.Add("import" + importIndex.ToString(), serviceInterfaceContract.Imports[importIndex].SchemaNamespace); } } // Finally write the file to the output stram. serializer1.Serialize(writer11, desc, nsSer); // Close the stream //writer1.Close(); // Now write the stream into a string outputStream.Seek(0, SeekOrigin.Begin); StreamReader sr = new StreamReader(outputStream); string wsdlData = sr.ReadToEnd(); //sr.Close(); writer1.Close(); return wsdlData; } catch (Exception ex) { writer1.Close(); string message = ex.Message; if (ex.InnerException != null) { message += ex.InnerException.Message; } throw new WsdlGenerationException(message, ex); } } private static string PersistWsdl(string serviceName, string wsdlSaveLocation, string xmlComment, string currWsdlLocation, string wsdlData) { // Generate the WSDL file. string fileName = string.Empty; string bkFileName = string.Empty; // Overwrite the existing file if one specified. if (currWsdlLocation == null) { fileName = wsdlSaveLocation + @"\" + serviceName + ".wsdl"; } else { fileName = currWsdlLocation; } // Backup existing file before proceeding. if (File.Exists(fileName)) { bkFileName = BackupExistingFile(fileName); } try { File.WriteAllText(fileName, wsdlData); if (bkFileName != string.Empty) { File.Delete(bkFileName); } } catch (Exception ex) { string message = ex.Message; if (ex.InnerException != null) { message += ex.InnerException.Message; } // Restore the original file. if (bkFileName != string.Empty) { RestoreFile(fileName, bkFileName, message); } else if (File.Exists(fileName)) { File.Delete(fileName); } throw new WsdlGenerationException( message, ex); } // return the path to the wsdl file return fileName; } private static void RestoreFile(string fileName, string bkFileName, string message) { try { File.Copy(bkFileName, fileName, true); File.Delete(bkFileName); } catch { throw new WsdlGenerationException( message + "\nFailed to restore the original file."); } } private static string BackupExistingFile(string fileName) { string bkFileName = String.Empty; int index = 1; // Create the backup file name. // See whether the generated backup file name is already taken by an existing file and // generate a new file name. while (File.Exists(fileName + "." + index.ToString())) { index++; } bkFileName = fileName + "." + index.ToString(); // Backup the file. try { File.Copy(fileName, bkFileName); } catch (Exception ex) { throw new WsdlGenerationException("An error occured while trying to generate a WSDL. Failed to backup the existing WSDL file.", ex); } return bkFileName; } #endregion #region "WSDL Building Helpers" private static object GetSoapBinding(System.ServiceModel.Channels.Binding binding) { if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap11) { SoapBinding soapBinding = new SoapBinding(); soapBinding.Transport = GetTransport(binding); soapBinding.Style = SoapBindingStyle.Document; return soapBinding; } else if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap12) { Soap12Binding soapBinding = new Soap12Binding(); soapBinding.Transport = GetTransport(binding); soapBinding.Style = SoapBindingStyle.Document; return soapBinding; } return null; } private static object GetSoapOperationBinding(System.ServiceModel.Channels.Binding binding, string action) { if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap11) { SoapOperationBinding soapOperationBinding = new SoapOperationBinding(); soapOperationBinding.SoapAction = action; soapOperationBinding.Style = SoapBindingStyle.Document; return soapOperationBinding; } else if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap12) { Soap12OperationBinding soapOperationBinding = new Soap12OperationBinding(); soapOperationBinding.SoapAction = action; soapOperationBinding.Style = SoapBindingStyle.Document; return soapOperationBinding; } return null; } private static object GetSoapHeaderBinding(System.ServiceModel.Channels.Binding binding, string message, string ns) { if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap11) { SoapHeaderBinding headerBinding = new SoapHeaderBinding(); headerBinding.Use = SoapBindingUse.Literal; headerBinding.Message = new XmlQualifiedName(message, ns); headerBinding.Part = Constants.DefaultMessagePartName; return headerBinding; } else if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap12) { Soap12HeaderBinding headerBinding = new Soap12HeaderBinding(); headerBinding.Use = SoapBindingUse.Literal; headerBinding.Message = new XmlQualifiedName(message, ns); headerBinding.Part = Constants.DefaultMessagePartName; return headerBinding; } return null; } private static object GetSoapBodyBinding(System.ServiceModel.Channels.Binding binding) { if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap11) { SoapBodyBinding soapBinding = new SoapBodyBinding(); soapBinding.Use = SoapBindingUse.Literal; return soapBinding; } else if (binding.MessageVersion.Envelope == EnvelopeVersion.Soap12) { Soap12BodyBinding soap12Binding = new Soap12BodyBinding(); soap12Binding.Use = SoapBindingUse.Literal; return soap12Binding; } return null; } private static string GetTransport(System.ServiceModel.Channels.Binding binding) { TransportBindingElement transport = binding.CreateBindingElements().Find<TransportBindingElement>(); if (transport != null) { if (typeof(HttpTransportBindingElement) == transport.GetType()) { return "http://schemas.xmlsoap.org/soap/http"; } if (typeof(HttpsTransportBindingElement) == transport.GetType()) { return "http://schemas.xmlsoap.org/soap/https"; } if (typeof(TcpTransportBindingElement) == transport.GetType()) { return "http://schemas.microsoft.com/soap/tcp"; } if (typeof(NamedPipeTransportBindingElement) == transport.GetType()) { return "http://schemas.microsoft.com/soap/named-pipe"; } if (typeof(MsmqTransportBindingElement) == transport.GetType()) { return "http://schemas.microsoft.com/soap/msmq"; } } return ""; } private static string GetDefaultEndpoint(System.ServiceModel.Channels.Binding binding, string serviceName) { TransportBindingElement transport = binding.CreateBindingElements().Find<TransportBindingElement>(); if (transport != null) { if (typeof(HttpTransportBindingElement) == transport.GetType()) { UriBuilder ub = new UriBuilder(transport.Scheme, "localhost"); ub.Path = serviceName; return ub.Uri.ToString(); } if (typeof(HttpsTransportBindingElement) == transport.GetType()) { UriBuilder ub = new UriBuilder(transport.Scheme, "localhost"); ub.Path = serviceName; return ub.Uri.ToString(); } if (typeof(TcpTransportBindingElement) == transport.GetType()) { UriBuilder ub = new UriBuilder(transport.Scheme, "localhost"); ub.Path = serviceName; return ub.Uri.ToString(); } if (typeof(NamedPipeTransportBindingElement) == transport.GetType()) { return "tbd"; } if (typeof(MsmqTransportBindingElement) == transport.GetType()) { return "tbd"; } } return ""; } #endregion #region "utility methods" #endregion #endregion #region "Public static method to load WSDL" /// <summary> /// Creates an <see cref="InterfaceContract"/> object by loading the contents in a specified /// WSDL file. /// </summary> /// <param name="wsdlFileName">Path of the WSDL file to load the information from.</param> /// <returns>An instance of <see cref="InterfaceContract"/> with the information loaded from the WSDL file.</returns> /// <remarks> /// This method first loads the content of the WSDL file to an instance of /// <see cref="System.Web.Services.Description.ServiceDescription"/> class. Then it creates an /// instance of <see cref="InterfaceContract"/> class by loading the data from that. /// This method throws <see cref="WsdlLoadException"/> in case of a failure to load the WSDL file. /// </remarks> public static InterfaceContract GetInterfaceContract(string wsdlFileName) { return WsdlLoader.GetInterfaceContract(wsdlFileName); } #endregion #region "Public methods to handle interface contract" #endregion } }
using System; using System.Collections.Generic; using Eto.Forms; using System.Diagnostics; using sw = Windows.UI.Xaml; using wf = Windows.Foundation; using swm = Windows.UI.Xaml.Media; using wuc = Windows.UI.Core; using System.Threading; namespace Eto.WinRT.Forms { /// <summary> /// Application handler. /// </summary> /// <copyright>(c) 2014 by Vivek Jhaveri</copyright> /// <copyright>(c) 2012-2014 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class ApplicationHandler : WidgetHandler<sw.Application, Application, Application.ICallback>, Application.IHandler { wuc.CoreDispatcher dispatcher; bool attached; //bool shutdown; string badgeLabel; static ApplicationHandler instance; List<sw.Window> delayShownWindows; public static ApplicationHandler Instance { get { return instance; } } public static bool EnableVisualStyles = true; public static void InvokeIfNecessary(Action action) { #if TODO_XAML if (sw.Application.Current == null || Thread.CurrentThread == sw.Application.Current.Dispatcher.Thread) action(); else { sw.Application.Current.Dispatcher.Invoke(action); } #else throw new NotImplementedException(); #endif } public List<sw.Window> DelayShownWindows { get { if (delayShownWindows == null) delayShownWindows = new List<sw.Window>(); return delayShownWindows; } } public bool IsStarted { get; private set; } protected override void Initialize() { base.Initialize(); instance = this; #if TODO_XAML Control.Startup += HandleStartup; #endif } #if TODO_XAML void HandleStartup(object sender, sw.StartupEventArgs e) { IsActive = true; IsStarted = true; Control.Activated += (sender2, e2) => IsActive = true; Control.Deactivated += (sender2, e2) => IsActive = false; if (delayShownWindows != null) { foreach (var window in delayShownWindows) { window.Show(); } delayShownWindows = null; } } #endif public bool IsActive { get; private set; } public string BadgeLabel { get { return badgeLabel; } set { badgeLabel = value; #if TODO_XAML var mainWindow = sw.Application.Current.MainWindow; if (mainWindow != null) { if (mainWindow.TaskbarItemInfo == null) mainWindow.TaskbarItemInfo = new sw.Shell.TaskbarItemInfo(); if (!string.IsNullOrEmpty(badgeLabel)) { var ctl = new CustomControls.OverlayIcon(); ctl.Content = badgeLabel; ctl.Measure(new wf.Size(16, 16)); var size = ctl.DesiredSize; var m = sw.PresentationSource.FromVisual(mainWindow).CompositionTarget.TransformToDevice; var bmp = new swm.Imaging.RenderTargetBitmap((int)size.Width, (int)size.Height, m.M22 * 96, m.M22 * 96, swm.PixelFormats.Default); ctl.Arrange(new wf.Rect(size)); bmp.Render(ctl); mainWindow.TaskbarItemInfo.Overlay = bmp; } else mainWindow.TaskbarItemInfo.Overlay = null; } #endif } } public void RunIteration() { } public void Quit() { #if TODO_XAML bool cancel = false; foreach (sw.Window window in Control.Windows) { window.Close(); cancel |= window.IsVisible; } if (!cancel) { Control.Shutdown(); shutdown = true; } #endif } public bool QuitIsSupported { get { return false; } } public void Invoke(Action action) { var ev = new ManualResetEvent(false); #pragma warning disable 4014 dispatcher.RunAsync(wuc.CoreDispatcherPriority.Normal, () => { try { action(); } finally { ev.Set(); } }); #pragma warning restore 4014 ev.WaitOne(); } public void AsyncInvoke(Action action) { #pragma warning disable 4014 dispatcher.RunAsync(wuc.CoreDispatcherPriority.Normal, () => action()); #pragma warning restore 4014 } public Keys CommonModifier { get { return Keys.Control; } } public Keys AlternateModifier { get { return Keys.Alt; } } public void Open(string url) { #if TODO_XAML Process.Start(url); #else throw new NotImplementedException(); #endif } public void Run() { dispatcher = wuc.CoreWindow.GetForCurrentThread().Dispatcher; Callback.OnInitialized(Widget, EventArgs.Empty); if (!attached) { //if (shutdown) return; if (Widget.MainForm != null) { #if TODO_XAML Control.Run((Windows.UI.Xaml.Window)Widget.MainForm.ControlObject); #else throw new NotImplementedException(); #endif } else { #if TODO_XAML Control.ShutdownMode = sw.ShutdownMode.OnExplicitShutdown; Control.Run(); #else throw new NotImplementedException(); #endif } } } public void Attach(object context) { attached = true; Control = sw.Application.Current; } public void OnMainFormChanged() { } public void Restart() { #if TODO_XAML Process.Start(Windows.UI.Xaml.Application.ResourceAssembly.Location); Windows.UI.Xaml.Application.Current.Shutdown(); #else throw new NotImplementedException(); #endif } public override void AttachEvent(string id) { switch (id) { case Application.TerminatingEvent: // handled by WpfWindow break; default: base.AttachEvent(id); break; } } } }
// <license> // The MIT License (MIT) // </license> // <copyright company="TTRider Technologies, Inc."> // Copyright (c) 2014-2017 All Rights Reserved // </copyright> using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace TTRider.FluidSql { public class Name : ExpressionToken , IList<string> { private static readonly Regex ParseName = new Regex( @"(\[(?<name>[^\]]*)]\.?)|(\`(?<name>[^\`]*)`\.?)|(\""(?<name>[^\""]*)""\.?)|((?<name>[^\.]*)\.?)", RegexOptions.Compiled); private readonly List<string> parts = new List<string>(); private readonly HashSet<string> noQuotes = new HashSet<string>(new[] { "*" }, StringComparer.OrdinalIgnoreCase); public Name() { } public Name(params string[] names) { this.Add(names); } public Name(string name1, Name name2) { this.Add(name1, name2); } public Name(string name1, string name2, Name name3) { this.Add(name1, name2, name3); } public Name(string name1, string name2, string name3, Name name4) { this.Add(name1, name2, name3, name4); } public Name(Name name, params string[] names) { this.Add(name, names); } public Name(IEnumerable<string> names) { this.Add(names); } public string LastPart => this.parts.LastOrDefault(); public string FirstPart => this.parts.FirstOrDefault(); public string CatalogName => this.parts.Count < 3 ? null : this.parts[this.parts.Count - 3]; public string SchemaName => this.parts.Count < 2 ? null : this.parts[this.parts.Count - 2]; public string ObjectName => LastPart; static IEnumerable<string> GetParts(string name) { if (string.IsNullOrWhiteSpace(name)) { yield return string.Empty; yield break; } var match = ParseName.Match(name); while (match.Success) { if (match.Length > 0) { yield return match.Groups["name"].Value; } match = match.NextMatch(); } } public Name As(string alias) { if (!string.IsNullOrWhiteSpace(alias)) { return new Name(this.parts) { Alias = alias }; } return this; } public Name NoQuotes(string noQuotesName) { this.noQuotes.Add(noQuotesName); return this; } public string GetFullName(string openQuote = null, string closeQuote = null) { openQuote = string.IsNullOrWhiteSpace(openQuote) ? "\"" : openQuote.Trim(); closeQuote = string.IsNullOrWhiteSpace(closeQuote) ? openQuote : closeQuote.Trim(); return string.Join(".", this.parts .Select( item => string.IsNullOrWhiteSpace(item) || string.Equals(item, "*") || item.TrimStart().StartsWith("@") || this.noQuotes.Contains(item) ? item : openQuote + item + closeQuote)); } public string GetFullNameWithoutQuotes() { return string.Join(".", this.parts); } public static implicit operator Name(string value) { return new Name(value); } #region IList public IEnumerator<string> GetEnumerator() { return this.parts.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(string item) { this.parts.AddRange(GetParts(item)); } public void Add(params string[] names) { this.parts.AddRange(names.SelectMany(GetParts)); } public void Add(string name1, Name name2) { this.parts.AddRange(GetParts(name1)); this.parts.AddRange(name2.parts); } public void Add(string name1, string name2, Name name3) { this.parts.AddRange(GetParts(name1)); this.parts.AddRange(GetParts(name2)); this.parts.AddRange(name3.parts); } public void Add(string name1, string name2, string name3, Name name4) { this.parts.AddRange(GetParts(name1)); this.parts.AddRange(GetParts(name2)); this.parts.AddRange(GetParts(name3)); this.parts.AddRange(name4.parts); } public void Add(Name name, params string[] names) { this.parts.AddRange(name.parts); this.parts.AddRange(names.SelectMany(GetParts)); } public void Add(IEnumerable<string> names) { if (names != null) { this.parts.AddRange(names.SelectMany(GetParts)); } } public void Clear() { this.parts.Clear(); } public bool Contains(string item) { return this.parts.Contains(item); } public void CopyTo(string[] array, int arrayIndex) { this.parts.CopyTo(array, arrayIndex); } public bool Remove(string item) { return this.parts.Remove(item); } public int Count => this.parts.Count; public bool IsReadOnly => false; public int IndexOf(string item) { return this.parts.IndexOf(item); } public void Insert(int index, string item) { this.parts.Insert(index, item); } public void RemoveAt(int index) { this.parts.RemoveAt(index); } public string this[int index] { get { return this.parts[index]; } set { this.parts[index] = value; } } #endregion IList } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Registry { using System; using System.Collections.Generic; using System.Security.AccessControl; using System.Text; /// <summary> /// A key within a registry hive. /// </summary> public sealed class RegistryKey { private RegistryHive _hive; private KeyNodeCell _cell; internal RegistryKey(RegistryHive hive, KeyNodeCell cell) { _hive = hive; _cell = cell; } /// <summary> /// Gets the name of this key. /// </summary> public string Name { get { RegistryKey parent = Parent; if (parent != null && ((parent.Flags & RegistryKeyFlags.Root) == 0)) { return parent.Name + @"\" + _cell.Name; } else { return _cell.Name; } } } /// <summary> /// Gets the number of child keys. /// </summary> public int SubKeyCount { get { return _cell.NumSubKeys; } } /// <summary> /// Gets the number of values in this key. /// </summary> public int ValueCount { get { return _cell.NumValues; } } /// <summary> /// Gets the time the key was last modified. /// </summary> public DateTime Timestamp { get { return _cell.Timestamp; } } /// <summary> /// Gets the parent key, or <c>null</c> if this is the root key. /// </summary> public RegistryKey Parent { get { if ((_cell.Flags & RegistryKeyFlags.Root) == 0) { return new RegistryKey(_hive, _hive.GetCell<KeyNodeCell>(_cell.ParentIndex)); } else { return null; } } } /// <summary> /// Gets the flags of this registry key. /// </summary> public RegistryKeyFlags Flags { get { return _cell.Flags; } } /// <summary> /// Gets the class name of this registry key. /// </summary> /// <remarks>Class name is rarely used.</remarks> public string ClassName { get { if (_cell.ClassNameIndex > 0) { return Encoding.Unicode.GetString(_hive.RawCellData(_cell.ClassNameIndex, _cell.ClassNameLength)); } return null; } } /// <summary> /// Gets an enumerator over all sub child keys. /// </summary> public IEnumerable<RegistryKey> SubKeys { get { if (_cell.NumSubKeys != 0) { ListCell list = _hive.GetCell<ListCell>(_cell.SubKeysIndex); foreach (var key in list.EnumerateKeys()) { yield return new RegistryKey(_hive, key); } } } } /// <summary> /// Gets an enumerator over all values in this key. /// </summary> private IEnumerable<RegistryValue> Values { get { if (_cell.NumValues != 0) { byte[] valueList = _hive.RawCellData(_cell.ValueListIndex, _cell.NumValues * 4); for (int i = 0; i < _cell.NumValues; ++i) { int valueIndex = Utilities.ToInt32LittleEndian(valueList, i * 4); yield return new RegistryValue(_hive, _hive.GetCell<ValueCell>(valueIndex)); } } } } /// <summary> /// Gets the Security Descriptor applied to the registry key. /// </summary> /// <returns>The security descriptor as a RegistrySecurity instance.</returns> public RegistrySecurity GetAccessControl() { if (_cell.SecurityIndex > 0) { SecurityCell secCell = _hive.GetCell<SecurityCell>(_cell.SecurityIndex); return secCell.SecurityDescriptor; } return null; } /// <summary> /// Gets the names of all child sub keys. /// </summary> /// <returns>The names of the sub keys</returns> public string[] GetSubKeyNames() { List<string> names = new List<string>(); if (_cell.NumSubKeys != 0) { _hive.GetCell<ListCell>(_cell.SubKeysIndex).EnumerateKeys(names); } return names.ToArray(); } /// <summary> /// Gets a named value stored within this key. /// </summary> /// <param name="name">The name of the value to retrieve</param> /// <returns>The value as a .NET object.</returns> /// <remarks>The mapping from registry type of .NET type is as follows: /// <list type="table"> /// <listheader> /// <term>Value Type</term> /// <term>.NET type</term> /// </listheader> /// <item> /// <description>String</description> /// <description>string</description> /// </item> /// <item> /// <description>ExpandString</description> /// <description>string</description> /// </item> /// <item> /// <description>Link</description> /// <description>string</description> /// </item> /// <item> /// <description>DWord</description> /// <description>uint</description> /// </item> /// <item> /// <description>DWordBigEndian</description> /// <description>uint</description> /// </item> /// <item> /// <description>MultiString</description> /// <description>string[]</description> /// </item> /// <item> /// <description>QWord</description> /// <description>ulong</description> /// </item> /// </list> /// </remarks> public object GetValue(string name) { return GetValue(name, null, Microsoft.Win32.RegistryValueOptions.None); } /// <summary> /// Gets a named value stored within this key. /// </summary> /// <param name="name">The name of the value to retrieve.</param> /// <param name="defaultValue">The default value to return, if no existing value is stored.</param> /// <returns>The value as a .NET object.</returns> /// <remarks>The mapping from registry type of .NET type is as follows: /// <list type="table"> /// <listheader> /// <term>Value Type</term> /// <term>.NET type</term> /// </listheader> /// <item> /// <description>String</description> /// <description>string</description> /// </item> /// <item> /// <description>ExpandString</description> /// <description>string</description> /// </item> /// <item> /// <description>Link</description> /// <description>string</description> /// </item> /// <item> /// <description>DWord</description> /// <description>uint</description> /// </item> /// <item> /// <description>DWordBigEndian</description> /// <description>uint</description> /// </item> /// <item> /// <description>MultiString</description> /// <description>string[]</description> /// </item> /// <item> /// <description>QWord</description> /// <description>ulong</description> /// </item> /// </list> /// </remarks> public object GetValue(string name, object defaultValue) { return GetValue(name, defaultValue, Microsoft.Win32.RegistryValueOptions.None); } /// <summary> /// Gets a named value stored within this key. /// </summary> /// <param name="name">The name of the value to retrieve.</param> /// <param name="defaultValue">The default value to return, if no existing value is stored.</param> /// <param name="options">Flags controlling how the value is processed before it's returned.</param> /// <returns>The value as a .NET object.</returns> /// <remarks>The mapping from registry type of .NET type is as follows: /// <list type="table"> /// <listheader> /// <term>Value Type</term> /// <term>.NET type</term> /// </listheader> /// <item> /// <description>String</description> /// <description>string</description> /// </item> /// <item> /// <description>ExpandString</description> /// <description>string</description> /// </item> /// <item> /// <description>Link</description> /// <description>string</description> /// </item> /// <item> /// <description>DWord</description> /// <description>uint</description> /// </item> /// <item> /// <description>DWordBigEndian</description> /// <description>uint</description> /// </item> /// <item> /// <description>MultiString</description> /// <description>string[]</description> /// </item> /// <item> /// <description>QWord</description> /// <description>ulong</description> /// </item> /// </list> /// </remarks> public object GetValue(string name, object defaultValue, Microsoft.Win32.RegistryValueOptions options) { RegistryValue regVal = GetRegistryValue(name); if (regVal != null) { if (regVal.DataType == RegistryValueType.ExpandString && (options & Microsoft.Win32.RegistryValueOptions.DoNotExpandEnvironmentNames) == 0) { return Environment.ExpandEnvironmentVariables((string)regVal.Value); } else { return regVal.Value; } } return defaultValue; } /// <summary> /// Sets a named value stored within this key. /// </summary> /// <param name="name">The name of the value to store.</param> /// <param name="value">The value to store.</param> public void SetValue(string name, object value) { SetValue(name, value, RegistryValueType.None); } /// <summary> /// Sets a named value stored within this key. /// </summary> /// <param name="name">The name of the value to store.</param> /// <param name="value">The value to store.</param> /// <param name="valueType">The registry type of the data</param> public void SetValue(string name, object value, RegistryValueType valueType) { RegistryValue valObj = GetRegistryValue(name); if (valObj == null) { valObj = AddRegistryValue(name); } valObj.SetValue(value, valueType); } /// <summary> /// Deletes a named value stored within this key. /// </summary> /// <param name="name">The name of the value to delete.</param> public void DeleteValue(string name) { DeleteValue(name, true); } /// <summary> /// Deletes a named value stored within this key. /// </summary> /// <param name="name">The name of the value to delete.</param> /// <param name="throwOnMissingValue">Throws ArgumentException if <c>name</c> doesn't exist</param> public void DeleteValue(string name, bool throwOnMissingValue) { bool foundValue = false; if (_cell.NumValues != 0) { byte[] valueList = _hive.RawCellData(_cell.ValueListIndex, _cell.NumValues * 4); int i = 0; while (i < _cell.NumValues) { int valueIndex = Utilities.ToInt32LittleEndian(valueList, i * 4); ValueCell valueCell = _hive.GetCell<ValueCell>(valueIndex); if (string.Compare(valueCell.Name, name, StringComparison.OrdinalIgnoreCase) == 0) { foundValue = true; _hive.FreeCell(valueIndex); _cell.NumValues--; _hive.UpdateCell(_cell, false); break; } ++i; } // Move following value's to fill gap if (i < _cell.NumValues) { while (i < _cell.NumValues) { int valueIndex = Utilities.ToInt32LittleEndian(valueList, (i + 1) * 4); Utilities.WriteBytesLittleEndian(valueIndex, valueList, i * 4); ++i; } _hive.WriteRawCellData(_cell.ValueListIndex, valueList, 0, _cell.NumValues * 4); } // TODO: Update maxbytes for value name and value content if this was the largest value for either. // Windows seems to repair this info, if not accurate, though. } if (throwOnMissingValue && !foundValue) { throw new ArgumentException("No such value: " + name, "name"); } } /// <summary> /// Gets the type of a named value. /// </summary> /// <param name="name">The name of the value to inspect.</param> /// <returns>The value's type.</returns> public RegistryValueType GetValueType(string name) { RegistryValue regVal = GetRegistryValue(name); if (regVal != null) { return regVal.DataType; } return RegistryValueType.None; } /// <summary> /// Gets the names of all values in this key. /// </summary> /// <returns>An array of strings containing the value names</returns> public string[] GetValueNames() { List<string> names = new List<string>(); foreach (var value in Values) { names.Add(value.Name); } return names.ToArray(); } /// <summary> /// Creates or opens a subkey. /// </summary> /// <param name="subkey">The relative path the the subkey</param> /// <returns>The subkey</returns> public RegistryKey CreateSubKey(string subkey) { if (string.IsNullOrEmpty(subkey)) { return this; } string[] split = subkey.Split(new char[] { '\\' }, 2); int cellIndex = FindSubKeyCell(split[0]); if (cellIndex < 0) { KeyNodeCell newKeyCell = new KeyNodeCell(split[0], _cell.Index); newKeyCell.SecurityIndex = _cell.SecurityIndex; ReferenceSecurityCell(newKeyCell.SecurityIndex); _hive.UpdateCell(newKeyCell, true); LinkSubKey(split[0], newKeyCell.Index); if (split.Length == 1) { return new RegistryKey(_hive, newKeyCell); } else { return new RegistryKey(_hive, newKeyCell).CreateSubKey(split[1]); } } else { KeyNodeCell cell = _hive.GetCell<KeyNodeCell>(cellIndex); if (split.Length == 1) { return new RegistryKey(_hive, cell); } else { return new RegistryKey(_hive, cell).CreateSubKey(split[1]); } } } /// <summary> /// Opens a sub key. /// </summary> /// <param name="path">The relative path to the sub key.</param> /// <returns>The sub key, or <c>null</c> if not found.</returns> public RegistryKey OpenSubKey(string path) { if (string.IsNullOrEmpty(path)) { return this; } string[] split = path.Split(new char[] { '\\' }, 2); int cellIndex = FindSubKeyCell(split[0]); if (cellIndex < 0) { return null; } else { KeyNodeCell cell = _hive.GetCell<KeyNodeCell>(cellIndex); if (split.Length == 1) { return new RegistryKey(_hive, cell); } else { return new RegistryKey(_hive, cell).OpenSubKey(split[1]); } } } /// <summary> /// Deletes a subkey and any child subkeys recursively. The string subkey is not case-sensitive. /// </summary> /// <param name="subkey">The subkey to delete</param> public void DeleteSubKeyTree(string subkey) { RegistryKey subKeyObj = OpenSubKey(subkey); if (subKeyObj == null) { return; } if ((subKeyObj.Flags & RegistryKeyFlags.Root) != 0) { throw new ArgumentException("Attempt to delete root key"); } foreach (var child in subKeyObj.GetSubKeyNames()) { subKeyObj.DeleteSubKeyTree(child); } DeleteSubKey(subkey); } /// <summary> /// Deletes the specified subkey. The string subkey is not case-sensitive. /// </summary> /// <param name="subkey">The subkey to delete</param> public void DeleteSubKey(string subkey) { DeleteSubKey(subkey, true); } /// <summary> /// Deletes the specified subkey. The string subkey is not case-sensitive. /// </summary> /// <param name="subkey">The subkey to delete</param> /// <param name="throwOnMissingSubKey"><c>true</c> to throw an argument exception if <c>subkey</c> doesn't exist</param> public void DeleteSubKey(string subkey, bool throwOnMissingSubKey) { if (string.IsNullOrEmpty(subkey)) { throw new ArgumentException("Invalid SubKey", "subkey"); } string[] split = subkey.Split(new char[] { '\\' }, 2); int subkeyCellIndex = FindSubKeyCell(split[0]); if (subkeyCellIndex < 0) { if (throwOnMissingSubKey) { throw new ArgumentException("No such SubKey", "subkey"); } else { return; } } KeyNodeCell subkeyCell = _hive.GetCell<KeyNodeCell>(subkeyCellIndex); if (split.Length == 1) { if (subkeyCell.NumSubKeys != 0) { throw new InvalidOperationException("The registry key has subkeys"); } if (subkeyCell.ClassNameIndex != -1) { _hive.FreeCell(subkeyCell.ClassNameIndex); subkeyCell.ClassNameIndex = -1; subkeyCell.ClassNameLength = 0; } if (subkeyCell.SecurityIndex != -1) { DereferenceSecurityCell(subkeyCell.SecurityIndex); subkeyCell.SecurityIndex = -1; } if (subkeyCell.SubKeysIndex != -1) { FreeSubKeys(subkeyCell); } if (subkeyCell.ValueListIndex != -1) { FreeValues(subkeyCell); } UnlinkSubKey(subkey); _hive.FreeCell(subkeyCellIndex); _hive.UpdateCell(_cell, false); } else { new RegistryKey(_hive, subkeyCell).DeleteSubKey(split[1], throwOnMissingSubKey); } } private RegistryValue GetRegistryValue(string name) { if (name != null && name.Length == 0) { name = null; } if (_cell.NumValues != 0) { byte[] valueList = _hive.RawCellData(_cell.ValueListIndex, _cell.NumValues * 4); for (int i = 0; i < _cell.NumValues; ++i) { int valueIndex = Utilities.ToInt32LittleEndian(valueList, i * 4); ValueCell cell = _hive.GetCell<ValueCell>(valueIndex); if (string.Compare(cell.Name, name, StringComparison.OrdinalIgnoreCase) == 0) { return new RegistryValue(_hive, cell); } } } return null; } private RegistryValue AddRegistryValue(string name) { byte[] valueList = _hive.RawCellData(_cell.ValueListIndex, _cell.NumValues * 4); if (valueList == null) { valueList = new byte[0]; } int insertIdx = 0; while (insertIdx < _cell.NumValues) { int valueCellIndex = Utilities.ToInt32LittleEndian(valueList, insertIdx * 4); ValueCell cell = _hive.GetCell<ValueCell>(valueCellIndex); if (string.Compare(name, cell.Name, StringComparison.OrdinalIgnoreCase) < 0) { break; } ++insertIdx; } // Allocate a new value cell (note _hive.UpdateCell does actual allocation). ValueCell valueCell = new ValueCell(name); _hive.UpdateCell(valueCell, true); // Update the value list, re-allocating if necessary byte[] newValueList = new byte[(_cell.NumValues * 4) + 4]; Array.Copy(valueList, 0, newValueList, 0, insertIdx * 4); Utilities.WriteBytesLittleEndian(valueCell.Index, newValueList, insertIdx * 4); Array.Copy(valueList, insertIdx * 4, newValueList, (insertIdx * 4) + 4, (_cell.NumValues - insertIdx) * 4); if (_cell.ValueListIndex == -1 || !_hive.WriteRawCellData(_cell.ValueListIndex, newValueList, 0, newValueList.Length)) { int newListCellIndex = _hive.AllocateRawCell(Utilities.RoundUp(newValueList.Length, 8)); _hive.WriteRawCellData(newListCellIndex, newValueList, 0, newValueList.Length); if (_cell.ValueListIndex != -1) { _hive.FreeCell(_cell.ValueListIndex); } _cell.ValueListIndex = newListCellIndex; } // Record the new value and save this cell _cell.NumValues++; _hive.UpdateCell(_cell, false); // Finally, set the data in the value cell return new RegistryValue(_hive, valueCell); } private int FindSubKeyCell(string name) { if (_cell.NumSubKeys != 0) { ListCell listCell = _hive.GetCell<ListCell>(_cell.SubKeysIndex); int cellIndex; if (listCell.FindKey(name, out cellIndex) == 0) { return cellIndex; } } return -1; } private void LinkSubKey(string name, int cellIndex) { if (_cell.SubKeysIndex == -1) { SubKeyHashedListCell newListCell = new SubKeyHashedListCell(_hive, "lf"); newListCell.Add(name, cellIndex); _hive.UpdateCell(newListCell, true); _cell.NumSubKeys = 1; _cell.SubKeysIndex = newListCell.Index; } else { ListCell list = _hive.GetCell<ListCell>(_cell.SubKeysIndex); _cell.SubKeysIndex = list.LinkSubKey(name, cellIndex); _cell.NumSubKeys++; } _hive.UpdateCell(_cell, false); } private void UnlinkSubKey(string name) { if (_cell.SubKeysIndex == -1 || _cell.NumSubKeys == 0) { throw new InvalidOperationException("No subkey list"); } ListCell list = _hive.GetCell<ListCell>(_cell.SubKeysIndex); _cell.SubKeysIndex = list.UnlinkSubKey(name); _cell.NumSubKeys--; } private void ReferenceSecurityCell(int cellIndex) { SecurityCell sc = _hive.GetCell<SecurityCell>(cellIndex); sc.UsageCount++; _hive.UpdateCell(sc, false); } private void DereferenceSecurityCell(int cellIndex) { SecurityCell sc = _hive.GetCell<SecurityCell>(cellIndex); sc.UsageCount--; if (sc.UsageCount == 0) { SecurityCell prev = _hive.GetCell<SecurityCell>(sc.PreviousIndex); prev.NextIndex = sc.NextIndex; _hive.UpdateCell(prev, false); SecurityCell next = _hive.GetCell<SecurityCell>(sc.NextIndex); next.PreviousIndex = sc.PreviousIndex; _hive.UpdateCell(next, false); _hive.FreeCell(cellIndex); } else { _hive.UpdateCell(sc, false); } } private void FreeValues(KeyNodeCell cell) { if (cell.NumValues != 0 && cell.ValueListIndex != -1) { byte[] valueList = _hive.RawCellData(cell.ValueListIndex, cell.NumValues * 4); for (int i = 0; i < cell.NumValues; ++i) { int valueIndex = Utilities.ToInt32LittleEndian(valueList, i * 4); _hive.FreeCell(valueIndex); } _hive.FreeCell(cell.ValueListIndex); cell.ValueListIndex = -1; cell.NumValues = 0; cell.MaxValDataBytes = 0; cell.MaxValNameBytes = 0; } } private void FreeSubKeys(KeyNodeCell subkeyCell) { if (subkeyCell.SubKeysIndex == -1) { throw new InvalidOperationException("No subkey list"); } Cell list = _hive.GetCell<Cell>(subkeyCell.SubKeysIndex); SubKeyIndirectListCell indirectList = list as SubKeyIndirectListCell; if (indirectList != null) { ////foreach (int listIndex in indirectList.CellIndexes) for (int i = 0; i < indirectList.CellIndexes.Count; ++i) { int listIndex = indirectList.CellIndexes[i]; _hive.FreeCell(listIndex); } } _hive.FreeCell(list.Index); } } }
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 ICurrencyOriginalData : ISchemaBaseOriginalData { string CurrencyCode { get; } string Name { get; } } public partial class Currency : OGM<Currency, Currency.CurrencyData, System.String>, ISchemaBase, INeo4jBase, ICurrencyOriginalData { #region Initialize static Currency() { 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, Currency> 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.CurrencyAlias, IWhereQuery> query) { q.CurrencyAlias alias; IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.Currency.Alias(out alias)); IWhereQuery partial = query.Invoke(matchQuery, alias); ICompiled compiled = partial.Return(alias).Compile(); RegisterQuery(name, compiled); } public override string ToString() { return $"Currency => CurrencyCode : {this.CurrencyCode}, Name : {this.Name}, 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 CurrencyData(InnerData); } } #endregion #region Validations protected override void ValidateSave() { bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged); #pragma warning disable CS0472 if (InnerData.CurrencyCode == null) throw new PersistenceException(string.Format("Cannot save Currency with key '{0}' because the CurrencyCode cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.Name == null) throw new PersistenceException(string.Format("Cannot save Currency with key '{0}' because the Name cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.ModifiedDate == null) throw new PersistenceException(string.Format("Cannot save Currency 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 CurrencyData : Data<System.String> { public CurrencyData() { } public CurrencyData(CurrencyData data) { CurrencyCode = data.CurrencyCode; Name = data.Name; ModifiedDate = data.ModifiedDate; Uid = data.Uid; } #region Initialize Collections protected override void InitializeCollections() { NodeType = "Currency"; } 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("CurrencyCode", CurrencyCode); dictionary.Add("Name", Name); 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("CurrencyCode", out value)) CurrencyCode = (string)value; if (properties.TryGetValue("Name", out value)) Name = (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 ICurrency public string CurrencyCode { get; set; } public string Name { get; 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 ICurrency public string CurrencyCode { get { LazyGet(); return InnerData.CurrencyCode; } set { if (LazySet(Members.CurrencyCode, InnerData.CurrencyCode, value)) InnerData.CurrencyCode = value; } } public string Name { get { LazyGet(); return InnerData.Name; } set { if (LazySet(Members.Name, InnerData.Name, value)) InnerData.Name = value; } } #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 CurrencyMembers members = null; public static CurrencyMembers Members { get { if (members == null) { lock (typeof(Currency)) { if (members == null) members = new CurrencyMembers(); } } return members; } } public class CurrencyMembers { internal CurrencyMembers() { } #region Members for interface ICurrency public Property CurrencyCode { get; } = Datastore.AdventureWorks.Model.Entities["Currency"].Properties["CurrencyCode"]; public Property Name { get; } = Datastore.AdventureWorks.Model.Entities["Currency"].Properties["Name"]; #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 CurrencyFullTextMembers fullTextMembers = null; public static CurrencyFullTextMembers FullTextMembers { get { if (fullTextMembers == null) { lock (typeof(Currency)) { if (fullTextMembers == null) fullTextMembers = new CurrencyFullTextMembers(); } } return fullTextMembers; } } public class CurrencyFullTextMembers { internal CurrencyFullTextMembers() { } } sealed public override Entity GetEntity() { if (entity == null) { lock (typeof(Currency)) { if (entity == null) entity = Datastore.AdventureWorks.Model.Entities["Currency"]; } } return entity; } private static CurrencyEvents events = null; public static CurrencyEvents Events { get { if (events == null) { lock (typeof(Currency)) { if (events == null) events = new CurrencyEvents(); } } return events; } } public class CurrencyEvents { #region OnNew private bool onNewIsRegistered = false; private EventHandler<Currency, EntityEventArgs> onNew; public event EventHandler<Currency, 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<Currency, EntityEventArgs> handler = onNew; if ((object)handler != null) handler.Invoke((Currency)sender, args); } #endregion #region OnDelete private bool onDeleteIsRegistered = false; private EventHandler<Currency, EntityEventArgs> onDelete; public event EventHandler<Currency, 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<Currency, EntityEventArgs> handler = onDelete; if ((object)handler != null) handler.Invoke((Currency)sender, args); } #endregion #region OnSave private bool onSaveIsRegistered = false; private EventHandler<Currency, EntityEventArgs> onSave; public event EventHandler<Currency, 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<Currency, EntityEventArgs> handler = onSave; if ((object)handler != null) handler.Invoke((Currency)sender, args); } #endregion #region OnPropertyChange public static class OnPropertyChange { #region OnCurrencyCode private static bool onCurrencyCodeIsRegistered = false; private static EventHandler<Currency, PropertyEventArgs> onCurrencyCode; public static event EventHandler<Currency, PropertyEventArgs> OnCurrencyCode { add { lock (typeof(OnPropertyChange)) { if (!onCurrencyCodeIsRegistered) { Members.CurrencyCode.Events.OnChange -= onCurrencyCodeProxy; Members.CurrencyCode.Events.OnChange += onCurrencyCodeProxy; onCurrencyCodeIsRegistered = true; } onCurrencyCode += value; } } remove { lock (typeof(OnPropertyChange)) { onCurrencyCode -= value; if (onCurrencyCode == null && onCurrencyCodeIsRegistered) { Members.CurrencyCode.Events.OnChange -= onCurrencyCodeProxy; onCurrencyCodeIsRegistered = false; } } } } private static void onCurrencyCodeProxy(object sender, PropertyEventArgs args) { EventHandler<Currency, PropertyEventArgs> handler = onCurrencyCode; if ((object)handler != null) handler.Invoke((Currency)sender, args); } #endregion #region OnName private static bool onNameIsRegistered = false; private static EventHandler<Currency, PropertyEventArgs> onName; public static event EventHandler<Currency, PropertyEventArgs> OnName { add { lock (typeof(OnPropertyChange)) { if (!onNameIsRegistered) { Members.Name.Events.OnChange -= onNameProxy; Members.Name.Events.OnChange += onNameProxy; onNameIsRegistered = true; } onName += value; } } remove { lock (typeof(OnPropertyChange)) { onName -= value; if (onName == null && onNameIsRegistered) { Members.Name.Events.OnChange -= onNameProxy; onNameIsRegistered = false; } } } } private static void onNameProxy(object sender, PropertyEventArgs args) { EventHandler<Currency, PropertyEventArgs> handler = onName; if ((object)handler != null) handler.Invoke((Currency)sender, args); } #endregion #region OnModifiedDate private static bool onModifiedDateIsRegistered = false; private static EventHandler<Currency, PropertyEventArgs> onModifiedDate; public static event EventHandler<Currency, 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<Currency, PropertyEventArgs> handler = onModifiedDate; if ((object)handler != null) handler.Invoke((Currency)sender, args); } #endregion #region OnUid private static bool onUidIsRegistered = false; private static EventHandler<Currency, PropertyEventArgs> onUid; public static event EventHandler<Currency, 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<Currency, PropertyEventArgs> handler = onUid; if ((object)handler != null) handler.Invoke((Currency)sender, args); } #endregion } #endregion } #endregion #region ICurrencyOriginalData public ICurrencyOriginalData OriginalVersion { get { return this; } } #region Members for interface ICurrency string ICurrencyOriginalData.CurrencyCode { get { return OriginalData.CurrencyCode; } } string ICurrencyOriginalData.Name { get { return OriginalData.Name; } } #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 } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009, 2013 Oracle and/or its affiliates. All rights reserved. * */ using System; using System.Collections.Generic; using System.Text; using BerkeleyDB.Internal; namespace BerkeleyDB { /// <summary> /// A class representing configuration parameters for /// <see cref="DatabaseEnvironment"/> /// </summary> public class DatabaseEnvironmentConfig { /// <summary> /// Create a new object, with default settings /// </summary> public DatabaseEnvironmentConfig() { DataDirs = new List<string>(); } /// <summary> /// Configuration for the locking subsystem /// </summary> public LockingConfig LockSystemCfg; /// <summary> /// Configuration for the logging subsystem /// </summary> public LogConfig LogSystemCfg; /// <summary> /// Configuration for the memory pool subsystem /// </summary> public MPoolConfig MPoolSystemCfg; /// <summary> /// Configuration for the mutex subsystem /// </summary> public MutexConfig MutexSystemCfg; /// <summary> /// Configuration for the replication subsystem /// </summary> public ReplicationConfig RepSystemCfg; /// <summary> /// The mechanism for reporting detailed error messages to the /// application. /// </summary> /// <remarks> /// <para> /// When an error occurs in the Berkeley DB library, a /// <see cref="DatabaseException"/>, or subclass of DatabaseException, /// is thrown. In some cases, however, the exception may be insufficient /// to completely describe the cause of the error, especially during /// initial application debugging. /// </para> /// <para> /// In some cases, when an error occurs, Berkeley DB will call the given /// delegate with additional error information. It is up to the delegate /// to display the error message in an appropriate manner. /// </para> /// <para> /// Setting ErrorFeedback to NULL unconfigures the callback interface. /// </para> /// <para> /// This error-logging enhancement does not slow performance or /// significantly increase application size, and may be run during /// normal operation as well as during application debugging. /// </para> /// </remarks> public ErrorFeedbackDelegate ErrorFeedback; /// <summary> /// Monitor progress within long running operations. /// </summary> /// <remarks> /// <para> /// Some operations performed by the Berkeley DB library can take /// non-trivial amounts of time. The Feedback delegate can be used by /// applications to monitor progress within these operations. When an /// operation is likely to take a long time, Berkeley DB will call the /// specified delegate with progress information. /// </para> /// <para> /// It is up to the delegate to display this information in an /// appropriate manner. /// </para> /// </remarks> public EnvironmentFeedbackDelegate Feedback; /// <summary> /// A delegate which is called to notify the process of specific /// Berkeley DB events. /// </summary> public EventNotifyDelegate EventNotify; /// <summary> /// A delegate that returns a unique identifier pair for the current /// thread of control. /// </summary> /// <remarks> /// This delegate supports <see cref="DatabaseEnvironment.FailCheck"/>. /// For more information, see Architecting Data Store and Concurrent /// Data Store applications, and Architecting Transactional Data Store /// applications, both in the Berkeley DB Programmer's Reference Guide. /// </remarks> public SetThreadIDDelegate SetThreadID; /// <summary> /// A delegate that formats a process ID and thread ID identifier pair. /// </summary> public SetThreadNameDelegate ThreadName; /// <summary> /// A delegate that returns if a thread of control (either a true thread /// or a process) is still running. /// </summary> public ThreadIsAliveDelegate ThreadIsAlive; /// <summary> /// Paths of directories to be used as the location of the access method /// database files. /// </summary> /// <remarks> /// <para> /// Paths specified to <see cref="Database.Open"/> will be searched /// relative to this path. Paths set using this method are additive, and /// specifying more than one will result in each specified directory /// being searched for database files. /// </para> /// <para> /// If no database directories are specified, database files must be /// named either by absolute paths or relative to the environment home /// directory. See Berkeley DB File Naming in the Programmer's Reference /// Guide for more information. /// </para> /// </remarks> public List<string> DataDirs; /// <summary> /// The path of a directory to be used as the location to create the /// access method database files. When <see cref="BTreeDatabase.Open"/>, /// <see cref="HashDatabase.Open"/>, <see cref="QueueDatabase.Open"/> or /// <see cref="RecnoDatabase.Open"/> is used to create a file it will be /// created relative to this path. /// </summary> /// <remarks> /// <para> /// This path must also exist in <see cref="DataDirs"/>. /// </para> /// <para> /// If no database directory is specified, database files must be named /// either by absolute paths or relative to the environment home /// directory. See Berkeley DB File Naming in the Programmer's Reference /// Guide for more information. /// </para> /// </remarks> public string CreationDir; internal bool encryptionIsSet; private String encryptPwd; private EncryptionAlgorithm encryptAlg; /// <summary> /// Set the password and algorithm used by the Berkeley DB library to /// perform encryption and decryption. /// </summary> /// <param name="password"> /// The password used to perform encryption and decryption. /// </param> /// <param name="alg"> /// The algorithm used to perform encryption and decryption. /// </param> public void SetEncryption(String password, EncryptionAlgorithm alg) { encryptionIsSet = true; encryptPwd = password; encryptAlg = alg; } /// <summary> /// The password used to perform encryption and decryption. /// </summary> public string EncryptionPassword { get { return encryptPwd; } } /// <summary> /// The algorithm used to perform encryption and decryption. /// </summary> public EncryptionAlgorithm EncryptAlgorithm { get { return encryptAlg; } } /// <summary> /// The prefix string that appears before error messages issued by /// Berkeley DB. /// </summary> /// <remarks> /// <para> /// For databases opened inside of a DatabaseEnvironment, setting /// ErrorPrefix affects the entire environment and is equivalent to /// setting <see cref="DatabaseEnvironment.ErrorPrefix"/>. /// </para> /// </remarks> public string ErrorPrefix; /// <summary> /// The permissions for any intermediate directories created by Berkeley /// DB. /// </summary> /// <remarks> /// <para> /// By default, Berkeley DB does not create intermediate directories /// needed for recovery, that is, if the file /a/b/c/mydatabase is being /// recovered, and the directory path b/c does not exist, recovery will /// fail. This default behavior is because Berkeley DB does not know /// what permissions are appropriate for intermediate directory /// creation, and creating the directory might result in a security /// problem. /// </para> /// <para> /// Directory permissions are interpreted as a string of nine /// characters, using the character set r (read), w (write), x (execute /// or search), and - (none). The first character is the read /// permissions for the directory owner (set to either r or -). The /// second character is the write permissions for the directory owner /// (set to either w or -). The third character is the execute /// permissions for the directory owner (set to either x or -). /// </para> /// <para> /// Similarly, the second set of three characters are the read, write /// and execute/search permissions for the directory group, and the /// third set of three characters are the read, write and execute/search /// permissions for all others. For example, the string rwx------ would /// configure read, write and execute/search access for the owner only. /// The string rwxrwx--- would configure read, write and execute/search /// access for both the owner and the group. The string rwxr----- would /// configure read, write and execute/search access for the directory /// owner and read-only access for the directory group. /// </para> /// </remarks> public string IntermediateDirMode; internal bool lckTimeoutIsSet; private uint lckTimeout; /// <summary> /// A value, in microseconds, representing lock timeouts. /// </summary> /// <remarks> /// <para> /// All timeouts are checked whenever a thread of control blocks on a /// lock or when deadlock detection is performed. As timeouts are only /// checked when the lock request first blocks or when deadlock /// detection is performed, the accuracy of the timeout depends on how /// often deadlock detection is performed. /// </para> /// <para> /// Timeout values specified for the database environment may be /// overridden on a per-transaction basis, see /// <see cref="Transaction.SetLockTimeout"/>. /// </para> /// </remarks> public uint LockTimeout { get { return lckTimeout; } set { lckTimeoutIsSet = true; lckTimeout = value; } } internal bool maxTxnsIsSet; private uint maxTxns; /// <summary> /// The number of active transactions supported by the environment. This /// value bounds the size of the memory allocated for transactions. /// Child transactions are counted as active until they either commit or /// abort. /// </summary> /// <remarks> /// <para> /// Transactions that update multiversion databases are not freed until /// the last page version that the transaction created is flushed from /// cache. This means that applications using multi-version concurrency /// control may need a transaction for each page in cache, in the /// extreme case. /// </para> /// <para> /// When all of the memory available in the database environment for /// transactions is in use, calls to /// <see cref="DatabaseEnvironment.BeginTransaction"/> will fail (until /// some active transactions complete). If MaxTransactions is never set, /// the database environment is configured to support at least 100 /// active transactions. /// </para> /// </remarks> public uint MaxTransactions { get { return maxTxns; } set { maxTxnsIsSet = true; maxTxns = value; } } /// <summary> /// The path of a directory to be used as the location to store /// the persistent metadata. /// </summary> /// <remarks> /// <para> /// By default, metadata is stored in the environment home directory. /// See Berkeley DB File Naming in the Programmer's Reference Guide for /// more information. /// </para> /// <para> /// When used in a replicated application, the metadata directory must /// be the same location for all sites within a replication group. /// </para> /// </remarks> public string MetadataDir; /// <summary> /// The path of a directory to be used as the location of temporary /// files. /// </summary> /// <remarks> /// <para> /// The files created to back in-memory access method databases will be /// created relative to this path. These temporary files can be quite /// large, depending on the size of the database. /// </para> /// <para> /// If no directories are specified, the following alternatives are /// checked in the specified order. The first existing directory path is /// used for all temporary files. /// </para> /// <list type="number"> /// <item>The value of the environment variable TMPDIR.</item> /// <item>The value of the environment variable TEMP.</item> /// <item>The value of the environment variable TMP.</item> /// <item>The value of the environment variable TempFolder.</item> /// <item>The value returned by the GetTempPath interface.</item> /// <item>The directory /var/tmp.</item> /// <item>The directory /usr/tmp.</item> /// <item>The directory /temp.</item> /// <item>The directory /tmp.</item> /// <item>The directory C:/temp.</item> /// <item>The directory C:/tmp.</item> /// </list> /// <para> /// Environment variables are only checked if /// <see cref="UseEnvironmentVars"/> is true. /// </para> /// </remarks> public string TempDir; internal bool threadCntIsSet; private uint threadCnt; /// <summary> /// An approximate number of threads in the database environment. /// </summary> /// <remarks> /// <para> /// ThreadCount must set if <see cref="DatabaseEnvironment.FailCheck"/> /// will be used. ThreadCount does not set the maximum number of threads /// but is used to determine memory sizing and the thread control block /// reclamation policy. /// </para> /// <para> /// If a process has not configured <see cref="ThreadIsAlive"/>, and /// then attempts to join a database environment configured for failure /// checking with <see cref="DatabaseEnvironment.FailCheck"/>, /// <see cref="SetThreadID"/>, <see cref="ThreadIsAlive"/> and /// ThreadCount, the program may be unable to allocate a thread control /// block and fail to join the environment. This is true of the /// standalone Berkeley DB utility programs. To avoid problems when /// using the standalone Berkeley DB utility programs with environments /// configured for failure checking, incorporate the utility's /// functionality directly in the application, or call /// <see cref="DatabaseEnvironment.FailCheck"/> before running the /// utility. /// </para> /// </remarks> public uint ThreadCount { get { return threadCnt; } set { threadCntIsSet = true; threadCnt = value; } } private uint _initthreadcount; internal bool initThreadCountIsSet; /// <summary> /// The initial number of concurrent threads catered for by the /// Berkeley DB environment /// </summary> /// <remarks> /// <para> /// This value is used by <see cref="DatabaseEnvironment.Open"/> to /// force Berkeley DB to allocate a certain number of thread /// objects when the environment is created. This can be useful if an /// application uses a large number of thread objects, and /// experiences performance issues with the default dynamic allocation /// algorithm. /// </para> /// <para> /// If the database environment already exists when /// <see cref="DatabaseEnvironment.Open"/> is called, the value of /// InitLockers will be ignored. /// </para> /// </remarks> public uint InitThreadCount { get { return _initthreadcount; } set { initThreadCountIsSet = true; _initthreadcount = value; } } private uint _inittxncount; internal bool initTxnCountIsSet; /// <summary> /// The initial number of transactions catered for by the Berkeley DB /// environment /// </summary> /// <remarks> /// <para> /// This value is used by <see cref="DatabaseEnvironment.Open"/> to /// force Berkeley DB to allocate a certain number of transaction /// objects when the environment is created. This can be useful if an /// application uses a large number of transaction objects, and /// experiences performance issues with the default dynamic allocation /// algorithm. /// </para> /// <para> /// If the database environment already exists when /// <see cref="DatabaseEnvironment.Open"/> is called, the value of /// InitLockers will be ignored. /// </para> /// </remarks> public uint InitTxnCount { get { return _inittxncount; } set { initTxnCountIsSet = true; _inittxncount = value; } } internal bool txnTimeoutIsSet; private uint _txnTimeout; /// <summary> /// A value, in microseconds, representing transaction timeouts. /// </summary> /// <remarks> /// <para> /// All timeouts are checked whenever a thread of control blocks on a /// lock or when deadlock detection is performed. As timeouts are only /// checked when the lock request first blocks or when deadlock /// detection is performed, the accuracy of the timeout depends on how /// often deadlock detection is performed. /// </para> /// <para> /// Timeout values specified for the database environment may be /// overridden on a per-transaction basis, see /// <see cref="Transaction.SetTxnTimeout"/>. /// </para> /// </remarks> public uint TxnTimeout { get { return _txnTimeout; } set { txnTimeoutIsSet = true; _txnTimeout = value; } } internal bool txnTimestampIsSet; private DateTime _txnTimestamp; /// <summary> /// Recover to the time specified by timestamp rather than to the most /// current possible date. /// </summary> /// <remarks> /// <para> /// Once a database environment has been upgraded to a new version of /// Berkeley DB involving a log format change (see Upgrading Berkeley DB /// installations in the Programmer's Reference Guide), it is no longer /// possible to recover to a specific time before that upgrade. /// </para> /// </remarks> public DateTime TxnTimestamp { get { return _txnTimestamp; } set { txnTimestampIsSet = true; _txnTimestamp = value; } } /// <summary> /// Specific additional informational and debugging messages in the /// Berkeley DB message output. /// </summary> public VerboseMessages Verbosity = new VerboseMessages(); /* Fields for set_flags() */ /// <summary> /// If true, database operations for which no explicit transaction /// handle was specified, and which modify databases in the database /// environment, will be automatically enclosed within a transaction. /// </summary> public bool AutoCommit; /// <summary> /// If true, Berkeley DB Concurrent Data Store applications will perform /// locking on an environment-wide basis rather than on a per-database /// basis. /// </summary> public bool CDB_ALLDB; /// <summary> /// If true, Berkeley DB will flush database writes to the backing disk /// before returning from the write system call, rather than flushing /// database writes explicitly in a separate system call, as necessary. /// </summary> /// <remarks> /// This is only available on some systems (for example, systems /// supporting the IEEE/ANSI Std 1003.1 (POSIX) standard O_DSYNC flag, /// or systems supporting the Windows FILE_FLAG_WRITE_THROUGH flag). /// This flag may result in inaccurate file modification times and other /// file-level information for Berkeley DB database files. This flag /// will almost certainly result in a performance decrease on most /// systems. This flag is only applicable to certain filesysystems (for /// example, the Veritas VxFS filesystem), where the filesystem's /// support for trickling writes back to stable storage behaves badly /// (or more likely, has been misconfigured). /// </remarks> public bool ForceFlush; /// /// <summary> Set a flag in the environment indicating that a /// hot backup is in progress. /// </summary> /// <remarks> /// When a "hot backup" copy of a database environment is taken, this /// attribute should be configured in the environment prior to copying. /// If any transactions with the bulk insert optimization enabled (i.e., /// started with the Bulk configuration attribute) are in progress, /// setting the HotBackupInProgress attribute will force a checkpoint in /// the environment. After this attribute is set, the bulk insert /// optimization is disabled, until the attribute is reset. Using this /// protocol allows a hot backup procedure to make a consistent copy of /// the database even when bulk transactions are ongoing. Please see the /// discussion of hot backups in the Getting Started With Transactions /// Guide, and the description of the Bulk attribute in /// <see cref="TransactionConfig.Bulk"/>for more information. /// </remarks> public bool HotbackupInProgress; /// <summary> /// If true, Berkeley DB will page-fault shared regions into memory when /// initially creating or joining a Berkeley DB environment. In /// addition, Berkeley DB will write the shared regions when creating an /// environment, forcing the underlying virtual memory and filesystems /// to instantiate both the necessary memory and the necessary disk /// space. This can also avoid out-of-disk space failures later on. /// </summary> /// <remarks> /// <para> /// In some applications, the expense of page-faulting the underlying /// shared memory regions can affect performance. (For example, if the /// page-fault occurs while holding a lock, other lock requests can /// convoy, and overall throughput may decrease.) /// </para> /// </remarks> public bool InitRegions; /// <summary> /// If true, turn off system buffering of Berkeley DB database files to /// avoid double caching. /// </summary> public bool NoBuffer; /// <summary> /// If true, Berkeley DB will grant all requested mutual exclusion /// mutexes and database locks without regard for their actual /// availability. This functionality should never be used for purposes /// other than debugging. /// </summary> public bool NoLocking; /// <summary> /// If true, Berkeley DB will copy read-only database files into the /// local cache instead of potentially mapping them into process memory /// (see <see cref="MPoolConfig.MMapSize"/> for further information). /// </summary> public bool NoMMap; /// <summary> /// If true, Berkeley DB will ignore any panic state in the database /// environment. (Database environments in a panic state normally refuse /// all attempts to call Berkeley DB functions, throwing /// <see cref="RunRecoveryException"/>. This functionality should never /// be used for purposes other than debugging. /// </summary> public bool NoPanic; /// <summary> /// If true, overwrite files stored in encrypted formats before deleting /// them. /// </summary> /// <remarks> /// Berkeley DB overwrites files using alternating 0xff, 0x00 and 0xff /// byte patterns. For file overwriting to be effective, the underlying /// file must be stored on a fixed-block filesystem. Systems with /// journaling or logging filesystems will require operating system /// support and probably modification of the Berkeley DB sources. /// </remarks> public bool Overwrite; /// <summary> /// If true, database calls timing out based on lock or transaction /// timeout values will throw <see cref="LockNotGrantedException"/> /// instead of <see cref="DeadlockException"/>. This allows applications /// to distinguish between operations which have deadlocked and /// operations which have exceeded their time limits. /// </summary> public bool TimeNotGranted; /// <summary> /// If true, Berkeley DB will not write or synchronously flush the log /// on transaction commit. /// </summary> /// <remarks> /// This means that transactions exhibit the ACI (atomicity, /// consistency, and isolation) properties, but not D (durability); that /// is, database integrity will be maintained, but if the application or /// system fails, it is possible some number of the most recently /// committed transactions may be undone during recovery. The number of /// transactions at risk is governed by how many log updates can fit /// into the log buffer, how often the operating system flushes dirty /// buffers to disk, and how often the log is checkpointed. /// </remarks> public bool TxnNoSync; /// <summary> /// If true and a lock is unavailable for any Berkeley DB operation /// performed in the context of a transaction, cause the operation to /// throw <see cref="DeadlockException"/> (or /// <see cref="LockNotGrantedException"/> if /// <see cref="TimeNotGranted"/> is set. /// </summary> public bool TxnNoWait; /// <summary> /// If true, all transactions in the environment will be started as if /// <see cref="TransactionConfig.Snapshot"/> were passed to /// <see cref="DatabaseEnvironment.BeginTransaction"/>, and all /// non-transactional cursors will be opened as if /// <see cref="CursorConfig.SnapshotIsolation"/> were passed to /// <see cref="BaseDatabase.Cursor"/>. /// </summary> public bool TxnSnapshot; /// <summary> /// If true, Berkeley DB will write, but will not synchronously flush, /// the log on transaction commit. /// </summary> /// <remarks> /// This means that transactions exhibit the ACI (atomicity, /// consistency, and isolation) properties, but not D (durability); that /// is, database integrity will be maintained, but if the system fails, /// it is possible some number of the most recently committed /// transactions may be undone during recovery. The number of /// transactions at risk is governed by how often the system flushes /// dirty buffers to disk and how often the log is checkpointed. /// </remarks> public bool TxnWriteNoSync; /// <summary> /// If true, all databases in the environment will be opened as if /// <see cref="DatabaseConfig.UseMVCC"/> is passed to /// <see cref="Database.Open"/>. This flag will be ignored for queue /// databases for which MVCC is not supported. /// </summary> public bool UseMVCC; /// <summary> /// If true, Berkeley DB will yield the processor immediately after each /// page or mutex acquisition. This functionality should never be used /// for purposes other than stress testing. /// </summary> public bool YieldCPU; internal uint flags { get { uint ret = 0; ret |= AutoCommit ? DbConstants.DB_AUTO_COMMIT : 0; ret |= CDB_ALLDB ? DbConstants.DB_CDB_ALLDB : 0; ret |= ForceFlush ? DbConstants.DB_DSYNC_DB : 0; ret |= HotbackupInProgress ? DbConstants.DB_HOTBACKUP_IN_PROGRESS : 0; ret |= InitRegions ? DbConstants.DB_REGION_INIT : 0; ret |= NoBuffer ? DbConstants.DB_DIRECT_DB : 0; ret |= NoLocking ? DbConstants.DB_NOLOCKING : 0; ret |= NoMMap ? DbConstants.DB_NOMMAP : 0; ret |= NoPanic ? DbConstants.DB_NOPANIC : 0; ret |= Overwrite ? DbConstants.DB_OVERWRITE : 0; ret |= TimeNotGranted ? DbConstants.DB_TIME_NOTGRANTED : 0; ret |= TxnNoSync ? DbConstants.DB_TXN_NOSYNC : 0; ret |= TxnNoWait ? DbConstants.DB_TXN_NOWAIT : 0; ret |= TxnSnapshot ? DbConstants.DB_TXN_SNAPSHOT : 0; ret |= TxnWriteNoSync ? DbConstants.DB_TXN_WRITE_NOSYNC : 0; ret |= UseMVCC ? DbConstants.DB_MULTIVERSION : 0; ret |= YieldCPU ? DbConstants.DB_YIELDCPU : 0; return ret; } } /* Fields for open() flags */ /// <summary> /// If true, Berkeley DB subsystems will create any underlying files, as /// necessary. /// </summary> public bool Create; /// <summary> /// If true, the created <see cref="DatabaseEnvironment"/> object will /// be free-threaded; that is, concurrently usable by multiple threads /// in the address space. /// </summary> /// <remarks> /// <para> /// Required to be true if the created <see cref="DatabaseEnvironment"/> /// object will be concurrently used by more than one thread in the /// process, or if any <see cref="Database"/> objects opened in the /// scope of the <see cref="DatabaseEnvironment"/> object will be /// concurrently used by more than one thread in the process. /// </para> /// <para>Required to be true when using the Replication Manager.</para> /// </remarks> public bool FreeThreaded; /// <summary> /// If true, lock shared Berkeley DB environment files and memory-mapped /// databases into memory. /// </summary> public bool Lockdown; /// <summary> /// If true, allocate region memory from the heap instead of from memory /// backed by the filesystem or system shared memory. /// </summary> /// <remarks> /// <para> /// This setting implies the environment will only be accessed by a /// single process (although that process may be multithreaded). This /// flag has two effects on the Berkeley DB environment. First, all /// underlying data structures are allocated from per-process memory /// instead of from shared memory that is accessible to more than a /// single process. Second, mutexes are only configured to work between /// threads. /// </para> /// <para> /// This setting should be false if more than a single process is /// accessing the environment because it is likely to cause database /// corruption and unpredictable behavior. For example, if both a server /// application and Berkeley DB utilities (for example, db_archive, /// db_checkpoint or db_stat) are expected to access the environment, /// this setting should be false. /// </para> /// </remarks> public bool Private; /// <summary> /// If true, check to see if recovery needs to be performed before /// opening the database environment. (For this check to be accurate, /// all processes using the environment must specify it when opening the /// environment.) /// </summary> /// <remarks> /// If recovery needs to be performed for any reason (including the /// initial use of this setting), and <see cref="RunRecovery"/>is also /// specified, recovery will be performed and the open will proceed /// normally. If recovery needs to be performed and /// <see cref="RunRecovery"/> is not specified, /// <see cref="RunRecoveryException"/> will be thrown. If recovery does /// not need to be performed, <see cref="RunRecovery"/> will be ignored. /// See Architecting Transactional Data Store applications in the /// Programmer's Reference Guide for more information. /// </remarks> public bool Register; /// <summary> /// If true, catastrophic recovery will be run on this environment /// before opening it for normal use. /// </summary> /// <remarks> /// If true, the <see cref="Create"/> and <see cref="UseTxns"/> must /// also be set, because the regions will be removed and re-created, /// and transactions are required for application recovery. /// </remarks> public bool RunFatalRecovery; /// <summary> /// If true, normal recovery will be run on this environment before /// opening it for normal use. /// </summary> /// <remarks> /// If true, the <see cref="Create"/> and <see cref="UseTxns"/> must /// also be set, because the regions will be removed and re-created, /// and transactions are required for application recovery. /// </remarks> public bool RunRecovery; /// <summary> /// If true, allocate region memory from system shared memory instead of /// from heap memory or memory backed by the filesystem. /// </summary> /// <remarks> /// See Shared Memory Regions in the Programmer's Reference Guide for /// more information. /// </remarks> public bool SystemMemory; /// <summary> /// If true, the Berkeley DB process' environment may be permitted to /// specify information to be used when naming files. /// </summary> /// <remarks> /// <para> /// See Berkeley DB File Naming in the Programmer's Reference Guide for /// more information. /// </para> /// <para> /// Because permitting users to specify which files are used can create /// security problems, environment information will be used in file /// naming for all users only if UseEnvironmentVars is true. /// </para> /// </remarks> public bool UseEnvironmentVars; private bool USE_ENVIRON_ROOT = false; /// <summary> /// If true, initialize locking for the Berkeley DB Concurrent Data /// Store product. /// </summary> /// <remarks> /// In this mode, Berkeley DB provides multiple reader/single writer /// access. The only other subsystem that should be specified with /// UseCDB flag is <see cref="UseMPool"/>. /// </remarks> public bool UseCDB; /// <summary> /// If true, initialize the locking subsystem. /// </summary> /// <remarks> /// This subsystem should be used when multiple processes or threads are /// going to be reading and writing a Berkeley DB database, so that they /// do not interfere with each other. If all threads are accessing the /// database(s) read-only, locking is unnecessary. When UseLocking is /// specified, it is usually necessary to run a deadlock detector, as /// well. See <see cref="DatabaseEnvironment.DetectDeadlocks"/> for more /// information. /// </remarks> public bool UseLocking; /// <summary> /// If true, initialize the logging subsystem. /// </summary> /// <remarks> /// This subsystem should be used when recovery from application or /// system failure is necessary. If the log region is being created and /// log files are already present, the log files are reviewed; /// subsequent log writes are appended to the end of the log, rather /// than overwriting current log entries. /// </remarks> public bool UseLogging; /// <summary> /// If true, initialize the shared memory buffer pool subsystem. /// </summary> /// <remarks> /// This subsystem should be used whenever an application is using any /// Berkeley DB access method. /// </remarks> public bool UseMPool; /// <summary> /// If true, initialize the replication subsystem. /// </summary> /// <remarks> /// This subsystem should be used whenever an application plans on using /// replication. UseReplication requires <see cref="UseTxns"/> and /// <see cref="UseLocking"/> also be set. /// </remarks> public bool UseReplication; /// <summary> /// If true, initialize the transaction subsystem. /// </summary> /// <remarks> /// This subsystem should be used when recovery and atomicity of /// multiple operations are important. UseTxns implies /// <see cref="UseLogging"/>. /// </remarks> public bool UseTxns; internal uint openFlags { get { uint ret = 0; ret |= Create ? DbConstants.DB_CREATE : 0; ret |= FreeThreaded ? DbConstants.DB_THREAD : 0; ret |= Lockdown ? DbConstants.DB_LOCKDOWN : 0; ret |= Private ? DbConstants.DB_PRIVATE : 0; ret |= RunFatalRecovery ? DbConstants.DB_RECOVER_FATAL : 0; ret |= RunRecovery ? DbConstants.DB_RECOVER : 0; ret |= SystemMemory ? DbConstants.DB_SYSTEM_MEM : 0; ret |= UseEnvironmentVars ? DbConstants.DB_USE_ENVIRON : 0; ret |= USE_ENVIRON_ROOT ? DbConstants.DB_USE_ENVIRON_ROOT : 0; ret |= UseCDB ? DbConstants.DB_INIT_CDB : 0; ret |= UseLocking ? DbConstants.DB_INIT_LOCK : 0; ret |= UseLogging ? DbConstants.DB_INIT_LOG : 0; ret |= UseMPool ? DbConstants.DB_INIT_MPOOL : 0; ret |= UseReplication ? DbConstants.DB_INIT_REP : 0; ret |= UseTxns ? DbConstants.DB_INIT_TXN : 0; return ret; } } } }
// 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.Buffers; using System.Linq; using System.Text; using Xunit; namespace System.Memory.Tests { public abstract class ReadOnlySequenceTestsByte { public class Array : ReadOnlySequenceTestsByte { public Array() : base(ReadOnlySequenceFactory<byte>.ArrayFactory) { } } public class Memory : ReadOnlySequenceTestsByte { public Memory() : base(ReadOnlySequenceFactory<byte>.MemoryFactory) { } } public class SingleSegment : ReadOnlySequenceTestsByte { public SingleSegment() : base(ReadOnlySequenceFactory<byte>.SingleSegmentFactory) { } } public class SegmentPerByte : ReadOnlySequenceTestsByte { public SegmentPerByte() : base(ReadOnlySequenceFactory<byte>.SegmentPerItemFactory) { } } public class SplitInThreeSegments : ReadOnlySequenceTestsByte { public SplitInThreeSegments() : base(ReadOnlySequenceFactory<byte>.SplitInThree) { } } internal ReadOnlySequenceFactory<byte> Factory { get; } internal ReadOnlySequenceTestsByte(ReadOnlySequenceFactory<byte> factory) { Factory = factory; } [Fact] public void EmptyIsCorrect() { ReadOnlySequence<byte> buffer = Factory.CreateOfSize(0); Assert.Equal(0, buffer.Length); Assert.True(buffer.IsEmpty); } [Theory] [InlineData(1)] [InlineData(8)] public void LengthIsCorrect(int length) { ReadOnlySequence<byte> buffer = Factory.CreateOfSize(length); Assert.Equal(length, buffer.Length); } [Theory] [InlineData(1)] [InlineData(8)] public void ToArrayIsCorrect(int length) { byte[] data = Enumerable.Range(0, length).Select(i => (byte)i).ToArray(); ReadOnlySequence<byte> buffer = Factory.CreateWithContent(data); Assert.Equal(length, buffer.Length); Assert.Equal(data, buffer.ToArray()); } [Fact] public void ToStringIsCorrect() { ReadOnlySequence<byte> buffer = Factory.CreateWithContent(Enumerable.Range(0, 255).Select(i => (byte)i).ToArray()); Assert.Equal("System.Buffers.ReadOnlySequence<Byte>[255]", buffer.ToString()); } [Theory] [MemberData(nameof(ValidSliceCases))] public void Slice_Works(Func<ReadOnlySequence<byte>, ReadOnlySequence<byte>> func) { ReadOnlySequence<byte> buffer = Factory.CreateWithContent(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); ReadOnlySequence<byte> slice = func(buffer); Assert.Equal(new byte[] { 5, 6, 7, 8, 9 }, slice.ToArray()); } [Theory] [MemberData(nameof(OutOfRangeSliceCases))] public void ReadOnlyBufferDoesNotAllowSlicingOutOfRange(Action<ReadOnlySequence<byte>> fail) { ReadOnlySequence<byte> buffer = Factory.CreateOfSize(100); Assert.Throws<ArgumentOutOfRangeException>(() => fail(buffer)); } [Fact] public void ReadOnlyBufferGetPosition_MovesPosition() { ReadOnlySequence<byte> buffer = Factory.CreateOfSize(100); SequencePosition position = buffer.GetPosition(65); Assert.Equal(35, buffer.Slice(position).Length); position = buffer.GetPosition(65, buffer.Start); Assert.Equal(35, buffer.Slice(position).Length); } [Fact] public void ReadOnlyBufferGetPosition_ChecksBounds() { ReadOnlySequence<byte> buffer = Factory.CreateOfSize(100); Assert.Throws<ArgumentOutOfRangeException>(() => buffer.GetPosition(101)); Assert.Throws<ArgumentOutOfRangeException>(() => buffer.GetPosition(101, buffer.Start)); } [Fact] public void ReadOnlyBufferGetPosition_DoesNotAlowNegative() { ReadOnlySequence<byte> buffer = Factory.CreateOfSize(20); Assert.Throws<ArgumentOutOfRangeException>(() => buffer.GetPosition(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => buffer.GetPosition(-1, buffer.Start)); } [Fact] public void ReadOnlyBufferSlice_ChecksEnd() { ReadOnlySequence<byte> buffer = Factory.CreateOfSize(100); Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Slice(70, buffer.Start)); } [Fact] public void SliceToTheEndWorks() { ReadOnlySequence<byte> buffer = Factory.CreateOfSize(10); Assert.True(buffer.Slice(buffer.End).IsEmpty); } [Theory] [InlineData("a", 'a', 0)] [InlineData("ab", 'a', 0)] [InlineData("aab", 'a', 0)] [InlineData("acab", 'a', 0)] [InlineData("acab", 'c', 1)] [InlineData("abcdefghijklmnopqrstuvwxyz", 'l', 11)] [InlineData("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", 'l', 11)] [InlineData("aaaaaaaaaaacmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", 'm', 12)] [InlineData("aaaaaaaaaaarmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", 'r', 11)] [InlineData("/localhost:5000/PATH/%2FPATH2/ HTTP/1.1", '%', 21)] [InlineData("/localhost:5000/PATH/%2FPATH2/?key=value HTTP/1.1", '%', 21)] [InlineData("/localhost:5000/PATH/PATH2/?key=value HTTP/1.1", '?', 27)] [InlineData("/localhost:5000/PATH/PATH2/ HTTP/1.1", ' ', 27)] public void PositionOf_ReturnsPosition(string raw, char searchFor, int expectIndex) { ReadOnlySequence<byte> buffer = Factory.CreateWithContent(Encoding.ASCII.GetBytes(raw)); SequencePosition? result = buffer.PositionOf((byte)searchFor); Assert.NotNull(result); Assert.Equal(buffer.Slice(result.Value).ToArray(), Encoding.ASCII.GetBytes(raw.Substring(expectIndex))); } [Fact] public void PositionOf_ReturnsNullIfNotFound() { ReadOnlySequence<byte> buffer = Factory.CreateWithContent(new byte[] { 1, 2, 3 }); SequencePosition? result = buffer.PositionOf((byte)4); Assert.Null(result); } [Fact] public void CopyTo_ThrowsWhenSourceLargerThenDestination() { ReadOnlySequence<byte> buffer = Factory.CreateOfSize(10); Assert.Throws<ArgumentOutOfRangeException>(() => { Span<byte> span = new byte[5]; buffer.CopyTo(span); }); } public static TheoryData<Func<ReadOnlySequence<byte>, ReadOnlySequence<byte>>> ValidSliceCases => new TheoryData<Func<ReadOnlySequence<byte>, ReadOnlySequence<byte>>> { b => b.Slice(5), b => b.Slice(0).Slice(5), b => b.Slice(5, 5), b => b.Slice(b.GetPosition(5), 5), b => b.Slice(5, b.GetPosition(10)), b => b.Slice(b.GetPosition(5), b.GetPosition(10)), b => b.Slice(b.GetPosition(5, b.Start), 5), b => b.Slice(5, b.GetPosition(10, b.Start)), b => b.Slice(b.GetPosition(5, b.Start), b.GetPosition(10, b.Start)), b => b.Slice((long)5), b => b.Slice((long)5, 5), b => b.Slice(b.GetPosition(5), (long)5), b => b.Slice((long)5, b.GetPosition(10)), b => b.Slice(b.GetPosition(5, b.Start), (long)5), b => b.Slice((long)5, b.GetPosition(10, b.Start)), }; public static TheoryData<Action<ReadOnlySequence<byte>>> OutOfRangeSliceCases => new TheoryData<Action<ReadOnlySequence<byte>>> { // negative start b => b.Slice(-1), // no length b => b.Slice(-1, -1), // negative length b => b.Slice(-1, 0), // zero length b => b.Slice(-1, 1), // positive length b => b.Slice(-1, 101), // after end length b => b.Slice(-1, b.Start), // to start b => b.Slice(-1, b.End), // to end // zero start b => b.Slice(0, -1), // negative length b => b.Slice(0, 101), // after end length // end start b => b.Slice(100, -1), // negative length b => b.Slice(100, 1), // after end length b => b.Slice(100, b.Start), // to start // After end start b => b.Slice(101), // no length b => b.Slice(101, -1), // negative length b => b.Slice(101, 0), // zero length b => b.Slice(101, 1), // after end length b => b.Slice(101, b.Start), // to start b => b.Slice(101, b.End), // to end // At Start start b => b.Slice(b.Start, -1), // negative length b => b.Slice(b.Start, 101), // after end length // At End start b => b.Slice(b.End, -1), // negative length b => b.Slice(b.End, 1), // after end length b => b.Slice(b.End, b.Start), // to start // Slice at begin b => b.Slice(0, 70).Slice(0, b.End), // to after end b => b.Slice(0, 70).Slice(b.Start, b.End), // to after end // from after end b => b.Slice(0, 70).Slice(b.End), b => b.Slice(0, 70).Slice(b.End, -1), // negative length b => b.Slice(0, 70).Slice(b.End, 0), // zero length b => b.Slice(0, 70).Slice(b.End, 1), // after end length b => b.Slice(0, 70).Slice(b.End, b.Start), // to start b => b.Slice(0, 70).Slice(b.End, b.End), // to after end // Slice at begin b => b.Slice(b.Start, 70).Slice(0, b.End), // to after end b => b.Slice(b.Start, 70).Slice(b.Start, b.End), // to after end // from after end b => b.Slice(b.Start, 70).Slice(b.End), b => b.Slice(b.Start, 70).Slice(b.End, -1), // negative length b => b.Slice(b.Start, 70).Slice(b.End, 0), // zero length b => b.Slice(b.Start, 70).Slice(b.End, 1), // after end length b => b.Slice(b.Start, 70).Slice(b.End, b.Start), // to start b => b.Slice(b.Start, 70).Slice(b.End, b.End), // to after end // Slice at middle b => b.Slice(30, 40).Slice(0, b.Start), // to before start b => b.Slice(30, 40).Slice(0, b.End), // to after end // from before start b => b.Slice(30, 40).Slice(b.Start), b => b.Slice(30, 40).Slice(b.Start, -1), // negative length b => b.Slice(30, 40).Slice(b.Start, 0), // zero length b => b.Slice(30, 40).Slice(b.Start, 1), // positive length b => b.Slice(30, 40).Slice(b.Start, 41), // after end length b => b.Slice(30, 40).Slice(b.Start, b.Start), // to before start b => b.Slice(30, 40).Slice(b.Start, b.End), // to after end // from after end b => b.Slice(30, 40).Slice(b.End), b => b.Slice(b.Start, 70).Slice(b.End, -1), // negative length b => b.Slice(b.Start, 70).Slice(b.End, 0), // zero length b => b.Slice(b.Start, 70).Slice(b.End, 1), // after end length b => b.Slice(30, 40).Slice(b.End, b.Start), // to before start b => b.Slice(30, 40).Slice(b.End, b.End), // to after end // Slice at end b => b.Slice(70, 30).Slice(0, b.Start), // to before start // from before start b => b.Slice(30, 40).Slice(b.Start), b => b.Slice(30, 40).Slice(b.Start, -1), // negative length b => b.Slice(30, 40).Slice(b.Start, 0), // zero length b => b.Slice(30, 40).Slice(b.Start, 1), // positive length b => b.Slice(30, 40).Slice(b.Start, 31), // after end length b => b.Slice(30, 40).Slice(b.Start, b.Start), // to before start b => b.Slice(30, 40).Slice(b.Start, b.End), // to end // from end b => b.Slice(70, 30).Slice(b.End, b.Start), // to before start // Slice at end b => b.Slice(70, 30).Slice(0, b.Start), // to before start // from before start b => b.Slice(30, 40).Slice(b.Start), b => b.Slice(30, 40).Slice(b.Start, -1), // negative length b => b.Slice(30, 40).Slice(b.Start, 0), // zero length b => b.Slice(30, 40).Slice(b.Start, 1), // positive length b => b.Slice(30, 40).Slice(b.Start, 31), // after end length b => b.Slice(30, 40).Slice(b.Start, b.Start), // to before start b => b.Slice(30, 40).Slice(b.Start, b.End), // to end // from end b => b.Slice(70, 30).Slice(b.End, b.Start), // to before start }; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Buffers; using System.Buffers.Reader; using System.Buffers.Text; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text.Http.Parser.Internal; namespace System.Text.Http.Parser { public class HttpParser : IHttpParser { // TODO: commented out; //public ILogger Log { get; set; } // byte types don't have a data type annotation so we pre-cast them; to avoid in-place casts private const byte ByteCR = (byte)'\r'; private const byte ByteLF = (byte)'\n'; private const byte ByteColon = (byte)':'; private const byte ByteSpace = (byte)' '; private const byte ByteTab = (byte)'\t'; private const byte ByteQuestionMark = (byte)'?'; private const byte BytePercentage = (byte)'%'; private const long maxRequestLineLength = 1024; static readonly byte[] s_Eol = Encoding.UTF8.GetBytes("\r\n"); static readonly byte[] s_http11 = Encoding.UTF8.GetBytes("HTTP/1.1"); static readonly byte[] s_http10 = Encoding.UTF8.GetBytes("HTTP/1.0"); static readonly byte[] s_http20 = Encoding.UTF8.GetBytes("HTTP/2.0"); private readonly bool _showErrorDetails; public HttpParser() : this(showErrorDetails: true) { } public HttpParser(bool showErrorDetails) { _showErrorDetails = showErrorDetails; } public unsafe bool ParseRequestLine<T>(T handler, in ReadOnlySequence<byte> buffer, out SequencePosition consumed, out SequencePosition examined) where T : IHttpRequestLineHandler { consumed = buffer.Start; examined = buffer.End; // Prepare the first span var span = buffer.First.Span; var lineIndex = span.IndexOf(ByteLF); if (lineIndex >= 0) { consumed = buffer.GetPosition(lineIndex + 1, consumed); span = span.Slice(0, lineIndex + 1); } else if (buffer.IsSingleSegment) { return false; } else { if (TryGetNewLineSpan(buffer, out SequencePosition found)) { span = PipelineExtensions.ToSpan(buffer.Slice(consumed, found)); consumed = found; } else { // No request line end return false; } } // Fix and parse the span fixed (byte* data = &MemoryMarshal.GetReference(span)) { ParseRequestLine(ref handler, data, span.Length); } examined = consumed; return true; } public unsafe bool ParseRequestLine<T>(ref T handler, in ReadOnlySequence<byte> buffer, out int consumed) where T : IHttpRequestLineHandler { // Prepare the first span var span = buffer.First.Span; var lineIndex = span.IndexOf(ByteLF); if (lineIndex >= 0) { consumed = lineIndex + 1; span = span.Slice(0, lineIndex + 1); } else { var eol = Sequence.IndexOf(buffer, s_Eol[0], s_Eol[1]); if (eol == -1) { consumed = 0; return false; } span = PipelineExtensions.ToSpan(buffer.Slice(0, eol + s_Eol.Length)); } // Fix and parse the span fixed (byte* data = &MemoryMarshal.GetReference(span)) { ParseRequestLine(ref handler, data, span.Length); } consumed = span.Length; return true; } private unsafe void ParseRequestLine<T>(ref T handler, byte* data, int length) where T : IHttpRequestLineHandler { // Get Method and set the offset var method = HttpUtilities.GetKnownMethod(data, length, out var offset); ReadOnlySpan<byte> customMethod = method == Http.Method.Custom ? GetUnknownMethod(data, length, out offset) : default; // Skip space offset++; byte ch = 0; // Target = Path and Query var pathEncoded = false; var pathStart = -1; for (; offset < length; offset++) { ch = data[offset]; if (ch == ByteSpace) { if (pathStart == -1) { // Empty path is illegal RejectRequestLine(data, length); } break; } else if (ch == ByteQuestionMark) { if (pathStart == -1) { // Empty path is illegal RejectRequestLine(data, length); } break; } else if (ch == BytePercentage) { if (pathStart == -1) { // Path starting with % is illegal RejectRequestLine(data, length); } pathEncoded = true; } else if (pathStart == -1) { pathStart = offset; } } if (pathStart == -1) { // Start of path not found RejectRequestLine(data, length); } var pathBuffer = new ReadOnlySpan<byte>(data + pathStart, offset - pathStart); // Query string var queryStart = offset; if (ch == ByteQuestionMark) { // We have a query string for (; offset < length; offset++) { ch = data[offset]; if (ch == ByteSpace) { break; } } } // End of query string not found if (offset == length) { RejectRequestLine(data, length); } var targetBuffer = new ReadOnlySpan<byte>(data + pathStart, offset - pathStart); var query = new ReadOnlySpan<byte>(data + queryStart, offset - queryStart); // Consume space offset++; // Version var httpVersion = HttpUtilities.GetKnownVersion(data + offset, length - offset); if (httpVersion == Http.Version.Unknown) { if (data[offset] == ByteCR || data[length - 2] != ByteCR) { // If missing delimiter or CR before LF, reject and log entire line RejectRequestLine(data, length); } else { // else inform HTTP version is unsupported. RejectUnknownVersion(data + offset, length - offset - 2); } } // After version's 8 bytes and CR, expect LF if (data[offset + 8 + 1] != ByteLF) { RejectRequestLine(data, length); } var line = new ReadOnlySpan<byte>(data, length); handler.OnStartLine(method, httpVersion, targetBuffer, pathBuffer, query, customMethod, pathEncoded); } public unsafe bool ParseHeaders<T>(T handler, in ReadOnlySequence<byte> buffer, out SequencePosition consumed, out SequencePosition examined, out int consumedBytes) where T : IHttpHeadersHandler { consumed = buffer.Start; examined = buffer.End; consumedBytes = 0; var bufferEnd = buffer.End; var reader = BufferReader.Create(buffer); var start = default(BufferReader); var done = false; try { while (!reader.End) { var span = reader.CurrentSegment; var remaining = span.Length - reader.CurrentSegmentIndex; fixed (byte* pBuffer = &MemoryMarshal.GetReference(span)) { while (remaining > 0) { var index = reader.CurrentSegmentIndex; int ch1; int ch2; // Fast path, we're still looking at the same span if (remaining >= 2) { ch1 = pBuffer[index]; ch2 = pBuffer[index + 1]; } else { // Store the reader before we look ahead 2 bytes (probably straddling // spans) start = reader; // Possibly split across spans ch1 = reader.Read(); ch2 = reader.Read(); } if (ch1 == ByteCR) { // Check for final CRLF. if (ch2 == -1) { // Reset the reader so we don't consume anything reader = start; return false; } else if (ch2 == ByteLF) { // If we got 2 bytes from the span directly so skip ahead 2 so that // the reader's state matches what we expect if (index == reader.CurrentSegmentIndex) { reader.Advance(2); } done = true; return true; } // Headers don't end in CRLF line. RejectRequest(RequestRejectionReason.InvalidRequestHeadersNoCRLF); } // We moved the reader so look ahead 2 bytes so reset both the reader // and the index if (index != reader.CurrentSegmentIndex) { reader = start; index = reader.CurrentSegmentIndex; } var endIndex = new ReadOnlySpan<byte>(pBuffer + index, remaining).IndexOf(ByteLF); var length = 0; if (endIndex != -1) { length = endIndex + 1; var pHeader = pBuffer + index; TakeSingleHeader(pHeader, length, ref handler); } else { var current = reader.Position; var subBuffer = buffer.Slice(reader.Position); // Split buffers var lineEnd = BuffersExtensions.PositionOf(subBuffer, ByteLF); if (!lineEnd.HasValue) { // Not there return false; } // Make sure LF is included in lineEnd lineEnd = subBuffer.GetPosition(1, lineEnd.Value); var headerSpan = PipelineExtensions.ToSpan(subBuffer.Slice(current, lineEnd.Value)); length = headerSpan.Length; fixed (byte* pHeader = &MemoryMarshal.GetReference(headerSpan)) { TakeSingleHeader(pHeader, length, ref handler); } // We're going to the next span after this since we know we crossed spans here // so mark the remaining as equal to the headerSpan so that we end up at 0 // on the next iteration remaining = length; } // Skip the reader forward past the header line reader.Advance(length); remaining -= length; } } } return false; } finally { consumed = reader.Position; consumedBytes = reader.ConsumedBytes; if (done) { examined = consumed; } } } public unsafe bool ParseHeaders<T>(ref T handler, ReadOnlySequence<byte> buffer, out int consumedBytes) where T : IHttpHeadersHandler { var index = 0; consumedBytes = 0; SequencePosition position = buffer.Start; if (!buffer.TryGet(ref position, out ReadOnlyMemory<byte> currentMemory)) { consumedBytes = 0; return false; } ReadOnlySpan<byte> currentSpan = currentMemory.Span; var remaining = currentSpan.Length; while (true) { fixed (byte* pBuffer = &MemoryMarshal.GetReference(currentSpan)) { while (remaining > 0) { int ch1; int ch2; // Fast path, we're still looking at the same span if (remaining >= 2) { ch1 = pBuffer[index]; ch2 = pBuffer[index + 1]; } // Slow Path else { ReadTwoChars(buffer, consumedBytes, out ch1, out ch2); // I think the above is fast enough. If we don't like it, we can do the code below after some modifications // to ensure that one next.Span is enough //if(hasNext) ReadNextTwoChars(pBuffer, remaining, index, out ch1, out ch2, next.Span); //else //{ // return false; //} } if (ch1 == ByteCR) { if (ch2 == ByteLF) { consumedBytes += 2; return true; } if (ch2 == -1) { consumedBytes = 0; return false; } // Headers don't end in CRLF line. RejectRequest(RequestRejectionReason.InvalidRequestHeadersNoCRLF); } var endIndex = new ReadOnlySpan<byte>(pBuffer + index, remaining).IndexOf(ByteLF); var length = 0; if (endIndex != -1) { length = endIndex + 1; var pHeader = pBuffer + index; TakeSingleHeader(pHeader, length, ref handler); } else { // Split buffers var end = Sequence.IndexOf(buffer.Slice(index), ByteLF); if (end == -1) { // Not there consumedBytes = 0; return false; } var headerSpan = PipelineExtensions.ToSpan(buffer.Slice(index, end - index + 1)); length = headerSpan.Length; fixed (byte* pHeader = &MemoryMarshal.GetReference(headerSpan)) { TakeSingleHeader(pHeader, length, ref handler); } } // Skip the reader forward past the header line index += length; consumedBytes += length; remaining -= length; } } if (buffer.TryGet(ref position, out var nextSegment)) { currentSpan = nextSegment.Span; remaining = currentSpan.Length + remaining; index = currentSpan.Length - remaining; } else { consumedBytes = 0; return false; } } } public static bool ParseResponseLine<T>(ref T handler, ref ReadOnlySequence<byte> buffer, out int consumedBytes) where T : IHttpResponseLineHandler { var line = buffer.First.Span; var lf = line.IndexOf(ByteLF); if (lf >= 0) { line = line.Slice(0, lf + 1); } else if (buffer.IsSingleSegment) { consumedBytes = 0; return false; } else { long index = Sequence.IndexOf(buffer, ByteLF); if (index < 0) { consumedBytes = 0; return false; } if (index > maxRequestLineLength) { throw new Exception("invalid response (LF too far)"); } line = line.Slice(0, lf + 1); } if (line[lf - 1] != ByteCR) { throw new Exception("invalid response (no CR)"); } Http.Version version; if (line.StartsWith(s_http11)) { version = Http.Version.Http11; } else if (line.StartsWith(s_http20)) { version = Http.Version.Http20; } else if (line.StartsWith(s_http10)) { version = Http.Version.Http10; } else { throw new Exception("invalid response (version)"); } int codeStart = line.IndexOf((byte)' ') + 1; var codeSlice = line.Slice(codeStart); if (!Utf8Parser.TryParse(codeSlice, out ushort code, out consumedBytes)) { throw new Exception("invalid response (status code)"); } var reasonStart = consumedBytes + 1; var reason = codeSlice.Slice(reasonStart, codeSlice.Length - reasonStart - 2); consumedBytes = lf + s_Eol.Length; handler.OnStatusLine(version, code, reason); return true; } [MethodImpl(MethodImplOptions.NoInlining)] private static void ReadTwoChars(ReadOnlySequence<byte> buffer, int consumedBytes, out int ch1, out int ch2) { var first = buffer.First.Span; if (first.Length - consumedBytes > 1) { ch1 = first[consumedBytes]; ch2 = first[consumedBytes + 1]; } if (buffer.Length < consumedBytes + 2) { ch1 = -1; ch2 = -1; } else { buffer = buffer.Slice(consumedBytes, 2); Span<byte> temp = stackalloc byte[2]; buffer.CopyTo(temp); ch1 = temp[0]; ch2 = temp[1]; } } // This is not needed, but I will leave it here for now, as we might need it later when optimizing //private static unsafe void ReadNextTwoChars(byte* pBuffer, int remaining, int index, out int ch1, out int ch2, ReadOnlySpan<byte> next) //{ // Debug.Assert(next.Length > 1); // Debug.Assert(remaining == 0 || remaining == 1); // if (remaining == 1) // { // ch1 = pBuffer[index]; // ch2 = next.IsEmpty ? -1 : next[0]; // } // else // { // ch1 = -1; // ch2 = -1; // if (next.Length > 0) // { // ch1 = next[0]; // if (next.Length > 1) // { // ch2 = next[1]; // } // } // } //} [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int FindEndOfName(byte* headerLine, int length) { var index = 0; var sawWhitespace = false; for (; index < length; index++) { var ch = headerLine[index]; if (ch == ByteColon) { break; } if (ch == ByteTab || ch == ByteSpace || ch == ByteCR) { sawWhitespace = true; } } if (index == length || sawWhitespace) { RejectRequestHeader(headerLine, length); } return index; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe void TakeSingleHeader<T>(byte* headerLine, int length, ref T handler) where T : IHttpHeadersHandler { // Skip CR, LF from end position var valueEnd = length - 3; var nameEnd = FindEndOfName(headerLine, length); if (headerLine[valueEnd + 2] != ByteLF) { RejectRequestHeader(headerLine, length); } if (headerLine[valueEnd + 1] != ByteCR) { RejectRequestHeader(headerLine, length); } // Skip colon from value start var valueStart = nameEnd + 1; // Ignore start whitespace for (; valueStart < valueEnd; valueStart++) { var ch = headerLine[valueStart]; if (ch != ByteTab && ch != ByteSpace && ch != ByteCR) { break; } else if (ch == ByteCR) { RejectRequestHeader(headerLine, length); } } // Check for CR in value var i = valueStart + 1; if (Contains(headerLine + i, valueEnd - i, ByteCR)) { RejectRequestHeader(headerLine, length); } // Ignore end whitespace for (; valueEnd >= valueStart; valueEnd--) { var ch = headerLine[valueEnd]; if (ch != ByteTab && ch != ByteSpace) { break; } } var nameBuffer = new ReadOnlySpan<byte>(headerLine, nameEnd); var valueBuffer = new ReadOnlySpan<byte>(headerLine + valueStart, valueEnd - valueStart + 1); handler.OnHeader(nameBuffer, valueBuffer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static unsafe bool Contains(byte* searchSpace, int length, byte value) { var i = 0; if (Vector.IsHardwareAccelerated) { // Check Vector lengths if (length - Vector<byte>.Count >= i) { var vValue = GetVector(value); do { if (!Vector<byte>.Zero.Equals(Vector.Equals(vValue, Unsafe.Read<Vector<byte>>(searchSpace + i)))) { goto found; } i += Vector<byte>.Count; } while (length - Vector<byte>.Count >= i); } } // Check remaining for CR for (; i <= length; i++) { var ch = searchSpace[i]; if (ch == value) { goto found; } } return false; found: return true; } [MethodImpl(MethodImplOptions.NoInlining)] private static bool TryGetNewLineSpan(in ReadOnlySequence<byte> buffer, out SequencePosition found) { var position = BuffersExtensions.PositionOf(buffer, ByteLF); if (position.HasValue) { // Move 1 byte past the \n found = buffer.GetPosition(1, position.Value); return true; } found = default; return false; } [MethodImpl(MethodImplOptions.NoInlining)] private unsafe ReadOnlySpan<byte> GetUnknownMethod(byte* data, int length, out int methodLength) { methodLength = 0; for (var i = 0; i < length; i++) { var ch = data[i]; if (ch == ByteSpace) { if (i == 0) { RejectRequestLine(data, length); } methodLength = i; break; } else if (!IsValidTokenChar((char)ch)) { RejectRequestLine(data, length); } } return new ReadOnlySpan<byte>(data, methodLength); } // TODO: this could be optimized by using a table private static bool IsValidTokenChar(char c) { // Determines if a character is valid as a 'token' as defined in the // HTTP spec: https://tools.ietf.org/html/rfc7230#section-3.2.6 return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' || c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~'; } private void RejectRequest(RequestRejectionReason reason) => throw BadHttpRequestException.GetException(reason); private unsafe void RejectRequestLine(byte* requestLine, int length) => throw GetInvalidRequestException(RequestRejectionReason.InvalidRequestLine, requestLine, length); private unsafe void RejectRequestHeader(byte* headerLine, int length) => throw GetInvalidRequestException(RequestRejectionReason.InvalidRequestHeader, headerLine, length); private unsafe void RejectUnknownVersion(byte* version, int length) => throw GetInvalidRequestException(RequestRejectionReason.UnrecognizedHTTPVersion, version, length); private unsafe BadHttpRequestException GetInvalidRequestException(RequestRejectionReason reason, byte* detail, int length) { string errorDetails = _showErrorDetails ? new Span<byte>(detail, length).GetAsciiStringEscaped(Constants.MaxExceptionDetailSize) : string.Empty; return BadHttpRequestException.GetException(reason, errorDetails); } public void Reset() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] static Vector<byte> GetVector(byte vectorByte) { // Vector<byte> .ctor doesn't become an intrinsic due to detection issue // However this does cause it to become an intrinsic (with additional multiply and reg->reg copy) // https://github.com/dotnet/coreclr/issues/7459#issuecomment-253965670 return Vector.AsVectorByte(new Vector<uint>(vectorByte * 0x01010101u)); } enum State : byte { ParsingName, BeforValue, ParsingValue, ArferCR, } } }
// 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.Diagnostics; using System.IO; using System.Threading; using System.Xml; using System.Text; using System.Globalization; using System.Runtime.InteropServices; using Microsoft.Build.BackEnd; using Microsoft.Build.Collections; using Microsoft.Build.Evaluation; using Microsoft.Win32.SafeHandles; using Xunit; using Xunit.Abstractions; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; namespace Microsoft.Build.UnitTests.BackEnd { public class TargetUpToDateChecker_Tests : IDisposable { private MockHost _mockHost; private readonly ITestOutputHelper _testOutputHelper; public TargetUpToDateChecker_Tests(ITestOutputHelper testOutputHelper) { _mockHost = new MockHost(); _testOutputHelper = testOutputHelper; } public void Dispose() { // Remove any temp files that have been created by each test ObjectModelHelpers.DeleteTempProjectDirectory(); ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); GC.Collect(); } [Fact] public void EmptyItemSpecInTargetInputs() { MockLogger ml = new MockLogger(); Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <MyFile Include='a.cs; b.cs; c.cs'/> </ItemGroup> <Target Name='Build' Inputs=""@(MyFile->'%(NonExistentMetadata)')"" Outputs='foo.exe'> <Message Text='Running Build target' Importance='High'/> </Target> </Project>")))); bool success = p.Build(new string[] { "Build" }, new ILogger[] { ml }); Assert.True(success); // It should have actually skipped the "Build" target since there were no inputs. ml.AssertLogDoesntContain("Running Build target"); } /// <summary> /// Verify missing output metadata does not cause errors. /// </summary> [Fact] public void EmptyItemSpecInTargetOutputs() { MockLogger ml = new MockLogger(); Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='Build' Inputs='@(TASKXML)' Outputs=""@(TASKXML->'%(OutputFile)');@(TASKXML->'%(PasFile)');""> <Message Text='Running Build target' Importance='High'/> </Target> <ItemGroup> <TASKXML Include='bcc32task.xml'> <OutputFile>bcc32task.cs</OutputFile> </TASKXML> <TASKXML Include='ccc32task.xml'> <PasFile>ccc32task.pas</PasFile> </TASKXML> </ItemGroup> </Project>")))); bool success = p.Build("Build", new ILogger[] { ml }); Assert.True(success); // It should not have skipped the "Build" target since some output metadata was missing ml.AssertLogContains("Running Build target"); ml = new MockLogger(); p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='Build' Inputs='@(TASKXML)' Outputs=""@(TASKXML->'%(OutputFile)');@(TASKXML->'%(PasFile)');""> <Message Text='Running Build target' Importance='High'/> </Target> <ItemGroup> <TASKXML Include='bcc32task.xml'> </TASKXML> <TASKXML Include='ccc32task.xml'> </TASKXML> </ItemGroup> </Project>")))); success = p.Build("Build", new ILogger[] { ml }); Assert.True(success); // It should have actually skipped the "Build" target since some output metadata was missing ml.AssertLogDoesntContain("Running Build target"); } /// <summary> /// Tests this case: /// /// <Target Name="x" /// Inputs="@(Items);c.cs" /// Outputs="@(Items->'%(Filename).dll')" /> /// /// If Items = [a.cs;b.cs], and only b.cs is out of date w/r/t its /// correlated output b.dll, then we should only build "b" incrementally. /// </summary> [Fact] public void MetaInputAndInputItemThatCorrelatesWithOutputItem() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); string inputs = "@(Items);c.cs"; string outputs = "@(Items->'%(Filename).dll')"; FileWriteInfo[] filesToAnalyze = new FileWriteInfo[] { new FileWriteInfo("a.cs", _yesterday), new FileWriteInfo("a.dll", _today), new FileWriteInfo("b.cs", _today), new FileWriteInfo("b.dll", _yesterday), new FileWriteInfo("c.cs", _twoDaysAgo) }; List<ProjectItemInstance> items = new List<ProjectItemInstance>(); items.Add(new ProjectItemInstance(project, "Items", "a.cs", project.FullPath)); items.Add(new ProjectItemInstance(project, "Items", "b.cs", project.FullPath)); ItemDictionary<ProjectItemInstance> itemsByName = new ItemDictionary<ProjectItemInstance>(); itemsByName.ImportItems(items); DependencyAnalysisResult result = PerformDependencyAnalysisTestHelper(filesToAnalyze, itemsByName, inputs, outputs); Assert.Equal(DependencyAnalysisResult.IncrementalBuild, result); // "Should only build partially." } /// <summary> /// Tests this case: /// /// <Target Name="x" /// Inputs="@(Items)" /// Outputs="@(Items->'%(Filename).dll');@(Items->'%(Filename).xml')" /> /// /// If Items = [a.cs;b.cs;c.cs], and only b.cs is out of date w/r/t its /// correlated outputs (dll or xml), then we should only build "b" incrementally. /// </summary> [Fact] public void InputItemThatCorrelatesWithMultipleTransformOutputItems() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); string inputs = "@(Items)"; string outputs = "@(Items->'%(Filename).dll');@(Items->'%(Filename).xml')"; FileWriteInfo[] filesToAnalyze = new FileWriteInfo[] { new FileWriteInfo("a.cs", _yesterday), new FileWriteInfo("a.dll", _today), new FileWriteInfo("a.xml", _today), new FileWriteInfo("b.cs", _yesterday), new FileWriteInfo("b.dll", _twoDaysAgo), new FileWriteInfo("b.xml", _today), new FileWriteInfo("c.cs", _yesterday), new FileWriteInfo("c.dll", _today), new FileWriteInfo("c.xml", _today) }; List<ProjectItemInstance> items = new List<ProjectItemInstance>(); items.Add(new ProjectItemInstance(project, "Items", "a.cs", project.FullPath)); items.Add(new ProjectItemInstance(project, "Items", "b.cs", project.FullPath)); items.Add(new ProjectItemInstance(project, "Items", "c.cs", project.FullPath)); ItemDictionary<ProjectItemInstance> itemsByName = new ItemDictionary<ProjectItemInstance>(); itemsByName.ImportItems(items); DependencyAnalysisResult result = PerformDependencyAnalysisTestHelper(filesToAnalyze, itemsByName, inputs, outputs); Assert.Equal(DependencyAnalysisResult.IncrementalBuild, result); // "Should only build partially." } /// <summary> /// Tests this case: /// /// <Target Name="x" /// Inputs="@(Items);@(MoreItems)" /// Outputs="@(Items->'%(Filename).dll');@(MoreItems->'%(Filename).xml')" /> /// /// If Items = [a.cs;b.cs;c.cs], and only b.cs is out of date w/r/t its /// correlated outputs (dll or xml), then we should only build "b" incrementally. /// </summary> [Fact] public void MultiInputItemsThatCorrelatesWithMultipleTransformOutputItems() { Console.WriteLine("MultiInputItemsThatCorrelatesWithMultipleTransformOutputItems"); ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); string inputs = "@(Items);@(MoreItems)"; string outputs = "@(Items->'%(Filename).dll');@(MoreItems->'%(Filename).xml')"; FileWriteInfo[] filesToAnalyze = new FileWriteInfo[] { new FileWriteInfo("a.cs", _yesterday), new FileWriteInfo("a.txt", _yesterday), new FileWriteInfo("a.dll", _today), new FileWriteInfo("a.xml", _today), new FileWriteInfo("b.cs", _yesterday), new FileWriteInfo("b.txt", _yesterday), new FileWriteInfo("b.dll", _twoDaysAgo), new FileWriteInfo("b.xml", _today), new FileWriteInfo("c.cs", _yesterday), new FileWriteInfo("c.txt", _yesterday), new FileWriteInfo("c.dll", _today), new FileWriteInfo("c.xml", _today) }; List<ProjectItemInstance> items = new List<ProjectItemInstance>(); items.Add(new ProjectItemInstance(project, "Items", "a.cs", project.FullPath)); items.Add(new ProjectItemInstance(project, "Items", "b.cs", project.FullPath)); items.Add(new ProjectItemInstance(project, "Items", "c.cs", project.FullPath)); items.Add(new ProjectItemInstance(project, "MoreItems", "a.txt", project.FullPath)); items.Add(new ProjectItemInstance(project, "MoreItems", "b.txt", project.FullPath)); items.Add(new ProjectItemInstance(project, "MoreItems", "c.txt", project.FullPath)); ItemDictionary<ProjectItemInstance> itemsByName = new ItemDictionary<ProjectItemInstance>(); itemsByName.ImportItems(items); ItemDictionary<ProjectItemInstance> changedTargetInputs = new ItemDictionary<ProjectItemInstance>(); ItemDictionary<ProjectItemInstance> upToDateTargetInputs = new ItemDictionary<ProjectItemInstance>(); DependencyAnalysisResult result = PerformDependencyAnalysisTestHelper(filesToAnalyze, itemsByName, inputs, outputs, out changedTargetInputs, out upToDateTargetInputs); foreach (ProjectItemInstance itemInstance in changedTargetInputs) { Console.WriteLine("Changed: {0}:{1}", itemInstance.ItemType, itemInstance.EvaluatedInclude); } Assert.Equal(DependencyAnalysisResult.IncrementalBuild, result); // "Should only build partially." // Even though they were all up to date, we still expect to see an empty marker // so that lookups can correctly *not* find items of that type Assert.True(changedTargetInputs.HasEmptyMarker("MoreItems")); } [Fact] public void InputItemsTransformedToDifferentNumberOfOutputsFewer() { Console.WriteLine("InputItemsTransformedToDifferentNumberOfOutputsFewer"); MockLogger logger = new MockLogger(); string projectText = ObjectModelHelpers.CleanupFileContents(@" <Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Foo Include=`foo.txt`><Bar>SomeMetaThing</Bar></Foo> <Foo Include=`foo1.txt`><Bar>SomeMetaThing</Bar></Foo> </ItemGroup> <Target Name=`Build` Inputs=`@(Foo)` Outputs=`@(Foo->Metadata('Bar')->Distinct())`> <Message Text=`%(Foo.Bar)` /> </Target> </Project> "); Project p = new Project(XmlReader.Create(new StringReader(projectText.Replace("`", "\"")))); Assert.True(p.Build(new string[] { "Build" }, new ILogger[] { logger })); logger.AssertLogContains("SomeMetaThing"); } [Fact] public void InputItemsTransformedToDifferentNumberOfOutputsFewer1() { Console.WriteLine("InputItemsTransformedToDifferentNumberOfOutputsFewer1"); MockLogger logger = new MockLogger(); string projectText = ObjectModelHelpers.CleanupFileContents(@" <Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Foo Include=`foo.txt`><Bar>SomeMetaThing</Bar></Foo> <Foo Include=`foo1.txt`><Bar>SomeMetaThing</Bar></Foo> </ItemGroup> <Target Name=`Build` Inputs=`@(Foo->Metadata('Bar')->Distinct())` Outputs=`@(Foo)`> <Message Text=`%(Foo.Bar)` /> </Target> </Project> "); Project p = new Project(XmlReader.Create(new StringReader(projectText.Replace("`", "\"")))); Assert.True(p.Build(new string[] { "Build" }, new ILogger[] { logger })); logger.AssertLogContains("SomeMetaThing"); } [Fact] public void InputItemsTransformedToDifferentNumberOfOutputsMore() { Console.WriteLine("InputItemsTransformedToDifferentNumberOfOutputsMore"); MockLogger logger = new MockLogger(); string projectText = ObjectModelHelpers.CleanupFileContents(@" <Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Foo Include=`foo.txt`><Bar>1;2;3;4;5;6;7;8;9</Bar></Foo> <Foo Include=`foo1.txt`><Bar>a;b;c;d;e;f;g</Bar></Foo> </ItemGroup> <Target Name=`Build` Inputs=`@(Foo)` Outputs=`@(Foo->Metadata('Bar')->Distinct())`> <Message Text=`%(Foo.Bar)` /> </Target> </Project> "); Project p = new Project(XmlReader.Create(new StringReader(projectText.Replace("`", "\"")))); Assert.True(p.Build(new string[] { "Build" }, new ILogger[] { logger })); logger.AssertLogContains("1;2;3;4;5;6;7;8;9"); logger.AssertLogContains("a;b;c;d;e;f;g"); } [Fact] public void InputItemsTransformedToDifferentNumberOfOutputsMore1() { Console.WriteLine("InputItemsTransformedToDifferentNumberOfOutputsMore1"); MockLogger logger = new MockLogger(); string projectText = ObjectModelHelpers.CleanupFileContents(@" <Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Foo Include=`foo.txt`><Bar>1;2;3;4;5;6;7;8;9</Bar></Foo> <Foo Include=`foo1.txt`><Bar>a;b;c;d;e;f;g</Bar></Foo> </ItemGroup> <Target Name=`Build` Inputs=`@(Foo->Metadata('Bar')->Distinct())` Outputs=`@(Foo)`> <Message Text=`%(Foo.Bar)` /> </Target> </Project> "); Project p = new Project(XmlReader.Create(new StringReader(projectText.Replace("`", "\"")))); Assert.True(p.Build(new string[] { "Build" }, new ILogger[] { logger })); logger.AssertLogContains("1;2;3;4;5;6;7;8;9"); logger.AssertLogContains("a;b;c;d;e;f;g"); } [Fact] public void InputItemsTransformedToDifferentNumberOfOutputsTwoWays() { Console.WriteLine("InputItemsTransformedToDifferentNumberOfOutputsTwoWays"); MockLogger logger = new MockLogger(); File.WriteAllText("foo1.txt", ""); File.WriteAllText("foo.txt", ""); Thread.Sleep(100); File.WriteAllText("1111", ""); File.WriteAllText("a", ""); string projectText = ObjectModelHelpers.CleanupFileContents(@" <Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Foo Include=`foo.txt`><Bar>1111</Bar></Foo> <Foo Include=`foo1.txt`><Bar>a</Bar></Foo> </ItemGroup> <Target Name=`Build` Inputs=`@(Foo)` Outputs=`@(Foo->Metadata('Bar'));@(Foo->'%(Filename).goo')`> <Message Text=`%(Foo.Bar)` /> </Target> </Project> "); Project p = new Project(XmlReader.Create(new StringReader(projectText.Replace("`", "\"")))); Assert.True(p.Build(new string[] { "Build" }, new ILogger[] { logger })); logger.AssertLogContains("foo.goo"); logger.AssertLogContains("foo1.goo"); File.Delete("foo1.txt"); File.Delete("foo.txt"); File.Delete("a"); File.Delete("1111"); } /// <summary> /// Ensure that items not involved in the incremental build are explicitly empty /// </summary> [Fact] public void MultiInputItemsThatCorrelatesWithMultipleTransformOutputItems2() { Console.WriteLine("MultiInputItemsThatCorrelatesWithMultipleTransformOutputItems2"); string currentDirectory = Directory.GetCurrentDirectory(); try { Directory.SetCurrentDirectory(ObjectModelHelpers.TempProjectDir); MockLogger logger = new MockLogger(); Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@" <Project InitialTargets='Setup' xmlns='msbuildnamespace'> <ItemGroup> <A Include='A' /> <B Include='B' /> </ItemGroup> <Target Name='Build' DependsOnTargets='GAFT'> <Message Text='Build: @(Outs)' /> <Message Text='Build: GAFTOutsA @(GAFTOutsA)' /> <Message Text='Build: GAFTOutsB @(GAFTOutsB)' /> </Target> <Target Name='Setup'> <WriteLinesToFile File='A' Lines='A' Overwrite='true'/> <WriteLinesToFile File='B.out' Lines='B.out' Overwrite='true'/> <Exec Command='sleep.exe 1' /> <WriteLinesToFile File='B' Lines='B' Overwrite='true'/> <WriteLinesToFile File='A.out' Lines='A.out' Overwrite='true'/> </Target> <Target Name='GAFT' Inputs='@(A);@(B)' Outputs=""@(A->'%(Filename).out');@(B->'%(Filename).out')""> <CreateItem Include=""@(A->'%(Filename).out')""> <Output TaskParameter='Include' ItemName='GAFTOutsA' /> </CreateItem> <Message Text='GAFT A:@(A)' /> <CreateItem Include=""@(B->'%(Filename).out')""> <Output TaskParameter='Include' ItemName='GAFTOutsB' /> </CreateItem> <Message Text='GAFT B:@(B)' /> </Target> </Project> ")))); p.Build(new string[] { "Build" }, new ILogger[] { logger }); // If the log contains B.out twice, then there is leakage from the parent lookup logger.AssertLogDoesntContain("B.out;B.out"); } finally { Directory.SetCurrentDirectory(currentDirectory); } } private readonly DateTime _today = DateTime.Today; private readonly DateTime _yesterday = DateTime.Today.AddTicks(-TimeSpan.TicksPerDay); private readonly DateTime _twoDaysAgo = DateTime.Today.AddTicks(-2 * TimeSpan.TicksPerDay); private class FileWriteInfo { public string Path; public DateTime LastWriteTime; public FileWriteInfo(string path, DateTime lastWriteTime) { this.Path = path; this.LastWriteTime = lastWriteTime; } } /// <summary> /// Helper method for tests of PerformDependencyAnalysis. /// The setup required here suggests that the TargetDependencyAnalyzer /// class should be refactored. /// </summary> private DependencyAnalysisResult PerformDependencyAnalysisTestHelper ( FileWriteInfo[] filesToAnalyze, ItemDictionary<ProjectItemInstance> itemsByName, string inputs, string outputs ) { ItemDictionary<ProjectItemInstance> h1 = new ItemDictionary<ProjectItemInstance>(); ItemDictionary<ProjectItemInstance> h2 = new ItemDictionary<ProjectItemInstance>(); return PerformDependencyAnalysisTestHelper(filesToAnalyze, itemsByName, inputs, outputs, out h1, out h2); } private DependencyAnalysisResult PerformDependencyAnalysisTestHelper ( FileWriteInfo[] filesToAnalyze, ItemDictionary<ProjectItemInstance> itemsByName, string inputs, string outputs, out ItemDictionary<ProjectItemInstance> changedTargetInputs, out ItemDictionary<ProjectItemInstance> upToDateTargetInputs ) { List<string> filesToDelete = new List<string>(); try { // first set the disk up for (int i = 0; i < filesToAnalyze.Length; ++i) { string path = ObjectModelHelpers.CreateFileInTempProjectDirectory(filesToAnalyze[i].Path, ""); File.SetCreationTime(path, filesToAnalyze[i].LastWriteTime); File.SetLastWriteTime(path, filesToAnalyze[i].LastWriteTime); filesToDelete.Add(path); } // Wait Thread.Sleep(50); // now create the project string unformattedProjectXml = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='Build' Inputs=""{0}"" Outputs=""{1}""> </Target> </Project>"); string projectFile = Path.Combine(ObjectModelHelpers.TempProjectDir, "temp.proj"); string formattedProjectXml = String.Format(unformattedProjectXml, inputs, outputs); File.WriteAllText(projectFile, formattedProjectXml); // Wait Thread.Sleep(50); filesToDelete.Add(projectFile); Project project = new Project(projectFile); ProjectInstance p = project.CreateProjectInstance(); // now do the dependency analysis ItemBucket itemBucket = new ItemBucket(null, null, new Lookup(itemsByName, new PropertyDictionary<ProjectPropertyInstance>()), 0); TargetUpToDateChecker analyzer = new TargetUpToDateChecker(p, p.Targets["Build"], _mockHost, BuildEventContext.Invalid); return analyzer.PerformDependencyAnalysis(itemBucket, out changedTargetInputs, out upToDateTargetInputs); } finally { // finally clean up foreach (string path in filesToDelete) { if (File.Exists(path)) File.Delete(path); } ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); } } /// <summary> /// Test comparison of inputs/outputs: up to date /// </summary> [Fact] public void TestIsAnyOutOfDate1() { IsAnyOutOfDateTestHelper ( new DateTime(2000, 1, 1), /* input1 */ new DateTime(2000, 1, 1), /* input2 */ new DateTime(2001, 1, 1), /* output1 */ new DateTime(2001, 1, 1), /* output2 */ false /* none out of date */ ); } /// <summary> /// Test comparison of inputs/outputs: first input out of date wrt second output /// </summary> [Fact] public void TestIsAnyOutOfDate2() { IsAnyOutOfDateTestHelper ( new DateTime(2002, 1, 1), /* input1 */ new DateTime(2000, 1, 1), /* input2 */ new DateTime(2003, 1, 1), /* output1 */ new DateTime(2001, 1, 1), /* output2 */ true /* some out of date */ ); } /// <summary> /// Test comparison of inputs/outputs: second input out of date wrt first output /// </summary> [Fact] public void TestIsAnyOutOfDate3() { IsAnyOutOfDateTestHelper ( new DateTime(2000, 1, 1), /* input1 */ new DateTime(2002, 1, 1), /* input2 */ new DateTime(2001, 1, 1), /* output1 */ new DateTime(2003, 1, 1), /* output2 */ true /* some out of date */ ); } /// <summary> /// Test comparison of inputs/outputs: inputs and outputs have same dates /// </summary> [Fact] public void TestIsAnyOutOfDate4() { IsAnyOutOfDateTestHelper ( new DateTime(2000, 1, 1), /* input1 */ new DateTime(2000, 1, 1), /* input2 */ new DateTime(2000, 1, 1), /* output1 */ new DateTime(2000, 1, 1), /* output2 */ false /* none out of date */ ); } /// <summary> /// Test comparison of inputs/outputs: first input missing /// </summary> [Fact] public void TestIsAnyOutOfDate5() { IsAnyOutOfDateTestHelper ( null, /* input1 */ new DateTime(2000, 1, 1), /* input2 */ new DateTime(2002, 1, 1), /* output1 */ new DateTime(2002, 1, 1), /* output2 */ true /* some out of date */ ); } /// <summary> /// Test comparison of inputs/outputs: second input missing /// </summary> [Fact] public void TestIsAnyOutOfDate6() { IsAnyOutOfDateTestHelper ( new DateTime(2000, 1, 1), /* input1 */ null, /* input2 */ new DateTime(2002, 1, 1), /* output1 */ new DateTime(2002, 1, 1), /* output2 */ true /* some out of date */ ); } /// <summary> /// Test comparison of inputs/outputs: second output missing /// </summary> [Fact] public void TestIsAnyOutOfDate7() { IsAnyOutOfDateTestHelper ( new DateTime(2000, 1, 1), /* input1 */ new DateTime(2000, 1, 1), /* input2 */ new DateTime(2002, 1, 1), /* output1 */ null, /* output2 */ true /* some out of date */ ); } /// <summary> /// Test comparison of inputs/outputs: first output missing /// </summary> [Fact] public void TestIsAnyOutOfDate8() { IsAnyOutOfDateTestHelper ( new DateTime(2000, 1, 1), /* input1 */ new DateTime(2000, 1, 1), /* input2 */ null, /* output1 */ new DateTime(2002, 1, 1), /* output2 */ true /* some out of date */ ); } /// <summary> /// Test comparison of inputs/outputs: first input and first output missing /// </summary> [Fact] public void TestIsAnyOutOfDate9() { IsAnyOutOfDateTestHelper ( null, /* input1 */ new DateTime(2000, 1, 1), /* input2 */ null, /* output1 */ new DateTime(2002, 1, 1), /* output2 */ true /* some out of date */ ); } /// <summary> /// Test comparison of inputs/outputs: one input, two outputs, input out of date /// </summary> [Fact] public void TestIsAnyOutOfDate10() { IsAnyOutOfDateTestHelper ( new DateTime(2002, 1, 1), /* input1 */ null, /* input2 */ new DateTime(2000, 1, 1), /* output1 */ new DateTime(2002, 1, 1), /* output2 */ true, /* some out of date */ true, /* include input1 */ false, /* do not include input2 */ true, /* include output1 */ true /* include output2 */ ); } /// <summary> /// Test comparison of inputs/outputs: one input, two outputs, input up to date /// </summary> [Fact] public void TestIsAnyOutOfDate11() { IsAnyOutOfDateTestHelper ( new DateTime(2000, 1, 1), /* input1 */ null, /* input2 */ new DateTime(2002, 1, 1), /* output1 */ new DateTime(2002, 1, 1), /* output2 */ false, /* none out of date */ true, /* include input1 */ false, /* do not include input2 */ true, /* include output1 */ true /* include output2 */ ); } /// <summary> /// Test comparison of inputs/outputs: two inputs, one output, inputs up to date /// </summary> [Fact] public void TestIsAnyOutOfDate12() { IsAnyOutOfDateTestHelper ( new DateTime(2000, 1, 1), /* input1 */ new DateTime(2000, 1, 1), /* input2 */ new DateTime(2002, 1, 1), /* output1 */ null, /* output2 */ false, /* none out of date */ true, /* include input1 */ true, /* include input2 */ true, /* include output1 */ false /* do not include output2 */ ); } /// <summary> /// Test comparison of inputs/outputs: two inputs, one output, second input out of date /// </summary> [Fact] public void TestIsAnyOutOfDate13() { IsAnyOutOfDateTestHelper ( new DateTime(2000, 1, 1), /* input1 */ new DateTime(2003, 1, 1), /* input2 */ new DateTime(2002, 1, 1), /* output1 */ null, /* output2 */ true, /* some out of date */ true, /* include input1 */ true, /* include input2 */ true, /* include output1 */ false /* do not include output2 */ ); } /// <summary> /// Helper method for tests of IsAnyOutOfDate. /// The setup required here suggests that the TargetDependencyAnalyzer /// class should be refactored. /// </summary> /// <param name="input1Time"></param> /// <param name="input2Time"></param> /// <param name="output1Time"></param> /// <param name="output2Time"></param> /// <param name="isUpToDate"></param> private void IsAnyOutOfDateTestHelper ( DateTime? input1Time, DateTime? input2Time, DateTime? output1Time, DateTime? output2Time, bool isUpToDate ) { IsAnyOutOfDateTestHelper(input1Time, input2Time, output1Time, output2Time, isUpToDate, true, true, true, true); } /// <summary> /// Helper method for tests of IsAnyOutOfDate. /// The setup required here suggests that the TargetDependencyAnalyzer /// class should be refactored. /// </summary> /// <param name="input1Time"></param> /// <param name="input2Time"></param> /// <param name="output1Time"></param> /// <param name="output2Time"></param> /// <param name="isUpToDate"></param> private void IsAnyOutOfDateTestHelper ( DateTime? input1Time, DateTime? input2Time, DateTime? output1Time, DateTime? output2Time, bool expectedAnyOutOfDate, bool includeInput1, bool includeInput2, bool includeOutput1, bool includeOutput2 ) { List<string> inputs = new List<string>(); List<string> outputs = new List<string>(); string input1 = "NONEXISTENT_FILE"; string input2 = "NONEXISTENT_FILE"; string output1 = "NONEXISTENT_FILE"; string output2 = "NONEXISTENT_FILE"; try { if (input1Time != null) { input1 = FileUtilities.GetTemporaryFile(); File.WriteAllText(input1, String.Empty); File.SetLastWriteTime(input1, (DateTime)input1Time); } if (input2Time != null) { input2 = FileUtilities.GetTemporaryFile(); File.WriteAllText(input2, String.Empty); File.SetLastWriteTime(input2, (DateTime)input2Time); } if (output1Time != null) { output1 = FileUtilities.GetTemporaryFile(); File.WriteAllText(output1, String.Empty); File.SetLastWriteTime(output1, (DateTime)output1Time); } if (output2Time != null) { output2 = FileUtilities.GetTemporaryFile(); File.WriteAllText(output2, String.Empty); File.SetLastWriteTime(output2, (DateTime)output2Time); } if (includeInput1) inputs.Add(input1); if (includeInput2) inputs.Add(input2); if (includeOutput1) outputs.Add(output1); if (includeOutput2) outputs.Add(output2); DependencyAnalysisLogDetail detail; Assert.Equal(expectedAnyOutOfDate, TargetUpToDateChecker.IsAnyOutOfDate(out detail, Directory.GetCurrentDirectory(), inputs, outputs)); } finally { if (File.Exists(input1)) File.Delete(input1); if (File.Exists(input2)) File.Delete(input2); if (File.Exists(output1)) File.Delete(output1); if (File.Exists(output2)) File.Delete(output2); } } private static readonly DateTime Old = new DateTime(2000, 1, 1); private static readonly DateTime Middle = new DateTime(2001, 1, 1); private static readonly DateTime New = new DateTime(2002, 1, 1); [Fact(Skip = "Creating a symlink on Windows requires elevation.")] public void NewSymlinkOldDestinationIsUpToDate() { SimpleSymlinkInputCheck(symlinkWriteTime: New, targetWriteTime: Old, outputWriteTime: Middle, expectedOutOfDate: false); } [Fact(Skip = "Creating a symlink on Windows requires elevation.")] public void OldSymlinkOldDestinationIsUpToDate() { SimpleSymlinkInputCheck(symlinkWriteTime: Old, targetWriteTime: Middle, outputWriteTime: New, expectedOutOfDate: false); } [Fact(Skip = "Creating a symlink on Windows requires elevation.")] public void OldSymlinkNewDestinationIsNotUpToDate() { SimpleSymlinkInputCheck(symlinkWriteTime: Old, targetWriteTime: New, outputWriteTime: Middle, expectedOutOfDate: true); } [Fact(Skip = "Creating a symlink on Windows requires elevation.")] public void NewSymlinkNewDestinationIsNotUpToDate() { SimpleSymlinkInputCheck(symlinkWriteTime: Middle, targetWriteTime: Middle, outputWriteTime: Old, expectedOutOfDate: true); } [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, UInt32 dwFlags); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetFileTime(SafeFileHandle hFile, ref long creationTime, ref long lastAccessTime, ref long lastWriteTime); private void SimpleSymlinkInputCheck(DateTime symlinkWriteTime, DateTime targetWriteTime, DateTime outputWriteTime, bool expectedOutOfDate) { var inputs = new List<string>(); var outputs = new List<string>(); string inputTarget = "NONEXISTENT_FILE"; string inputSymlink = "NONEXISTENT_FILE"; string outputTarget = "NONEXISTENT_FILE"; try { inputTarget = FileUtilities.GetTemporaryFile(); _testOutputHelper.WriteLine($"Created input file {inputTarget}"); File.SetLastWriteTime(inputTarget, targetWriteTime); inputSymlink = FileUtilities.GetTemporaryFile(null, ".linkin", createFile: false); if (!CreateSymbolicLink(inputSymlink, inputTarget, 0)) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } // File.SetLastWriteTime on the symlink sets the target write time, // so set the symlink's write time the hard way using (SafeFileHandle handle = NativeMethodsShared.CreateFile( inputSymlink, NativeMethodsShared.GENERIC_READ | 0x100 /* FILE_WRITE_ATTRIBUTES */, NativeMethodsShared.FILE_SHARE_READ, IntPtr.Zero, NativeMethodsShared.OPEN_EXISTING, NativeMethodsShared.FILE_ATTRIBUTE_NORMAL | NativeMethodsShared.FILE_FLAG_OPEN_REPARSE_POINT, IntPtr.Zero)) { if (handle.IsInvalid) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } long symlinkWriteTimeTicks = symlinkWriteTime.ToFileTimeUtc(); if (SetFileTime(handle, ref symlinkWriteTimeTicks, ref symlinkWriteTimeTicks, ref symlinkWriteTimeTicks) != true) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } } _testOutputHelper.WriteLine($"Created input link {inputSymlink}"); outputTarget = FileUtilities.GetTemporaryFile(); _testOutputHelper.WriteLine($"Created output file {outputTarget}"); File.SetLastWriteTime(outputTarget, outputWriteTime); inputs.Add(inputSymlink); outputs.Add(outputTarget); DependencyAnalysisLogDetail detail; Assert.Equal(expectedOutOfDate, TargetUpToDateChecker.IsAnyOutOfDate(out detail, Directory.GetCurrentDirectory(), inputs, outputs)); } finally { if (File.Exists(inputTarget)) File.Delete(inputTarget); if (File.Exists(inputSymlink)) File.Delete(inputSymlink); if (File.Exists(outputTarget)) File.Delete(outputTarget); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using PylonC.NETSupportLibrary; using PylonC.NET; namespace PylonC.NETSupportLibrary { /* Displays a combo box with the data of a GenICam enumeration and the name of the node. */ public partial class EnumerationComboBoxUserControl : UserControl { private string name = "ValueName"; /* The name of the node. */ private ImageProvider m_imageProvider = null; /* The image provider providing the node handle and status events. */ private NODE_HANDLE m_hNode = new NODE_HANDLE(); /* The handle of the node. */ private NODE_CALLBACK_HANDLE m_hCallbackHandle = new NODE_CALLBACK_HANDLE(); /* The handle of the node callback. */ private NodeCallbackHandler m_nodeCallbackHandler = new NodeCallbackHandler(); /* The callback handler. */ /* Used for connecting an image provider providing the node handle and status events. */ public ImageProvider MyImageProvider { set { m_imageProvider = value; /* Image provider has been connected. */ if (m_imageProvider != null) { /* Register for the events of the image provider needed for proper operation. */ m_imageProvider.DeviceOpenedEvent += new ImageProvider.DeviceOpenedEventHandler(DeviceOpenedEventHandler); m_imageProvider.DeviceClosingEvent += new ImageProvider.DeviceClosingEventHandler(DeviceClosingEventHandler); /* Update the control values. */ UpdateValues(); } else /* Image provider has been disconnected. */ { Reset(); } } } [Description("The GenICam node name representing an enumeration, e.g. TestImageSelector. The pylon Viewer tool feature tree can be used to get the name and the type of a node.")] public string NodeName { get { return name; } set { name = value; labelName.Text = name + ":"; } } /* A device has been opened. Update the control. */ private void DeviceOpenedEventHandler() { if (InvokeRequired) { /* If called from a different thread, we must use the Invoke method to marshal the call to the proper thread. */ BeginInvoke(new ImageProvider.DeviceOpenedEventHandler(DeviceOpenedEventHandler)); return; } try { /* Get the node. */ m_hNode = m_imageProvider.GetNodeFromDevice(name); /* Register for changes. */ m_hCallbackHandle = GenApi.NodeRegisterCallback(m_hNode, m_nodeCallbackHandler); /* Update the displayed name. */ labelName.Text = GenApi.NodeGetDisplayName(m_hNode) + ":"; /* Update the control values. */ UpdateValues(); } catch { /* If errors occurred disable the control. */ Reset(); } } /* The device has been closed. Update the control. */ private void DeviceClosingEventHandler() { if (InvokeRequired) { /* If called from a different thread, we must use the Invoke method to marshal the call to the proper thread. */ BeginInvoke(new ImageProvider.DeviceRemovedEventHandler(DeviceClosingEventHandler)); return; } Reset(); } /* The node state has changed. Update the control. */ private void NodeCallbackEventHandler(NODE_HANDLE handle) { if (InvokeRequired) { /* If called from a different thread, we must use the Invoke method to marshal the call to the proper thread. */ BeginInvoke(new NodeCallbackHandler.NodeCallback(NodeCallbackEventHandler), handle); return; } if (handle.Equals(m_hNode)) { /* Update the control values. */ UpdateValues(); } } /* Deactivate the control and deregister the callback. */ private void Reset() { if (m_hNode.IsValid && m_hCallbackHandle.IsValid) { try { GenApi.NodeDeregisterCallback(m_hNode, m_hCallbackHandle); } catch { /* Ignore. The control is about to be disabled. */ } } m_hNode.SetInvalid(); m_hCallbackHandle.SetInvalid(); comboBox.Enabled = false; labelName.Enabled = false; } /* Get the current values from the node and display them. */ private void UpdateValues() { try { if (m_hNode.IsValid) { if (GenApi.NodeGetType(m_hNode) == EGenApiNodeType.EnumerationNode) /* Check is proper node type. */ { /* Check is writable. */ bool writable = GenApi.NodeIsWritable(m_hNode); /* Get the number of enumeration values. */ uint itemCount = GenApi.EnumerationGetNumEntries(m_hNode); /* Clear the combo box. */ comboBox.Items.Clear(); /* Get all enumeration values, add them to the combo box, and set the selected item. */ string selected = GenApi.NodeToString(m_hNode); for (uint i = 0; i < itemCount; i++) { NODE_HANDLE hEntry = GenApi.EnumerationGetEntryByIndex(m_hNode, i); if (GenApi.NodeIsAvailable(hEntry)) { comboBox.Items.Add(GenApi.NodeGetDisplayName(hEntry)); if (selected == GenApi.EnumerationEntryGetSymbolic(hEntry)) { comboBox.SelectedIndex = comboBox.Items.Count - 1; } } } /* Update accessibility. */ comboBox.Enabled = writable; labelName.Enabled = writable; return; } } } catch { /* If errors occurred disable the control. */ } Reset(); } /* Set up the initial state. */ public EnumerationComboBoxUserControl() { InitializeComponent(); m_nodeCallbackHandler.CallbackEvent += new NodeCallbackHandler.NodeCallback(NodeCallbackEventHandler); Reset(); } /* Handle selection changes. */ private void comboBox_SelectedIndexChanged(object sender, EventArgs e) { if (m_hNode.IsValid) { try { /* If writable and combo box selection ok. */ if (GenApi.NodeIsAvailable(m_hNode) && comboBox.SelectedIndex >= 0) { /* Get the displayed selected enumeration value. */ string selectedDisplayName = comboBox.GetItemText(comboBox.Items[comboBox.SelectedIndex]); /* Get the number of enumeration values. */ uint itemCount = GenApi.EnumerationGetNumEntries(m_hNode); /* Determine the symbolic name of the selected item and set it if different. */ for (uint i = 0; i < itemCount; i++) { NODE_HANDLE hEntry = GenApi.EnumerationGetEntryByIndex(m_hNode, i); if (GenApi.NodeIsAvailable(hEntry)) { if (GenApi.NodeGetDisplayName(hEntry) == selectedDisplayName) { /* Get the value to set. */ string value = GenApi.EnumerationEntryGetSymbolic(hEntry); /* Set the value if other than the current value of the node. */ if (GenApi.NodeToString(m_hNode) != value) { GenApi.NodeFromString(m_hNode, value); } } } } } } catch { /* Ignore any errors here. */ } } } } }
/* * 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.Data; using System.Reflection; using OpenSim.Data; using OpenSim.Framework; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenMetaverse.StructuredData; using log4net; namespace OpenSim.Data.MySQL { public class UserProfilesData: IProfilesData { static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #region Properites string ConnectionString { get; set; } protected virtual Assembly Assembly { get { return GetType().Assembly; } } #endregion Properties #region class Member Functions public UserProfilesData(string connectionString) { ConnectionString = connectionString; Init(); } void Init() { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); Migration m = new Migration(dbcon, Assembly, "UserProfiles"); m.Update(); } } #endregion Member Functions #region Classifieds Queries /// <summary> /// Gets the classified records. /// </summary> /// <returns> /// Array of classified records /// </returns> /// <param name='creatorId'> /// Creator identifier. /// </param> public OSDArray GetClassifiedRecords(UUID creatorId) { OSDArray data = new OSDArray(); using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { string query = "SELECT classifieduuid, name FROM classifieds WHERE creatoruuid = ?Id"; dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", creatorId); using( MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default)) { if(reader.HasRows) { while (reader.Read()) { OSDMap n = new OSDMap(); UUID Id = UUID.Zero; string Name = null; try { UUID.TryParse(Convert.ToString( reader["classifieduuid"]), out Id); Name = Convert.ToString(reader["name"]); } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": UserAccount exception {0}", e.Message); } n.Add("classifieduuid", OSD.FromUUID(Id)); n.Add("name", OSD.FromString(Name)); data.Add(n); } } } } } return data; } public bool UpdateClassifiedRecord(UserClassifiedAdd ad, ref string result) { string query = string.Empty; query += "INSERT INTO classifieds ("; query += "`classifieduuid`,"; query += "`creatoruuid`,"; query += "`creationdate`,"; query += "`expirationdate`,"; query += "`category`,"; query += "`name`,"; query += "`description`,"; query += "`parceluuid`,"; query += "`parentestate`,"; query += "`snapshotuuid`,"; query += "`simname`,"; query += "`posglobal`,"; query += "`parcelname`,"; query += "`classifiedflags`,"; query += "`priceforlisting`) "; query += "VALUES ("; query += "?ClassifiedId,"; query += "?CreatorId,"; query += "?CreatedDate,"; query += "?ExpirationDate,"; query += "?Category,"; query += "?Name,"; query += "?Description,"; query += "?ParcelId,"; query += "?ParentEstate,"; query += "?SnapshotId,"; query += "?SimName,"; query += "?GlobalPos,"; query += "?ParcelName,"; query += "?Flags,"; query += "?ListingPrice ) "; query += "ON DUPLICATE KEY UPDATE "; query += "category=?Category, "; query += "expirationdate=?ExpirationDate, "; query += "name=?Name, "; query += "description=?Description, "; query += "parentestate=?ParentEstate, "; query += "posglobal=?GlobalPos, "; query += "parcelname=?ParcelName, "; query += "classifiedflags=?Flags, "; query += "priceforlisting=?ListingPrice, "; query += "snapshotuuid=?SnapshotId"; if(string.IsNullOrEmpty(ad.ParcelName)) ad.ParcelName = "Unknown"; if(ad.ParcelId == null) ad.ParcelId = UUID.Zero; if(string.IsNullOrEmpty(ad.Description)) ad.Description = "No Description"; DateTime epoch = new DateTime(1970, 1, 1); DateTime now = DateTime.Now; TimeSpan epochnow = now - epoch; TimeSpan duration; DateTime expiration; TimeSpan epochexp; if(ad.Flags == 2) { duration = new TimeSpan(7,0,0,0); expiration = now.Add(duration); epochexp = expiration - epoch; } else { duration = new TimeSpan(365,0,0,0); expiration = now.Add(duration); epochexp = expiration - epoch; } ad.CreationDate = (int)epochnow.TotalSeconds; ad.ExpirationDate = (int)epochexp.TotalSeconds; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?ClassifiedId", ad.ClassifiedId.ToString()); cmd.Parameters.AddWithValue("?CreatorId", ad.CreatorId.ToString()); cmd.Parameters.AddWithValue("?CreatedDate", ad.CreationDate.ToString()); cmd.Parameters.AddWithValue("?ExpirationDate", ad.ExpirationDate.ToString()); cmd.Parameters.AddWithValue("?Category", ad.Category.ToString()); cmd.Parameters.AddWithValue("?Name", ad.Name.ToString()); cmd.Parameters.AddWithValue("?Description", ad.Description.ToString()); cmd.Parameters.AddWithValue("?ParcelId", ad.ParcelId.ToString()); cmd.Parameters.AddWithValue("?ParentEstate", ad.ParentEstate.ToString()); cmd.Parameters.AddWithValue("?SnapshotId", ad.SnapshotId.ToString ()); cmd.Parameters.AddWithValue("?SimName", ad.SimName.ToString()); cmd.Parameters.AddWithValue("?GlobalPos", ad.GlobalPos.ToString()); cmd.Parameters.AddWithValue("?ParcelName", ad.ParcelName.ToString()); cmd.Parameters.AddWithValue("?Flags", ad.Flags.ToString()); cmd.Parameters.AddWithValue("?ListingPrice", ad.Price.ToString ()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": ClassifiedesUpdate exception {0}", e.Message); result = e.Message; return false; } return true; } public bool DeleteClassifiedRecord(UUID recordId) { string query = string.Empty; query += "DELETE FROM classifieds WHERE "; query += "classifieduuid = ?recordId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?recordId", recordId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": DeleteClassifiedRecord exception {0}", e.Message); return false; } return true; } public bool GetClassifiedInfo(ref UserClassifiedAdd ad, ref string result) { string query = string.Empty; query += "SELECT * FROM classifieds WHERE "; query += "classifieduuid = ?AdId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?AdId", ad.ClassifiedId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader()) { if(reader.Read ()) { ad.CreatorId = new UUID(reader.GetGuid("creatoruuid")); ad.ParcelId = new UUID(reader.GetGuid("parceluuid")); ad.SnapshotId = new UUID(reader.GetGuid("snapshotuuid")); ad.CreationDate = Convert.ToInt32(reader["creationdate"]); ad.ExpirationDate = Convert.ToInt32(reader["expirationdate"]); ad.ParentEstate = Convert.ToInt32(reader["parentestate"]); ad.Flags = (byte)reader.GetUInt32("classifiedflags"); ad.Category = reader.GetInt32("category"); ad.Price = reader.GetInt16("priceforlisting"); ad.Name = reader.GetString("name"); ad.Description = reader.GetString("description"); ad.SimName = reader.GetString("simname"); ad.GlobalPos = reader.GetString("posglobal"); ad.ParcelName = reader.GetString("parcelname"); } } } dbcon.Close(); } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": GetPickInfo exception {0}", e.Message); } return true; } #endregion Classifieds Queries #region Picks Queries public OSDArray GetAvatarPicks(UUID avatarId) { string query = string.Empty; query += "SELECT `pickuuid`,`name` FROM userpicks WHERE "; query += "creatoruuid = ?Id"; OSDArray data = new OSDArray(); try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", avatarId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader()) { if(reader.HasRows) { while (reader.Read()) { OSDMap record = new OSDMap(); record.Add("pickuuid",OSD.FromString((string)reader["pickuuid"])); record.Add("name",OSD.FromString((string)reader["name"])); data.Add(record); } } } } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": GetAvatarPicks exception {0}", e.Message); } return data; } public UserProfilePick GetPickInfo(UUID avatarId, UUID pickId) { string query = string.Empty; UserProfilePick pick = new UserProfilePick(); query += "SELECT * FROM userpicks WHERE "; query += "creatoruuid = ?CreatorId AND "; query += "pickuuid = ?PickId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?CreatorId", avatarId.ToString()); cmd.Parameters.AddWithValue("?PickId", pickId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader()) { if(reader.HasRows) { reader.Read(); string description = (string)reader["description"]; if (string.IsNullOrEmpty(description)) description = "No description given."; UUID.TryParse((string)reader["pickuuid"], out pick.PickId); UUID.TryParse((string)reader["creatoruuid"], out pick.CreatorId); UUID.TryParse((string)reader["parceluuid"], out pick.ParcelId); UUID.TryParse((string)reader["snapshotuuid"], out pick.SnapshotId); pick.GlobalPos = (string)reader["posglobal"]; pick.Gatekeeper = (string)reader["gatekeeper"]; bool.TryParse((string)reader["toppick"], out pick.TopPick); bool.TryParse((string)reader["enabled"], out pick.Enabled); pick.Name = (string)reader["name"]; pick.Desc = description; pick.ParcelName = (string)reader["user"]; pick.OriginalName = (string)reader["originalname"]; pick.SimName = (string)reader["simname"]; pick.SortOrder = (int)reader["sortorder"]; } } } dbcon.Close(); } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": GetPickInfo exception {0}", e.Message); } return pick; } public bool UpdatePicksRecord(UserProfilePick pick) { string query = string.Empty; query += "INSERT INTO userpicks VALUES ("; query += "?PickId,"; query += "?CreatorId,"; query += "?TopPick,"; query += "?ParcelId,"; query += "?Name,"; query += "?Desc,"; query += "?SnapshotId,"; query += "?User,"; query += "?Original,"; query += "?SimName,"; query += "?GlobalPos,"; query += "?SortOrder,"; query += "?Enabled,"; query += "?Gatekeeper)"; query += "ON DUPLICATE KEY UPDATE "; query += "parceluuid=?ParcelId,"; query += "name=?Name,"; query += "description=?Desc,"; query += "user=?User,"; query += "simname=?SimName,"; query += "snapshotuuid=?SnapshotId,"; query += "pickuuid=?PickId,"; query += "posglobal=?GlobalPos,"; query += "gatekeeper=?Gatekeeper"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?PickId", pick.PickId.ToString()); cmd.Parameters.AddWithValue("?CreatorId", pick.CreatorId.ToString()); cmd.Parameters.AddWithValue("?TopPick", pick.TopPick.ToString()); cmd.Parameters.AddWithValue("?ParcelId", pick.ParcelId.ToString()); cmd.Parameters.AddWithValue("?Name", pick.Name.ToString()); cmd.Parameters.AddWithValue("?Desc", pick.Desc.ToString()); cmd.Parameters.AddWithValue("?SnapshotId", pick.SnapshotId.ToString()); cmd.Parameters.AddWithValue("?User", pick.ParcelName.ToString()); cmd.Parameters.AddWithValue("?Original", pick.OriginalName.ToString()); cmd.Parameters.AddWithValue("?SimName",pick.SimName.ToString()); cmd.Parameters.AddWithValue("?GlobalPos", pick.GlobalPos); cmd.Parameters.AddWithValue("?Gatekeeper",pick.Gatekeeper); cmd.Parameters.AddWithValue("?SortOrder", pick.SortOrder.ToString ()); cmd.Parameters.AddWithValue("?Enabled", pick.Enabled.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": UpdateAvatarNotes exception {0}", e.Message); return false; } return true; } public bool DeletePicksRecord(UUID pickId) { string query = string.Empty; query += "DELETE FROM userpicks WHERE "; query += "pickuuid = ?PickId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?PickId", pickId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": DeleteUserPickRecord exception {0}", e.Message); return false; } return true; } #endregion Picks Queries #region Avatar Notes Queries public bool GetAvatarNotes(ref UserProfileNotes notes) { // WIP string query = string.Empty; query += "SELECT `notes` FROM usernotes WHERE "; query += "useruuid = ?Id AND "; query += "targetuuid = ?TargetId"; OSDArray data = new OSDArray(); try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", notes.UserId.ToString()); cmd.Parameters.AddWithValue("?TargetId", notes.TargetId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { reader.Read(); notes.Notes = OSD.FromString((string)reader["notes"]); } else { notes.Notes = OSD.FromString(""); } } } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": GetAvatarNotes exception {0}", e.Message); } return true; } public bool UpdateAvatarNotes(ref UserProfileNotes note, ref string result) { string query = string.Empty; bool remove; if(string.IsNullOrEmpty(note.Notes)) { remove = true; query += "DELETE FROM usernotes WHERE "; query += "useruuid=?UserId AND "; query += "targetuuid=?TargetId"; } else { remove = false; query += "INSERT INTO usernotes VALUES ( "; query += "?UserId,"; query += "?TargetId,"; query += "?Notes )"; query += "ON DUPLICATE KEY "; query += "UPDATE "; query += "notes=?Notes"; } try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { if(!remove) cmd.Parameters.AddWithValue("?Notes", note.Notes); cmd.Parameters.AddWithValue("?TargetId", note.TargetId.ToString ()); cmd.Parameters.AddWithValue("?UserId", note.UserId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": UpdateAvatarNotes exception {0}", e.Message); return false; } return true; } #endregion Avatar Notes Queries #region Avatar Properties public bool GetAvatarProperties(ref UserProfileProperties props, ref string result) { string query = string.Empty; query += "SELECT * FROM userprofile WHERE "; query += "useruuid = ?Id"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", props.UserId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { reader.Read(); props.WebUrl = (string)reader["profileURL"]; UUID.TryParse((string)reader["profileImage"], out props.ImageId); props.AboutText = (string)reader["profileAboutText"]; UUID.TryParse((string)reader["profileFirstImage"], out props.FirstLifeImageId); props.FirstLifeText = (string)reader["profileFirstText"]; UUID.TryParse((string)reader["profilePartner"], out props.PartnerId); props.WantToMask = (int)reader["profileWantToMask"]; props.WantToText = (string)reader["profileWantToText"]; props.SkillsMask = (int)reader["profileSkillsMask"]; props.SkillsText = (string)reader["profileSkillsText"]; props.Language = (string)reader["profileLanguages"]; } else { props.WebUrl = string.Empty; props.ImageId = UUID.Zero; props.AboutText = string.Empty; props.FirstLifeImageId = UUID.Zero; props.FirstLifeText = string.Empty; props.PartnerId = UUID.Zero; props.WantToMask = 0; props.WantToText = string.Empty; props.SkillsMask = 0; props.SkillsText = string.Empty; props.Language = string.Empty; props.PublishProfile = false; props.PublishMature = false; query = "INSERT INTO userprofile ("; query += "useruuid, "; query += "profilePartner, "; query += "profileAllowPublish, "; query += "profileMaturePublish, "; query += "profileURL, "; query += "profileWantToMask, "; query += "profileWantToText, "; query += "profileSkillsMask, "; query += "profileSkillsText, "; query += "profileLanguages, "; query += "profileImage, "; query += "profileAboutText, "; query += "profileFirstImage, "; query += "profileFirstText) VALUES ("; query += "?userId, "; query += "?profilePartner, "; query += "?profileAllowPublish, "; query += "?profileMaturePublish, "; query += "?profileURL, "; query += "?profileWantToMask, "; query += "?profileWantToText, "; query += "?profileSkillsMask, "; query += "?profileSkillsText, "; query += "?profileLanguages, "; query += "?profileImage, "; query += "?profileAboutText, "; query += "?profileFirstImage, "; query += "?profileFirstText)"; dbcon.Close(); dbcon.Open(); using (MySqlCommand put = new MySqlCommand(query, dbcon)) { put.Parameters.AddWithValue("?userId", props.UserId.ToString()); put.Parameters.AddWithValue("?profilePartner", props.PartnerId.ToString()); put.Parameters.AddWithValue("?profileAllowPublish", props.PublishProfile); put.Parameters.AddWithValue("?profileMaturePublish", props.PublishMature); put.Parameters.AddWithValue("?profileURL", props.WebUrl); put.Parameters.AddWithValue("?profileWantToMask", props.WantToMask); put.Parameters.AddWithValue("?profileWantToText", props.WantToText); put.Parameters.AddWithValue("?profileSkillsMask", props.SkillsMask); put.Parameters.AddWithValue("?profileSkillsText", props.SkillsText); put.Parameters.AddWithValue("?profileLanguages", props.Language); put.Parameters.AddWithValue("?profileImage", props.ImageId.ToString()); put.Parameters.AddWithValue("?profileAboutText", props.AboutText); put.Parameters.AddWithValue("?profileFirstImage", props.FirstLifeImageId.ToString()); put.Parameters.AddWithValue("?profileFirstText", props.FirstLifeText); put.ExecuteNonQuery(); } } } } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": Requst properties exception {0}", e.Message); result = e.Message; return false; } return true; } public bool UpdateAvatarProperties(ref UserProfileProperties props, ref string result) { string query = string.Empty; query += "UPDATE userprofile SET "; query += "profileURL=?profileURL, "; query += "profileImage=?image, "; query += "profileAboutText=?abouttext,"; query += "profileFirstImage=?firstlifeimage,"; query += "profileFirstText=?firstlifetext "; query += "WHERE useruuid=?uuid"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?profileURL", props.WebUrl); cmd.Parameters.AddWithValue("?image", props.ImageId.ToString()); cmd.Parameters.AddWithValue("?abouttext", props.AboutText); cmd.Parameters.AddWithValue("?firstlifeimage", props.FirstLifeImageId.ToString()); cmd.Parameters.AddWithValue("?firstlifetext", props.FirstLifeText); cmd.Parameters.AddWithValue("?uuid", props.UserId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": AgentPropertiesUpdate exception {0}", e.Message); return false; } return true; } #endregion Avatar Properties #region Avatar Interests public bool UpdateAvatarInterests(UserProfileProperties up, ref string result) { string query = string.Empty; query += "UPDATE userprofile SET "; query += "profileWantToMask=?WantMask, "; query += "profileWantToText=?WantText,"; query += "profileSkillsMask=?SkillsMask,"; query += "profileSkillsText=?SkillsText, "; query += "profileLanguages=?Languages "; query += "WHERE useruuid=?uuid"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?WantMask", up.WantToMask); cmd.Parameters.AddWithValue("?WantText", up.WantToText); cmd.Parameters.AddWithValue("?SkillsMask", up.SkillsMask); cmd.Parameters.AddWithValue("?SkillsText", up.SkillsText); cmd.Parameters.AddWithValue("?Languages", up.Language); cmd.Parameters.AddWithValue("?uuid", up.UserId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": AgentInterestsUpdate exception {0}", e.Message); result = e.Message; return false; } return true; } #endregion Avatar Interests public OSDArray GetUserImageAssets(UUID avatarId) { OSDArray data = new OSDArray(); string query = "SELECT `snapshotuuid` FROM {0} WHERE `creatoruuid` = ?Id"; // Get classified image assets try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(string.Format (query,"`classifieds`"), dbcon)) { cmd.Parameters.AddWithValue("?Id", avatarId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { while (reader.Read()) { data.Add(new OSDString((string)reader["snapshotuuid"].ToString ())); } } } } dbcon.Close(); dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(string.Format (query,"`userpicks`"), dbcon)) { cmd.Parameters.AddWithValue("?Id", avatarId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { while (reader.Read()) { data.Add(new OSDString((string)reader["snapshotuuid"].ToString ())); } } } } dbcon.Close(); dbcon.Open(); query = "SELECT `profileImage`, `profileFirstImage` FROM `userprofile` WHERE `useruuid` = ?Id"; using (MySqlCommand cmd = new MySqlCommand(string.Format (query,"`userpicks`"), dbcon)) { cmd.Parameters.AddWithValue("?Id", avatarId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { while (reader.Read()) { data.Add(new OSDString((string)reader["profileImage"].ToString ())); data.Add(new OSDString((string)reader["profileFirstImage"].ToString ())); } } } } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": GetAvatarNotes exception {0}", e.Message); } return data; } #region User Preferences public bool GetUserPreferences(ref UserPreferences pref, ref string result) { string query = string.Empty; query += "SELECT imviaemail,visible,email FROM "; query += "usersettings WHERE "; query += "useruuid = ?Id"; OSDArray data = new OSDArray(); try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", pref.UserId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader()) { if(reader.HasRows) { reader.Read(); bool.TryParse((string)reader["imviaemail"], out pref.IMViaEmail); bool.TryParse((string)reader["visible"], out pref.Visible); pref.EMail = (string)reader["email"]; } else { dbcon.Close(); dbcon.Open(); query = "INSERT INTO usersettings VALUES "; query += "(?uuid,'false','false', ?Email)"; using (MySqlCommand put = new MySqlCommand(query, dbcon)) { put.Parameters.AddWithValue("?Email", pref.EMail); put.Parameters.AddWithValue("?uuid", pref.UserId.ToString()); put.ExecuteNonQuery(); } } } } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": Get preferences exception {0}", e.Message); result = e.Message; return false; } return true; } public bool UpdateUserPreferences(ref UserPreferences pref, ref string result) { string query = string.Empty; query += "UPDATE usersettings SET "; query += "imviaemail=?ImViaEmail, "; query += "visible=?Visible, "; query += "email=?EMail "; query += "WHERE useruuid=?uuid"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?ImViaEmail", pref.IMViaEmail.ToString().ToLower()); cmd.Parameters.AddWithValue("?Visible", pref.Visible.ToString().ToLower()); cmd.Parameters.AddWithValue("?uuid", pref.UserId.ToString()); cmd.Parameters.AddWithValue("?EMail", pref.EMail.ToString().ToLower()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": UserPreferencesUpdate exception {0} {1}", e.Message, e.InnerException); result = e.Message; return false; } return true; } #endregion User Preferences #region Integration public bool GetUserAppData(ref UserAppData props, ref string result) { string query = string.Empty; query += "SELECT * FROM `userdata` WHERE "; query += "UserId = ?Id AND "; query += "TagId = ?TagId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", props.UserId.ToString()); cmd.Parameters.AddWithValue ("?TagId", props.TagId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { reader.Read(); props.DataKey = (string)reader["DataKey"]; props.DataVal = (string)reader["DataVal"]; } else { query += "INSERT INTO userdata VALUES ( "; query += "?UserId,"; query += "?TagId,"; query += "?DataKey,"; query += "?DataVal) "; using (MySqlCommand put = new MySqlCommand(query, dbcon)) { put.Parameters.AddWithValue("?UserId", props.UserId.ToString()); put.Parameters.AddWithValue("?TagId", props.TagId.ToString()); put.Parameters.AddWithValue("?DataKey", props.DataKey.ToString()); put.Parameters.AddWithValue("?DataVal", props.DataVal.ToString()); put.ExecuteNonQuery(); } } } } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": Requst application data exception {0}", e.Message); result = e.Message; return false; } return true; } public bool SetUserAppData(UserAppData props, ref string result) { string query = string.Empty; query += "UPDATE userdata SET "; query += "TagId = ?TagId, "; query += "DataKey = ?DataKey, "; query += "DataVal = ?DataVal WHERE "; query += "UserId = ?UserId AND "; query += "TagId = ?TagId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?UserId", props.UserId.ToString()); cmd.Parameters.AddWithValue("?TagId", props.TagId.ToString()); cmd.Parameters.AddWithValue("?DataKey", props.DataKey.ToString()); cmd.Parameters.AddWithValue("?DataVal", props.DataKey.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.ErrorFormat("[PROFILES_DATA]" + ": SetUserData exception {0}", e.Message); return false; } return true; } #endregion Integration } }